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
package myproject;

public interface Hello { 
    
    public String getMessage(); 
} 

HelloImpl.java
package myproject;

public class HelloImpl implements Hello { 
    
    @Override 
    public String getMessage() { 
        return "Hello World"; 
    } 
} 

HelloFactory.java
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
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(); 
        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()); 
    } 
} 

No comments:

Post a Comment