Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tomcat embedded: NoInitialContextException when trying to get a DataSource

Tags:

java

tomcat

jdbc

I have a JSF web application that I'd like to run using tomcat embedded. It's working so far [including JDBCRealm, specified in the context.xml in the following code snippet], except after login my code is unable to actually get the connection resource specified in the source, throwing a NoInitialContextException.

I'm probably missing something obvious, but there seems to be very little traffic out there regarding tomcat embedded. [Tomcat7.0.47, JDK7].

As per other questions on this site on this site, I've tried a number of variants on adding an initial environment, but I haven't been able to figure out if that's really my problem, or I just haven't found the right incantation for this tomcat server, yet.

Tomcat launching code:

tomcat = new Tomcat();
tomcat.setPort(port);
tomcat.setBaseDir(".");
Context ctx = tomcat.addWebapp("/" + appname, appname);
// The login realm specified in this XML file is a JDBC realm, and the server correctly logs users in, so I believe this is parsed.
ctx.setConfigFile(new URL("file:///home/chunky/src/aqmt/AQMTEmbed/webapps/AQMTWeb/META-INF/context.xml"));

ContextResource resource = new ContextResource();
resource.setName("jdbc/aqmtwebdb");
resource.setAuth("Container");
resource.setType("javax.sql.DataSource");
resource.setScope("Sharable");
resource.setProperty("driverClassName", "com.mysql.jdbc.Driver");
resource.setProperty("url", "jdbc:mysql://localhost:3306/aqmtweb?autoreconnect=true");
resource.setProperty("username", "username");
resource.setProperty("password", "password");
ctx.getNamingResources().addResource(resource);

tomcat.start();

In the web application itself is this:

InitialContext ctx = new InitialContext();
// This line here throws the exception:
DataSource webds = (DataSource)ctx.lookup("java:/comp/env/jdbc/aqmtwebdb");

The exception thrown is:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
    at javax.naming.InitialContext.lookup(InitialContext.java:411)
    at org.rand.aqmt.UserBean.<init>(UserBean.java:77)

[where line UserBean.java:77 is the ctx.lookup() above]

I'm fairly at a loss as to how to progress.

like image 726
Gary B Avatar asked Jan 20 '14 19:01

Gary B


1 Answers

Evidently I just needed Tomcat.enableNaming(), which isn't enabled by default.

like image 196
Gary B Avatar answered Oct 19 '22 11:10

Gary B