Monday, August 01, 2005

A piece of Java code to walk a JNDI tree in a Servlet

public void doGet(...){
...

InitialContext initialContext;
StringBuffer sb
try {
sb = new StringBuffer();
initialContext = new InitialContext();

loopLevel(sb, initialContext, "java:comp");

} catch (NamingException e) {
writer.println("<html><body>");
e.printStackTrace(writer);
writer.println("</html></body>");
} catch (Exception e) {
}
writer.println("<html><body>" + sb.toString() + "</html></body>");

}

private void loopLevel(StringBuffer sb, InitialContext initialContext, String name){
try {
NamingEnumeration ne = initialContext.list(name);

sb.append("<ul>");

while (ne.hasMoreElements()) {
NameClassPair ncp = (NameClassPair) ne.nextElement();
sb.append("<li> " + ncp.getName());
loopLevel(sb, initialContext, name + "/" + ncp.getName());
}
sb.append("</ul>");
} catch (NamingException e) {
e.printStackTrace();
}
}

No comments: