package com.primeton.poctag.service.ldap.impl;
import com.primeton.poctag.service.ldap.PersonRepo;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
/**
*
*
* Created by zhenqin.
* User: zhenqin
* Date: 2021/9/14
* Time: 16:40
* Vendor: yiidata.com
*
*
*
* @author zhenqin
*/
public class TraditionalPersonRepoImpl implements PersonRepo {
@Override
public List getAllPersonNames() {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389/ou=yiidata,dc=yiidata,dc=com");
DirContext ctx;
try {
ctx = new InitialDirContext(env);
} catch (NamingException e) {
throw new RuntimeException(e);
}
List list = new LinkedList();
NamingEnumeration results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = ctx.search("", "(uid=*)", controls);
System.out.println("-------------------------------");
while (results.hasMore()) {
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
System.out.println(attributes);
Attribute attr = attributes.get("uid");
String cn = attr.get().toString();
list.add(cn);
}
} catch (NameNotFoundException e) {
// The base context was not found.
e.printStackTrace();
// Just clean up and exit.
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
// Never mind this.
}
}
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
// Never mind this.
}
}
}
return list;
}
public static void main(String[] args) {
final List allPersonNames = new TraditionalPersonRepoImpl().getAllPersonNames();
System.out.println(allPersonNames);
}
}