Skip to content

Instantly share code, notes, and snippets.

@jonseymour
Created February 2, 2012 11:19
Show Gist options
  • Save jonseymour/1722976 to your computer and use it in GitHub Desktop.
Save jonseymour/1722976 to your computer and use it in GitHub Desktop.
NameSpaceWalker - utility for dumping a web application's JNDI context to the servlet context log
package org.jonseymour.servlet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
public class NameSpaceWalker {
/**
* Recursively dump the JNDI namespace of a webapp to the servlet context log.
* <p>
* To use, add:
*
* <xmp>
* <listener>
* <listener-class>org.jonseymour.servlet.NameSpaceWalker$ServletContextListener</listener-class>
* </listener>
* </xmp>
*
* to your web.xml
*
* @author jonseymour
*/
static public class ServletContextListener implements javax.servlet.ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
public void contextInitialized(final ServletContextEvent arg0) {
final ServletContext servletContext = arg0.getServletContext();
try
{
final NameSpaceWalker walker = new NameSpaceWalker(new InitialContext())
{
protected void log(final String msg)
{
servletContext.log(msg);
}
};
walker.walk();
}
catch (NamingException e)
{
servletContext.log(e.getMessage(), e);
}
}
}
private final Context context;
public NameSpaceWalker(final Context context)
{
this.context = context;
}
public void walk(final String contextName)
{
try {
final NamingEnumeration<NameClassPair> names = context
.list(contextName);
for (; names.hasMore();) {
final NameClassPair name;
final String bindingName;
final String className;
final String fullName;
name = names.next();
bindingName = name.getName();
className = name.getClassName();
if (contextName.endsWith(":")) {
fullName = contextName + bindingName;
} else {
fullName = contextName + "/" + bindingName;
}
log("JNDI name " + fullName + "," + className);
walk(fullName);
}
} catch (NamingException n) {
log("not a naming context: " + contextName);
}
}
public void walk()
{
walk("java:");
walk("ejblocal:");
}
protected void log(final String msg)
{
Logger.getLogger(NameSpaceWalker.class.getName()).log(Level.INFO, msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment