简体   繁体   中英

Get Email Addresses from Active Directory by passing Group Name in JAVA

I am trying to create a function which return Email Addresses of All Group members from Active Directory by taking Group Name as an input Parameter, the result will be a ";" separate String.

I found following code but is returning only First member Email address not all members can you please guide me what is problem in below code or is there any other way in Java to get it done : Thanks

public String fetchGroupMembers(String strGroupName)
    {
        Vector memberEmails = new Vector();
        String strEmails = "";    
        try
        { 
            //Create the initial directory context
            //DirContext ctx = new InitialDirContext(ctx);
            //Create the search controls        
            SearchControls searchCtls = new SearchControls();
            //Specify the search scope
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            //specify the LDAP search filter
            String searchFilter = "(&(objectClass=group)(CN="+strGroupName+"))";
            //Specify the Base for the search
            //String searchBase =searchBase;
            //initialize counter to total the group members
            int totalResults = 0;

            //Specify the attributes to return
            String returnedAtts[]={"member", "mail"};
            searchCtls.setReturningAttributes(returnedAtts);

            //Search for objects using the filter
            NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
            //Loop through the search results
            while (answer.hasMoreElements())
            {
                SearchResult sr = (SearchResult)answer.next();
                //System.out.println(">>>" + sr.getName());
                Attributes attrs = sr.getAttributes();
                if (attrs != null)
                {
                    try
                    {
                        for (NamingEnumeration ae = attrs.getAll();ae.hasMore();)
                        {
                            Attribute attr = (Attribute)ae.next();
                            //System.out.println("Attribute: " + attr.getID());
                            for (NamingEnumeration e = attr.getAll();e.hasMore();totalResults++)
                            {
                                String str = e.next().toString();
                                //System.out.println(" " +  totalResults + ". " + str );
                                int end = str.indexOf(",");
                                //System.out.println("end " + end);
                                if(end != -1)
                                {
                                    String str1 = str.substring(3, end);
                                    //System.out.println("Name-->>" + str1 + "<<");
                                    doFilterSearch(str1.trim(), memberEmails);
                                }
                            }
                        }
                    }    
                    catch (NamingException e)
                    {
                         e.printStackTrace();
                        System.err.println("Problem listing members: " + e);
                    } 
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("Total members: " + totalResults);
            ctx.close();
        } 

And Filter Code :

public void doFilterSearch(String employeeID,Vector memberEmails) throws Exception{

    SearchControls ctls = new SearchControls();
    ctls. setReturningObjFlag (true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String[] attrIDs = {"sn","mail"};
    ctls.setReturningAttributes(attrIDs);
    //System.out.println("Searching For :: " + employeeID);
    String filter = "(&(objectclass=*)(cn="+employeeID+"))"; //  ( mail=*)  // , "mail","manager"

    NamingEnumeration myInum = ctx.search(searchBase, filter, ctls);
    //formatResults(answer , grievanceBean);
    int count = 0;
    try
    {
        while (myInum.hasMoreElements())
        {
            SearchResult sr = (SearchResult)myInum.next();
            //grievanceBean = formatAttributes(sr.getAttributes() , grievanceBean);
            for (NamingEnumeration enuNaming = sr.getAttributes().getAll(); enuNaming.hasMore();) 
            {
                 Attribute attrib = (Attribute)enuNaming.nextElement();
                 String attrName = attrib.getID();
                // System.out.println("ATTRIBUTE Name : " + attrib.getID());
                // System.out.println("ATTRIBUTE Value: " + attrib.toString());

                 if (attrName.equalsIgnoreCase("mail"))
                 {  
                        String attrValue = attrib.toString();
                        int length = attrValue.length();
                        String mail = attrValue.substring(attrValue.indexOf(":")+2,length);

                        //System.out.println("Mail :: -->" + mail + "<--");
                        //System.out.println("E-mail :: -->>" + (mail.substring(mail.indexOf(":") + 1, mail.length())).trim() + "<<--");
                        memberEmails.add((mail.substring(mail.indexOf(":") + 1, mail.length())).trim());
                   }
            }
            count++;
        }
       //System.out.println("Search returned " + count + " results");
    }
    catch (NamingException e)
    {
        e.printStackTrace();
    }
    ctx.close();
}

EDIT : Thanks for your guidance, I am getting Error when it getting second email address

================= Debug Result ===========================
>>>CN=GRP_WF_XXXXNF,OU=DMS
Attribute: member
 0. CN=MAk,OU=HR,DC=xxx,DC=com
Name-->>MAk<<
Searching For :: MAk
ATTRIBUTE Name : mail
ATTRIBUTE Value: mail: mak@xxx.coom
Mail :: -->mak@xxx.coom<--
E-mail :: -->>mak@xxx.coom<<--
ATTRIBUTE Name : sn
ATTRIBUTE Value: sn: SAk
Search returned 1 results
 1. CN=Msi,OU=HR,,DC=xxx,DC=com
end 33
Name-->>Msi<<
Searching For :: Msi
Total members: 1
mak@xxx.coom
exception :: java.lang.NullPointerException
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
    at javax.naming.directory.InitialDirContext.getURLOrDefaultInitDirCtx(InitialDirContext.java:106)
    at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:267)
    at com.mzec.model.ADModel.doFilterSearch(ADModel.java:388)
    at com.mzec.model.ADModel.fetchGroupMembers(ADModel.java:270)
    at com.mzec.model.ADModel.main(ADModel.java:439)
Problem listing members: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

Line 388

NamingEnumeration myInum = ctx.search(searchBase, filter, ctls);

I haven't tried to run your code, but if I counted your braces correctly, you are closing your DirContext with the loop:

System.out.println("Total members: " + totalResults);
ctx.close();

This also corresponds with the output you posted:

Total members: 1
mak@xxx.coom
exception :: java.lang.NullPointerException

The first operation on ctx after you closed it triggers the NullPointerException . You also close the (same?) ctx at the end of your doFilterSearch .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM