Search code examples
javajdbcjbossjndi

How to retrieve a DataSource from JBoss via JNDI


What I am trying to do is to retrieve a DataSource from a locally running JBoss (EAP 5.1) per JNDI. It works fine inside a deployed DAO, but I seem to misunderstand something as when I am trying to get the DataSource in a test case, I keep getting a javax.naming.NoInitialContextException when trying

        Properties env = new Properties();
        env.put(Context.PROVIDER_URL, "jnp://localhost:1099");

        final InitialContext ic = new InitialContext(env);
        ds = (DataSource) ic.lookup(DATASOURCE_NAME);  

If i add

        env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");

I get a ClassNotFoundException for the org.jnp.interfaces.NamingContextFactory

Being new to JNDI and JBoss, I'm stuck at that point. Searching the web just adds to my confusion as all I find are scattered pieces of info that I try to apply by trial-and-error with no real progress.

Thank you


Solution

  • What functionality is it that you are testing? Is it the retrieval of a DataSource or some actual database code? If the latter, then I would suggest not using JNDI at all and using a local DataSource implementation.

    This thread shows how to use Commons DBCP to set up local DataSources.

    http://forum.springsource.org/showthread.php?16670-Problem-running-JUNIT-test-with-JNDI-datasource

    If you really need the JNDI aspect, this example shows how to populate an InitialContext with a minimum of values to get a DataSource back. You can probably use the same Commons DBCP config as above to configure the DataSource(s) that you need.

    http://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit