Senin, 03 Desember 2012

JNDI look-up JBOSS 7

I used to access JNDI lookup for datasource in JBOSS AS 5 as well as JBOSS AS 6 by using this way:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
try {
Context ctx = new InitialContext(props);
DataSource ds = (DataSource) ctx.lookup("java:jboss/datasources/ConcordeDS");
connection = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
view raw x@da1 hosted with ❤ by GitHub
Unfortunately, it seems doesn't work in AS 7, as it produces error:
javax.naming.NamingException: JBAS011843: Failed instantiate InitialContextFactory org.jboss.naming.remote.client.InitialContextFactory from classloader ModuleClassLoader for Module "deployment.omega.war:main" from Service Module Loader

Thanks to this link, the solution is quite simple, only put the INITIAL_CONTEXT_FACTORY to org.jboss.as.naming.InitialContextFactory.

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory");
try {
Context ctx = new InitialContext(props);
DataSource ds = (DataSource) ctx.lookup("java:jboss/datasources/ConcordeDS");
connection = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
view raw x@da2 hosted with ❤ by GitHub
One additional note, put the JNDI name with prefix java:/ or java:jboss/.