Thursday, July 15, 2010

Storing and Retrieving an Object with JNDI

In this article, I'm gonna talk about how to store and retrieve an object with JNDI. To make it easier, I'll use File System provider which can be downloaded from
http://java.sun.com/products/jndi/downloads/index.html

Let's do the world famous Hello World application.

Hello.java
1
2
3
4
5
6
package myproject;
 
public interface Hello {
     
    public String getMessage();
}

HelloImpl.java
1
2
3
4
5
6
7
8
9
package myproject;
 
public class HelloImpl implements Hello {
     
    @Override
    public String getMessage() {
        return "Hello World";
    }
}

HelloFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package myproject;
 
import java.util.Hashtable;
 
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;
 
public class HelloFactory implements ObjectFactory {
 
    @Override
    public Object getObjectInstance(Object obj, Name name, Context nameCtx,
            Hashtable<?, ?> environment) throws Exception {
        return new HelloImpl();
    }
}
This class is responsible in creating an instance of Hello.

Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package myproject;
 
import java.util.Hashtable;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Reference;
 
public class Main {
 
    public static void main(String[] args) throws Exception {
        Hashtable<String, String> env = new Hashtable<string, string="">();
        env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.fscontext.RefFSContextFactory");
        env.put(Context.PROVIDER_URL, "file:///C:/test");
        InitialContext ic = new InitialContext(env);
        Reference ref = new Reference(Hello.class.getName(),
            HelloFactory.class.getName(), null);
        ic.rebind("whatever/object", ref);
         
        System.out.println(((Hello) ic.lookup("whatever/object")).getMessage());
    }
}
</string,>

No comments:

Post a Comment