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).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s