Monthly Archives: April 2010

JDBC connections under an oppressive regime

If you are using tomcat in an environment where you are not allowed to view the data source configurations, it can be frustrating.  Fortunately, when you need to debug, there’s a programmatic way to get the configuration.  Here’s a sample:

<%@page import="javax.naming.InitialContext" %>
<%@page import="javax.naming.Context" %>
<%@page import="javax.naming.NamingEnumeration" %>
<%@page import="javax.naming.NameClassPair" %>
<%@page import="org.apache.tomcat.dbcp.dbcp.BasicDataSource" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <body>
      <ul>
      <%
      if ("alwold".equals(request.getRemoteUser())) {
        InitialContext ic = new InitialContext();
        NamingEnumeration<NameClassPair> ne = ic.list("java:comp/env/jdbc");
        while (ne.hasMore()) {
          NameClassPair ncp = ne.next();
          Object o = ic.lookup("java:comp/env/jdbc/"+ncp.getName());
          if (o instanceof BasicDataSource) {
            BasicDataSource ds = (BasicDataSource) o;
            out.println("<li>"+ncp.getName()+"</li><ul>");
            out.println("<li>"+ds.getUrl()+"</li>");
            out.println("<li>"+ds.getUsername()+"</li>");
            out.println("<li>"+ds.getPassword()+"</li>");
            out.println("</ul>");
          } else {
            out.println("<li>found odd object "+ncp.getName()+" of type "+o.getClass().getName());
          }
        }
        }

      %>
      </ul>
    </body>
</html>

It’s particularly important to have the part that checks for remote user, because this thing is printing out passwords to the screen. You’ll have to put some sort of filter to set the remote user and then replace my username with yours (or come up with some entirely different protection mechanism).

Apache Commons

If you are a Java developer, and you don’t know about Apache Commons, you should take a minute to check it out.  A lot of times when you need to write some mundane code to do something, and you are thinking to yourself, “I’m sure a million other people have had to write this code”, you should take a quick look at commons to see if they did it.  A lot of times they have it packaged up in a nice library.  One of my favorites is the IOUtils class in commons-io, which can pull an InputStream into a String object in one line of code, but they have a bunch of other stuff that is useful as well.