package test;
import java.util.Hashtable;
import javax.naming.Context;
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;
public class test {
private static test instance = new test();
private DirContext ctx = null;
public static test getInstance(){
return instance;
}
public test() {
init();
}
public void init(){
try{
Hashtable env = new Hashtable();
String rootdn = "cn=root,dc=universityname,dc=com";
String rootpw = "secret";
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, rootdn);
env.put(Context.SECURITY_CREDENTIALS, rootpw);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,"ldap://localhost:389");
ctx = new InitialDirContext(env);
}
catch(Exception e){
System.out.println(e.toString());
}
}
public void reload(){
instance = new test();
}
public String getPassword(String userId) {
byte[] password = null;
try{
String userObjectClass = "inetorgPerson";
String userIdAttrName = "uid";
String userPwdAttrName = "userPassword";
String rootEntry = "dc=universityname,dc=com";
SearchControls controls = new SearchControls();
controls.setCountLimit(1);
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectClass=" + userObjectClass + ")(" +
"uid" + "=" + userId + "))";
NamingEnumeration ne = ctx.search(rootEntry, filter, controls);
if (ne.hasMore()) {
SearchResult sr = (SearchResult)ne.next();
Attributes attrs = sr.getAttributes();
Attribute passwordAttr = attrs.get(userPwdAttrName);
password = (byte[])passwordAttr.get();
}
else{
}
return new String(password);
}
catch(Exception e){
init();
System.out.println(e.toString());
return "";
}
}
public static void main(String[] args){
try{
System.out.println(test.getInstance().getPassword("test42"));
}
catch(Exception e){
e.printStackTrace();
}
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/chen_hh2/archive/2005/11/21/534140.aspx