Connecting to ApacheDS with Java components
Which option to choose?
JNDI
A natural choice for LDAP integration in Java components is JNDI, the Java Naming and Directory Interface. It has been part of the J2SE since version 1.3, and it is available as a separate download for even more ancient JDKs.
JNDI offers a common interface to connect to different naming and directory services, including DNS, file systems, CORBA naming services and LDAP. Therefore it represents an abstraction layer, which sometimes causes trouble if special LDAP features have to be exploited.
"Native" LDAP libraries for Java
On the other hand several libraries exist which take advantage of the basic Java network functionality directly. The interfaces are organized the LDAP protocol operations, which leads to an LDAP programming experience without abstraction. Examples for pure Java libraries like that are
- Netscape Directory SDK for Java
- JLDAP, derived from Novell Developer Kit
But because JNDI is present in practically every Java runtime environment, these libraries are not widely used any longer, although they have some advantages versus JNDI.
A first example with JNDI
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.InitialDirContext; public class SimpleJndiExample { public static void main(String[] args) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://zanzibar:10389/o=sevenSeas"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); InitialDirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(""); NamingEnumeration enm = attrs.getAll(); while (enm.hasMore()) { System.out.println(enm.next()); } } }
Output:
$ java SimpleJndiExample objectClass: organization, top description: Contains Apache Directory Tutorial example data o: sevenSeas $
An excellent resource to learn more about JNDI is the JNDI Tutorial at Sun Microsystems.
Resources
- JNDI Tutorial at Sun Micosystems
- LDAP Programming with Java by Rob Weltman and Tony Dahbura (Addison-Wesley Professional 2000) focuses on Netscape SDK