Search code examples
tomcatjndi

Changing embedded Tomcat from v6 to v7 causes InitialContext lookup to fail


I'm using JUnit test cases to exercise my web service using embedded Tomcat. Under Tomcat 6 everything was working fine, but when I switched my project to Tomcat 7 I'm coming unstuck.

The test code to setup the embedded Tomcat server is as follows:

Tomcat 6

Embedded container = new Embedded();
container.setCatalinaHome("C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0.11");
container.setRealm(new MemoryRealm());
container.setName("Catalina");
Engine engine = container.createEngine();
container.addEngine(engine);
Host host = container.createHost("localhost", "/DecoderServiceTest");
Context rootContext = container.createContext("/DecoderServiceTest", System.getProperty("user.dir") + "/build/web");
host.addChild(rootContext);
engine.setName("Catalina");
engine.addChild(host);
engine.setDefaultHost("localhost");
container.addEngine(engine);
Connector connector = container.createConnector(InetAddress.getLocalHost(), 4321, false);
container.addConnector(connector);
container.start();

As the embedded API has changed between versions 6 and 7, I've changed my own code to the following:

Tomcat 7

Tomcat tomcat = new Tomcat();
tomcat.setBaseDir("C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0.11");
tomcat.setPort(1234);
tomcat.addWebApp("/DecoderServiceTest", System.getProperty("user.dir")+"/build/web");
tomcat.setHostname("localhost");
tomcat.start();

The actual web service starts up fine when I execute the JUnit test (I can use my web browser and see the WSDL being served up).

However, in the constructor of my web service I intialise some variables based on the values in the web.xml file (which is located in System.getProperty("user.dir")+"/build/web/WEB-INF/web.xml"), as follows:

  Context initCtx = new InitialContext();
  Context envCtx = (Context) initCtx.lookup("java:comp/env");
  int thumbnailSize = (Integer) envCtx.lookup("thumbnail-pixel-size");

Where my web.xml file contains the following entry:

<env-entry>
  <env-entry-name>thumbnail-pixel-size</env-entry-name>
  <env-entry-type>java.lang.Integer</env-entry-type>
  <env-entry-value>64</env-entry-value>
</env-entry>

When I try and create the envCtx object I get a NamingException with the message that Name java:comp is not bound in this Context. I'm confused because it worked fine with Tomcat 6. Have I missed something in the setup of Tomcat 7 that I had previously defined in the setup of Tomcat 6?


Solution

  • Mark Thomas via the tomcat-users mailing list suggested

    tomcat.enableNaming();
    

    before the server is started. This worked for me (I guess they changed the default behaviour between 6 and 7).