Monday, August 18, 2008

List JNDI Names

Sometimes we need to list all the JNDI names in an application server for debugging purpose. Other times, we may wish to list available datasources in a dropdown list for end-users to choose from. How to do this? In a nutshell, the JNDI bindings are organized in a tree strucuture. The following code is a simple example to recursively exhaust this binding tree:


Context ctx = (Context)new InitialContext().lookup("java:comp/env");
listContext(ctx, "");

/**
* Recursively exhaust the JNDI tree
*/
private static final void listContext(Context ctx, String indent) {
try {
NamingEnumeration list = ctx.listBindings("");
while (list.hasMore()) {
Binding item = (Binding) list.next();
String className = item.getClassName();
String name = item.getName();
logger.log(Level.INFO, indent + className + " " + name);
Object o = item.getObject();
if (o instanceof javax.naming.Context) {
listContext((Context) o, indent + " ");
}
}
} catch (NamingException ex) {
logger.log(Level.WARNING, "JNDI failure: ", ex);
}

3 comments:

  1. java:comp/env is standard across all env ? I'm getting

    javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
    at javax.naming.InitialContext.lookup(InitialContext.java:411)

    ReplyDelete
  2. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete