Monday, March 4, 2013

Query OpenLDAP from Java using JNDI

Description: Uses Java Naming and Directory (JNDI) to connect to OpenLDAP in a Java application and query entries.

import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;

/**
* Connect to OpenLDAP and query the directory using Java Naming 
* and Directory (JNDI).
*/
public class DirectoryConnection
{
    public static void main(String[] args) throws NamingException
    {
        //LDAP information
        String ldapServerName = "localhost";
        String ldapProviderURL = "ldap://" + ldapServerName + ":389";
        String username = "cn=Manager,dc=my-domain,dc=com";
        String password = "secret";

        //Set LDAP information in a properties object
        Properties properties = new Properties();
        properties.put(Context.SECURITY_AUTHENTICATION, "simple");
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        properties.put(Context.PROVIDER_URL, ldapProviderURL);
        properties.put(Context.SECURITY_PRINCIPAL, username);
        properties.put(Context.SECURITY_CREDENTIALS, password);

        //Initializing LDAP connection
        InitialDirContext ctx = new InitialDirContext(properties);

        //Create the search controls
        SearchControls searchCtls = new SearchControls();

        //Specify the attributes to return
        String[] returnAttrs = {"cn", "sn", "uid"};
        searchCtls.setReturningAttributes(returnAttrs);

        //Specifiy the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        //Specifiy the LDAP search filter
        String searchFilter = "(&(uid=*))";

        //Specify the base foe the search
        String searchBase = "ou=people,dc=my-domain,dc=com";

        //initialize counter to total the results
        int totalResults = 0;

        //Search for objects using the filter
        NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

        //Loop through the search results
        while(answer.hasMoreElements())
        {
            javax.naming.directory.SearchResult sr = (javax.naming.directory.SearchResult) answer.next();
            totalResults++;
            System.out.println(">>>" + sr.getName());
            Attributes attrs = sr.getAttributes();

            //Print out some of the attributes
            if(attrs != null)
            {
                System.out.println(attrs.get("sn"));
                System.out.println(attrs.get("cn"));
            }
        }

        System.out.println(totalResults);
    }
}

No comments:

Post a Comment