Previous | Next | Trail Map | Building a Service Provider | The Essential Components

Implementing an Initial Context Factory

The Preparations (in the Basics trail) lesson describes how to set up an initial context to access naming/directory services via the JNDI. For example, to use Sun's LDAP provider, use code that looks as follows.
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=jnditutorial");
Context ctx = new InitialContext(env);

// ... do something useful with ctx
The InitialContext(in the API reference documentation) class is just a wrapper class that accesses the real context implementation--the Context instance created by the initial context factory class named by the Context.INITIAL_CONTEXT_FACTORY(in the API reference documentation) ("java.naming.factory.initial") environment property. This factory class must implement the InitialContextFactory(in the API reference documentation) interface. In the previous example, the initial context factory class is com.sun.jndi.ldap.LdapCtxFactory.

For a context implementation to be accessible from the initial context, a service provider must provide a class that implements the InitialContextFactory interface. Here is an example of an initial context factory for the hierarchical namespace example.

public class InitCtxFactory implements InitialContextFactory {

    public Context getInitialContext(Hashtable env) {
        return new HierCtx(env);
    }
}
This example is very simple. It calls the HierCtx constructor and returns an empty context. In an actual implementation, the initial context factory must create a Context instance for reaching all other parts of the namespace of the underlying naming/directory service. Also, an actual implementation would typically use the Context.PROVIDER_URL(in the API reference documentation) ("java.naming.provider.url") environment property to initialize the initial context. For example, in Sun's LDAP provider, the Context.PROVIDER_URL property indicates directory server's machine address and port, as well as the DN (distinguished name) of root naming context to use. In the previous example, the machine address and port are localhost and 389 and the DN is "o=jnditutorial".

The Essential Components: End of Lesson

What's next? Now you can:


Previous | Next | Trail Map | Building a Service Provider | The Essential Components