通过在JAVA中传递组名来从Active Directory获取电子邮件地址

时间:2016-10-18 05:40:04

标签: java

我正在尝试通过将Group Name作为输入参数来创建一个从Active Directory返回所有组成员的电子邮件地址的函数,结果将是&#34 ;;"单独的字符串。

我发现以下代码但仅返回第一个成员电子邮件地址并非所有成员都可以指导下面的代码中有什么问题,或者在Java中有任何其他方法可以完成它: 感谢

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();
        } 

并过滤代码:

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();
}

编辑: 感谢您的指导,我收到错误时收到第二个电子邮件地址

================= 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

第388行

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

1 个答案:

答案 0 :(得分:2)

我没有尝试过运行您的代码,但如果我正确计算了您的大括号,那么您将使用循环关闭DirContext

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

这也与您发布的输出相对应:

  

总会员:1   mak@xxx.coom
  exception :: java.lang.NullPointerException

关闭后ctx上的第一个操作会触发NullPointerException。您还可以在ctx的末尾关闭(相同的?)doFilterSearch