如何从Ldap中的给定组中提取所有成员的电子邮件地址

时间:2019-12-16 09:10:11

标签: java ldap

我必须从LDAP提取组中所有成员的电子邮件ID。 我的网上论坛名称是 reportMember(字符串groupName = reportMember;),我想让该网上论坛的所有用户都收到他们的电子邮件地址。所以我写了一个代码来得到它。 我提供的查询为:“ String searchFilter =” cn =“ + groupName; ”。该查询为我提供了该组所有成员的名称,为:

member1:CN = Alex,OU = InfoWorker,OU = People,DC = abc,DC = xyz,DC = com

member2:......等等。

但是通过此查询,我将无法获得我的代码在下面的那些成员的电子邮件地址。

非常感谢。

代码:

public List<LDAPUser> searchGroupDetails(String currentUserName, String groupName) {

List<LDAPUser> LDAPUsers=new ArrayList<LDAPUser>();
        ArrayList<String> listOfMembersInGroup= new ArrayList<String>();
        int maxResults=Integer.parseInt("2000");
        DirContext dirSearchContext = utilusr.getLDAPDirContext().get(currentUserName);

        String searchbase = "DC=abc,DC=xyz,DC=com";
        String searchFilter="cn="+groupName;
                String member="";
        try{
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);       
            searchCtls.setReturningAttributes(returnAttributes);

            try{
                NamingEnumeration<?> users = dirSearchContext.search(searchbase, searchFilter, searchCtls);
                if(users.hasMoreElements() == false){
                    System.out.println("Not find any object with this filter " + searchFilter + " and searchBase " + searchbase);
                }

                int k = 0;
                String attValue = "";


                while (users.hasMoreElements()){

                    if(k >= maxResults)
                        break;           
                    SearchResult sr = (SearchResult)users.next();
                    Attributes attrs = sr.getAttributes();
                    if (attrs.size() == 0){
                        System.out.println("Could not find attribute " + returnAttributes[0] + " for this object.");
                    }else{

                        try{       
                            //-- Code to extract members of a given group Start.
                            for (NamingEnumeration<?> ae = attrs.getAll();ae.hasMore();){ 
                                Attribute attr = (Attribute)ae.next();                 
                                String id = attr.getID();


                                for (NamingEnumeration<?> e = attr.getAll();e.hasMore();){                      
                                    attValue = (String)e.next();


                                    if(id.equalsIgnoreCase("member")){
                                        member = attValue;
                                        System.out.println("member :"+member);
                                        String memberName=member.substring(member.indexOf("=")+1, member.indexOf(","));
                                        listOfMembersInGroup.add(memberName);
                                    }
                                    //-- Code to extract members of a given group Ends.
                                    else
                                    {
                                        System.out.println("empty");
                                    }
                                }
                            }
                        }catch(NamingException e){
                            e.printStackTrace();

                        }     
                    }
                    k++;
                }

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

            }       
            dirSearchContext=null;   
        }catch (Exception e){
            e.printStackTrace();

        } 

}

2 个答案:

答案 0 :(得分:0)

假设是否有Microsoft Active Directory(或是否为memberOF,因为您没有透露)

类似的事情应该起作用(当然,要与您的环境mods兼容)

String[] attrIDs = {"mail"};
String groupName = "reportMember";
String groupDN = "CN=Groups,DC=abc,DC=xyz,DC=com"; // Where groups are in LDAP
Attributes matchAttrs = new BasicAttributes(true); // ignore case
    matchAttrs.put(new BasicAttribute("memberOf", "CN=" + groupName + ","+ groupDN)); // finds group by CN Value 

String searchFilter = "(&(objectCategory=Person)(objectClass=User)(memberOf=" + groupDN + "))";

SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls, attrIDs);

while (results.hasMore()) {
    SearchResult result = results.next();
    Attributes attributes = result.getAttributes();
    Attribute email = attributes.get("mail");
    System.out.println(email);
    //get/iterate the values of the attribute
}

System.out.println("DONE");

答案 1 :(得分:0)

public List<LDAPUser> search_MemberAndEmailAddresFromGroup(String currentUserName, String groupName) {

        UserSingleton utilusr = UserSingleton.getInstance(); 
        List<LDAPUser> LDAPUsers=new ArrayList<LDAPUser>();
        ArrayList<String> listOfMembersInGroup= new ArrayList<String>();
        int maxResults=Integer.parseInt("2000");
        DirContext dirSearchContext = utilusr.getLDAPDirContext().get(currentUserName);//TODO call the singleton to get this object


        String searchbase = "DC=ABC,DC=LMN,DC=XYZ";
        String searchFilter="cn="+groupName;

        String member="";
        try{
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);       
            searchCtls.setReturningAttributes(returnAttributes);

            try{
                NamingEnumeration<?> membersOfGroup = dirSearchContext.search(searchbase, searchFilter, searchCtls);
                if(membersOfGroup.hasMoreElements() == false){
                    System.out.println("Not find any object/members with this filter " + searchFilter + " and searchBase " + searchbase);
                }

                int k = 0;
                String attValue = "";

                while (membersOfGroup.hasMoreElements()){
                    if(k >= maxResults)
                        break;           
                    SearchResult sr = (SearchResult)membersOfGroup.next();
                    Attributes attrs = sr.getAttributes();
                    if (attrs.size() == 0){
                        System.out.println("Could not find attribute " + returnAttributes[0] + " for this object.");
                    }else{

                        try{       
                            //-- Code to extract members of a given group Start.
                            for (NamingEnumeration<?> ae = attrs.getAll();ae.hasMore();){ 
                                Attribute attr = (Attribute)ae.next();                 
                                String id = attr.getID();

                                for (NamingEnumeration<?> e = attr.getAll();e.hasMore();){                      
                                    attValue = (String)e.next();

                                    if(id.equalsIgnoreCase("member")){
                                        member = attValue;
                                        String memberName=member.substring(member.indexOf("=")+1, member.indexOf(","));
                                        System.out.println("member Name is: "+memberName);
                                        listOfMembersInGroup.add(memberName);//-- adding member name in a list
                                    }
                                    //-- Code to extract members of a given group Ends.
                                    else
                                    {
                                        System.out.println("empty");
                                    }
                                }
                            }
                        }catch(NamingException e){
                            e.printStackTrace();
                            System.out.println("Problem listing membership:"+e);            
                        }     
                    }
                    k++;
                }
                //--After getting member name of a group extracting their email_Id code start
                if((listOfMembersInGroup!=null)||(!(listOfMembersInGroup.isEmpty()))){

                    for(String name:listOfMembersInGroup){
                        searchFilter="(name="+name.replace(" ", "\\ ")+")";
                        System.out.println("Search Filter to find email address of a member: "+searchFilter);
                        queryRes = dirSearchContext.search(searchbase, searchFilter, searchCtls);
                        while (queryRes.hasMoreElements()){
                            SearchResult srchResObj = (SearchResult) queryRes.next();
                            Attributes attributesList = srchResObj.getAttributes();

                            if (attributesList != null) {
                                if(attributesList.get("mail") !=null && attributesList.get("memberOf")!=null){
                                    if(attributesList.get("memberOf").toString().split(":")[1].trim().contains(groupName)){
                                        System.out.println(attributesList.get("mail").toString().split(":")[1].trim());

                                        LDAPUser user=new LDAPUser();
                                        user.setEmail(attributesList.get("mail").toString().split(":")[1].trim());
                                        user.setUserName(attributesList.get("displayname").toString().split(":")[1].trim());
                                        LDAPUsers.add(user);
                                    }
                                }
                            }
                        }
                    }
                }
                //--After getting member name of a group extracting their email_Id code End
            }catch (NamingException e){
                e.printStackTrace();
                System.out.println("Problem searching directory: "+e);            
            }       

        }catch (Exception e){
            e.printStackTrace();
            System.out.println("Exception while fetching the users from LDAP::"+e);        
        }     
        return LDAPUsers;
    }