Working With JNDI In A J2SE Application

Java Naming and Directory Interface (JNDI) allows Java objects to be published to a directory service which can be accessed by other Java applications later. For this to work you need a JNDI service provider. All the J2EE servers come with a built-in implementation of the JNDI service. This makes most people assume that you can work with JNDI only in J2EE ecosystem. It is possible for you to set up your own lightweight JNDI server, great number your J2SE objects on this and make these objects obtainable for other’s use. There are varieties of JNDI service providers obtainable. In this article, I am going to refer to the one provided by JBOSS.

The following .jar files must be additional to your classpath in order to setup the server, great number an object, and to access the same.

1) log4j.jar

2) jnpserver.jar

3) jboss-shared.jar

4) concurrent.jar

In addition, you must also have the log4j.similarities file in your classpath. These files are obtainable with the Jboss binary dispensing.

To setup the ecosystem you can also kind the following in a text file (setJNPEnv.cmd)

set JNP_HOME=C:jnp

set JNP_LIB=%JNP_HOME%lib

set JNP_PATH=%JNP_LIB%;%JNP_LIB%log4j.jar

set JNP_PATH=%JNP_PATH%;%JNP_LIB%jnpserver.jar

set JNP_PATH=%JNP_PATH%;%JNP_LIB%jboss-shared.jar

set JNP_PATH=%JNP_PATH%;%JNP_LIB%concurrent.jar

set CLASSPATH=.;%JNP_PATH%;%CLASSPATH%

Make sure to change the JNP_HOME ecosystem variable’s value to the folder, where you have extracted the jnp.zip.

To start the JNDI service, open a command prompt and kind the following command:

c:work>setJNPEnv.cmd

c:work>start java org.jnp.server.Main

This opens a new window which represents the JNP (Jboss Naming Provider) server listening at port 1099.

Now you can store any object you want in the JNDI using the code below:

Context ctx=new InitialContext();

ctx.rebind(“name1”, “Vinod”);

ctx.rebind(“person1”, new Person(“Vinod”, “Bangalore”));

Also, you can lookup and acquire an object using the code below:

Context ctx=new InitialContext();

String name=(String) ctx.lookup(“name1”);

Person p1=(Person) ctx.lookup(“person1”);

One last thing. You must provide the information about JNDI provider when you call new InitialContext(). This is usually done by placing a jndi.similarities file in you working directory or supplying a java.util.Map object. Here is the content of jndi.similarities file:

java.naming.provider.url=localhost:1099

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory

java.naming.factory.url.pkgs=org.jboss.naming

Leave a Reply