Recipe 18.5 Programming with Java

18.5.1 Problem

You want to programmatically access Active Directory using Java.

18.5.2 Solution

The Java Naming and Directory Interface (JNDI) is a standard extension to Java that can be used to access a variety of naming and directory services including DNS and LDAP. JNDI is part of the Java Enterprise API set and is documented on the following site: JNDI provides an object-oriented interface to programming with LDAP, and is not based on the LDAP C API, which many other LDAP API's are based on.

The following code uses JNDI to print out the RootDSE for the host DC1:

/**  * Print the RootDSE for DC1  * usage: java RootDSE  */ import javax.naming.*; import*; class RootDSE {     public static void main(String[] args) {         try {             // Create initial context.             DirContext ctx = new InitialDirContext( );             // Read attributes from root DSE.         Attributes attrs = ctx.getAttributes(                "ldap://DC1", new String[]{"*"});         // Get a list of the attributes.         NamingEnumeration enums = attrs.getIDs( );         // Print out each attribute and its values.         while (enums != null && enums.hasMore( )) {            String nextattr = (String) );                   System.out.println( attrs.get(nextattr) );         }                // Close the context.             ctx.close( );     } catch (NamingException e) {          e.printStackTrace( );     }   } }

18.5.3 Discussion

Any serious Java programmer should be familiar with JNDI. It is a generic interface that can be used with a variety of services, not least of which includes Active Directory. A good tutorial on JNDI is available on Sun's web site:

18.5.4 See Also

Sun's JNDI home page :

Active Directory Cookbook
Active Directory Cookbook, 3rd Edition
ISBN: 0596521103
EAN: 2147483647
Year: 2006
Pages: 456

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: