We get asked about how to do things in JNDI for LDAP on a regular basis.

We put together these short examples to try to help out.

Of course all of this is very dependent on your own LDAP implementation and is subject to our Standard Disclaimer

The JNDI Example was done for Microsoft Active Directory and some items are AD specific.

package temp;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class Test
{
    String ldapHostUrl = "ldap://laura.willeke.com:389";
    String ldapBaseForusers = "CN=Users,DC=mad,DC=willeke,DC=com";
    String ldapBaseForDomain = "DC=mad,DC=willeke,DC=com";
    String ldapBindDN = "CN=Nick James,CN=Users,DC=mad,DC=willeke,DC=com";
    String ldapBindPwd = "password";
    String ldapUserIDAttribute = "samAccountName";
    String ldapContainerIDAttribute = "name";

    public Test()
    {
	// TODO Auto-generated constructor stub
    }

    /**
     * Generic method to obtain a reference to a DirContext
     */
    public DirContext getDirContext() throws Exception
    {
	Hashtable<String, String> env = new Hashtable<String, String>(11);
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.PROVIDER_URL, ldapHostUrl);
	// Authenticate as S. User and password "mysecret"
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, ldapBindDN);
	env.put(Context.SECURITY_CREDENTIALS, ldapBindPwd);
	// Create the initial context
	DirContext ctx = new InitialDirContext(env);
	return ctx;
    }

    /**
     * 
     * @param stid
     *            String - Standard ID (userID)
     * @throws Exception
     *             -
     */
    public void doFindEntries(String stid, String searchAttribute, String searchBase) throws Exception
    {
	DirContext ctx = getDirContext();
	Attributes matchAttrs = new BasicAttributes(true); // ignore attribute name case
	matchAttrs.put(new BasicAttribute(searchAttribute, stid));
	// Search for objects with those matching attributes
	NamingEnumeration answer = ctx.search(searchBase, matchAttrs);
	formatResults(answer);
	ctx.close();
    }

    public String getDN(String name) throws NamingException, Exception
    {
	String dn = null;
	NamingEnumeration results = getDirContext().search(ldapBaseForusers, "(name=" + name + ")", null);
	if (results != null && results.hasMore())
	{
	    SearchResult si = (SearchResult) results.next();
	    dn = si.getNameInNamespace();
	}
	return dn;

    }

    /*
     * Generic method to format the NamingEnumeration returned from a search.
     */
    public void formatResults(NamingEnumeration enumer) throws Exception
    {
	int count = 0;
	try
	{
	    while (enumer.hasMore())
	    {
		SearchResult sr = (SearchResult) enumer.next();
		System.out.println("SEARCH RESULT:" + sr.getName());
		formatAttributes(sr.getAttributes());
		System.out.println("====================================================");
		count++;
	    }
	    System.out.println("Search returned " + count + " results");
	}
	catch (NamingException e)
	{
	    if (e instanceof javax.naming.PartialResultException)
	    {
		// ignore
	    }
	    else
	    {
		e.printStackTrace();
	    }
	}
    }

    /*
     * Generic method to format the Attributes .Displays all the multiple values of each Attribute in the Attributes
     */
    public void formatAttributes(Attributes attrs) throws Exception
    {
	if (attrs == null)
	{
	    System.out.println("This result has no attributes");
	}
	else
	{
	    try
	    {
		for (NamingEnumeration enumer = attrs.getAll(); enumer.hasMore();)
		{
		    Attribute attrib = (Attribute) enumer.next();
		    System.out.println("ATTRIBUTE :" + attrib.getID());

		    try
		    {
			for (NamingEnumeration e = attrib.getAll(); e.hasMore();)
			{
			    System.out.println("\t\t        = " + e.next());
			}
		    }
		    catch (Exception e)
		    {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		}
	    }
	    catch (NamingException e)
	    {
		e.printStackTrace();
	    }
	}
    }

    private OrganizationalUnitNode getOrganizationalUnits(String rootOu, String searchFilter, SearchControls searchCtls, OrganizationalUnitNode root)
    {
	// TODO Auto-generated method stub
	return null;
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {
	Test test = new Test();
	// /Find a user
	System.out.println();
	System.out.println("Find All users by test.ldapUserIDAttribute:");
	System.out.println("====================================================");

	try
	{
	    test.doFindEntries("molly", test.ldapUserIDAttribute, test.ldapBaseForusers);

	}
	catch (javax.naming.PartialResultException e)
	{
	    // ignore
	}
	catch (Exception e)
	{
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	// Now look for container by name
	System.out.println();
	System.out.println("Find user by Name:");
	System.out.println("====================================================");

	try
	{
	    test.doFindEntries("users", test.ldapContainerIDAttribute, test.ldapBaseForDomain);
	}
	catch (Exception e)
	{
	    if (e instanceof javax.naming.PartialResultException)
	    {
		// ignore
	    }
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	System.out.println();
	System.out.println("Find user DN by Name:");
	System.out.println("====================================================");
	try
	{
	    System.out.println("DN: " + test.getDN("molly"));
	}
	catch (NamingException e)
	{
	    if (e instanceof javax.naming.PartialResultException)
	    {
		// ignore
	    }
	    else
	    {
		e.printStackTrace();
	    }
	}
	catch (Exception e)
	{
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }
}

Still Need Help?#

We do Custom LDAP Tools and can help regardless JNDI or Java or C#.

javax.naming.PartialResultException#

This is a common condition often encountered when using Microsoft Active Directory as there are often referrals to other location like the GAL.

We do not recommend jut throwing these away in a "real" implementation.

if (e instanceof javax.naming.PartialResultException)
{
  // ignore
}

More Information#

There might be more information for this subject on one of the following:

Add new attachment

Only authorized users are allowed to upload new attachments.
« This page (revision-11) was last changed on 13-Jul-2016 18:05 by jim