JNDI Access from Java and Jython

February 22, 2010

When using Tomcat (or any other web servlet/JEE container) you can set up configuration variables in web.xml, and then refer to them from code. The value of this variable can be set by either hardcoding it in web.xml, or by setting a value in the Tomcat configuration files.

web.xml

In web.xml, define that the value is needed by this WAR file.

<env-entry>
  <description>WebServices Location</description> 
  <env-entry-name>WebServices</env-entry-name> 
  <env-entry-value /> 
  <env-entry-type>java.lang.String</env-entry-type> 
</env-entry>

This specifies no default value.

Tomcat Config

Then, in conf/context.xml (Tomcat 6) or conf/Catalina/localhost/war_file_name.xml (Tomcat 5) define what the value is in this particular container:

<Environment description="Web Services" 
             name="WebServices" 
             type="java.lang.String" 
             value="http://localhost:8080/web-services" 
             override="false" />

Note that the name matches what is in web.xml, but the description doesn't have to.

Getting The Value in Java

To get the value in code, use the following:

public static String getJndiValue(String pName)
{
  String  lReturn = null;
  try
  {
    InitialContext lContext = new InitialContext();
    String lLookupURI = "java:comp/env/" + pName;
    lReturn = (String) lContext.lookup(lLookupURI);
  }
  catch (NamingException lEx)
  {
    throw new RuntimeException("Can't fetch " + pName + " from JNDI config");
  }
  return lReturn;
}

Note that the path in lLookupURI includes the name specified earlier, passed in as a parameter.

Getting The Value in Jython

The following code gets hold of the hostname/port of a deployed web service, reading the value from the JNDI setup.

try:
    from javax.naming import InitialContext
    lContext = InitialContext()
    lLookupURI = "java:comp/env/%s" % "WebServices";
    lWsUrl = lContext.lookup(lLookupURI);
    lRegEx = 'http://(\w+:\d+)/WebServices'
    lMatches = re.match(lRegEx, lWsUrl) 
    lHostPort = lMatches.group(1).strip()
except:
    lHostPort = "localhost:8080"

Tags: java jndi tomcat jython