ldap search all ou, throws exception

来源:互联网 发布:cacti 监控linux流量 编辑:程序博客网 时间:2024/04/28 15:48
public static void search(String dn,String attribute,  String value){

// String filter = "(&(objectClass=top)(objectClass=organizationalPerson)("+ attribute +"=" + value + "))";
String filter = "(&(objectClass=top)(objectClass=organizationalUnit)("+ attribute +"=" + value + "))";

// String[] attrPersonArray = {"uid","userPassword","displayName","distinguishedName","sAMAccountName","sAMAccountType","name","cn","sn","mobile","telephoneNumber","mail","userPassword","description"};
String[] attrPersonArray = {"name","distinguishedName","whenChanged","whenCreated"};
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);//SUBTREE_SCOPE三个查询范围,分别代表 当前对象查询、当前节点下对象查询、当前节点所有子目录查询
sc.setReturningAttributes(attrPersonArray);

try {
NamingEnumeration<SearchResult> sr = ctx.search(dn, filter.toString(), sc);

while(sr.hasMore()){
SearchResult result = sr.next();
NamingEnumeration<? extends Attribute> attrs = result.getAttributes().getAll();
while(attrs.hasMore()){
Attribute attr= attrs.next();
System.out.println(attr.getID() + "~~~~~~" + attr.get());
}
}

} catch (NamingException e) {
throw new UnsupportedOperationException("Unexpected Exception", e);

} finally{
//closeCtx();
}

}


上面代码查询所有的组织机构,当查询到最后一条的时候会抛出来异常信息,


Exception in thread "main" java.lang.UnsupportedOperationException: Unexpected Exception
at com.web.test.TestLDAP.search(TestLDAP.java:149)
at com.web.test.TestLDAP.main(TestLDAP.java:83)
Caused by: javax.naming.PartialResultException: Unprocessed Continuation Reference(s); remaining name ''
at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
at com.sun.jndi.ldap.LdapNamingEnumeration.getNextBatch(Unknown Source)
at com.sun.jndi.ldap.LdapNamingEnumeration.hasMoreImpl(Unknown Source)
at com.sun.jndi.ldap.LdapNamingEnumeration.hasMore(Unknown Source)
at com.web.test.TestLDAP.search(TestLDAP.java:139)
... 1 more


经过查询资料,发现方法hasMore的问题,修改为如下就没有问题了,


while(sr.hasMoreElements()){
SearchResult result = sr.next();
NamingEnumeration<? extends Attribute> attrs = result.getAttributes().getAll();
while(attrs.hasMore()){
Attribute attr= attrs.next();
System.out.println(attr.getID() + "~~~~~~" + attr.get());
}
}


参考资料: 

http://forum.spring.io/forum/spring-projects/data/ldap/68622-retrieve-user-via-filter


参考内容:

NamingEnumeration.hasMore() 

The JavaDoc for NamingEnumeration describes how hasMore() should function:

* When the last of the results has been returned by the NamingEnumeration's
* next(), invoking hasMore() would result in PartialResultException being thrown.

In the Template, there are several methods that call hasMore() when it appears they should be calling hasMoreElements() instead. 

hasMoreElements() does not throw the error and instead returns the expected true or false

0 0
原创粉丝点击