import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.context.web.WebAppConfiguration;import javax.naming.Context;import javax.naming.NamingEnumeration;import javax.naming.NamingException;import javax.naming.directory.*;import java.util.Enumeration;import java.util.HashMap;import java.util.Hashtable;import java.util.concurrent.ConcurrentLinkedQueue;import static org.junit.Assert.assertEquals;//@RunWith(SpringRunner.class)//@SpringBootTest(classes = Application.class)public class ControllerTest { @Test public void test(){ //System.out.println(commonUtil.getAssetCode()); Hashtable env = new Hashtable(); String LDAP_URL = "ldap://ip:389"; // LDAP 访问地址 String adminName = ""; // 注意用户名的写法:domain\User 或 cn=user String adminPassword = ""; // 密码 env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, adminName); env.put(Context.SECURITY_CREDENTIALS, adminPassword); InitialDirContext dc = null; try { dc = new InitialDirContext(env);// 初始化上下文 System.out.println("认证成功"); } catch (javax.naming.AuthenticationException e) { System.out.println("认证失败"); } catch (Exception e) { System.out.println("认证出错:" + e); } // 创建搜索控件 SearchControls searchCtls = new SearchControls(); // 设置搜索范围 searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // 设置搜索过滤条件 String searchFilter = "sAMAccountName=" + ""; // 设置搜索域节点 String searchBase = "ou=传化化学集团,ou=全体人员,dc=etransfar,dc=com"; // 定制返回属性 String returnedAtts[] = { "ou", "displayname","cn","dn"};//displayname 姓名 ou 组织 cn 工号 searchCtls.setReturningAttributes(returnedAtts); // 不定制属性,返回所有的属性集 //searchCtls.setReturningAttributes(null); int totalResults = 0; try { NamingEnumeration answer = dc.search(searchBase, "(objectClass=person)", searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes Attrs = sr.getAttributes(); System.out.println(sr.getName()); if (Attrs != null) { try { for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore();) { Attribute Attr = (Attribute) ne.next(); // 读取属性值 for (NamingEnumeration e = Attr.getAll(); e.hasMore();) { // 接受循环遍历读取的userPrincipalName用户属性 String user = e.next().toString(); System.out.println(" user=" + user); }/* // 读取属性值 Enumeration values = Attr.getAll(); if (values != null) { while (values.hasMoreElements()) { System.out.println(" AttributeValues=" + values.nextElement()); } }*/ } } catch (NamingException e) { System.err.println("Throw Exception : " + e); } } totalResults++; System.out.println("--------------------------"); } System.out.println(totalResults); } catch (Exception e) { e.printStackTrace(); System.err.println("Throw Exception : " + e); } }}