Search code examples
javaactive-directoryldapjndi

Iterate LDAP Search Result


I amn't much familiar with the Java LDAP api. What I am trying to achieve here is to query all Groups Under an OU and also the list of users under each group.

Something like

Group_1
g1_member_1 
g1_member_2 
g1_member_3
Group_2 
g2_member_1 
g2_member_2

etc.

I am using the below code snippet. Not sure how I should be iterating the search results.

 String[] attrs = {"dn","cn","member"};
 SearchControls controls = new SearchControls();
 controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
 controls.setReturningAttributes(attrs);
 NamingEnumeration<SearchResult> results = lContext.search(ou, "cn=*", controls);
 while (results.hasMore()){
  SearchResult result = results.next();
  System.out.println(result.getNameInNamespace());
 }

Currently, when I print the result.getNameInNamespace(), I get the dn. I am interested in the cn and also the members per cn.

Should I be doing an iterative search here? Meaning for each group returned, do I initiate a new search again for the users? Isn't there a way to get it all in one query?


Solution

  • Was able to get it working with the below changes.

     String[] attrs = {"dn","cn","member"};
     SearchControls controls = new SearchControls();
     controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
     controls.setReturningAttributes(attrs);
     NamingEnumeration<SearchResult> results = lContext.search(ou, "(&(objectClass=group))", controls);
     while (results.hasMore()){
      SearchResult result = results.next();
      System.out.println(result.getNameInNamespace());
      Attributes attributes = result.getAttributes();
      System.out.println("DN "+result.getNameInNamespace());
      System.out.println("CN "+attributes.get("cn"));
      System.out.println("MEMBER "+attributes.get("member"));
      System.out.println("**********************");
     }
    

    Iterate over the member attribute to handle each user separate.