This post explains how to connect to an LDAP server (in my case Apache DS) and retrieve elements that match a certain filter.
I have deployed an Apache Directory Server version 2.0 and imported the demo LDIF containing users and groups for the “sevenSeas” organization. You can download the file from the apache DS documentation.
This java code connects to the Apache DS deployed locally using the default port and user, and searches the context “ou=groups,o=sevenSeas” for groups the user “Fletcher Christian” belongs to.
publicclassLdapSearch { publicstaticvoidmain(String[] args) throwsNamingException { InitialLdapContext ctx = constructInitialLdapContext(); // the name of the context to search String contextName = "ou=groups,o=sevenSeas"; // Filter expression String filterExpr = "(uniquemember={0})"; // selects the groups a user belongs to.
// Filter parameters (name of the user) String userDN = "cn=Fletcher Christian,ou=people,o=sevenSeas"; Object[] filterArgs = { userDN };
SearchControls constraints = newjavax.naming.directory.SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); // SUBTREE_SCOPE means recursive search