Implementing an Initial Context Factory

The Preparations 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=jndidocs");
Context ctx = new InitialContext(env);

// ... do something useful with ctx
The InitialContext 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 ("java.naming.factory.initial") environment property. This factory class must implement the InitialContextFactory 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 ("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=jndidocs".

The Essential Components: End of Lesson

What's next? Now you can:

  • Continue on in this trail to learn how to add directory support.
  • Go to the Adding URL Support lesson to learn how to add pieces to the service provider for supporting URLs.
  • Go to the Adding Federation Support lesson to learn how to add federation support to a service provider.
  • Go to the Miscellaneous lesson to learn how to add various enhancements to a service provider, such as adding support for referrals and bundling factories.