Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding datasource programmatically to JNDI context in embedded tomcat 7

I'm trying to register a new datasource before the server starts but on lookup execution I'm getting

javax.naming.NameNotFoundException: Name [jdbc/db] is not bound in this Context. Unable to find [jdbc].

This is how I start tomcat:

    Tomcat tomcat = new Tomcat();
    //...
    ContextResource resource = new ContextResource();
    resource.setName("jdbc/db");
    resource.setAuth("Container");
    resource.setType("javax.sql.DataSource");
    resource.setScope("Sharable");
    resource.setProperty("driverClassName", "org.hsqldb.jdbc.JDBCDriver");
    resource.setProperty("url", "jdbc:hsqldb:hsql://localhost:1234/mydb1");

    tomcat.getServer().getGlobalNamingResources().addResource(resource);
    tomcat.start();
    tomcat.getServer().await();

The lookup:

    Connection conn = null;
    try {
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup("java:/comp/env");
        DataSource ds = (DataSource) envContext.lookup("jdbc/db");

        conn = ds.getConnection();
        conn.createStatement()....
    } catch (Exception e) {
        e.printStackTrace();
    }

What am I missing here?

like image 297
ali Avatar asked Dec 31 '13 16:12

ali


People also ask

Does Tomcat supports JNDI?

Tomcat provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java Enterprise Edition application server. The Java EE standard provides a standard set of elements in the /WEB-INF/web.


1 Answers

Oh well i figured it out! Instead of adding it in the GlobalNamingResources

tomcat.getServer().getGlobalNamingResources().addResource(resource);

I added it in the NamingResources

Context rootCtx = tomcat.addContext("", base.getAbsolutePath());
//...
rootCtx.getNamingResources().addResource(resource);

and it works!

If someone can tell me the difference between globalNamingResources and (local)NamingResources and how to lookup a globalNamingResource then please leave me a comment!

like image 175
ali Avatar answered Sep 22 '22 13:09

ali