18.5. Programming with Java

Problem

You want to programmatically access Active Directory using Java.

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: http://java.sun.com/products/jndi/. 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 javax.naming.directory.*;

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)enums.next( );
                  System.out.println( attrs.get(nextattr) );
        }
  
            // Close the context.
            ctx.close( );

    } catch (NamingException e) {
         e.printStackTrace( );
    }
  }
}

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 ...

Get Active Directory Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.