LDAP操作之java篇(1)
本文將分成4部分對LDAP操作進行講解,每一部分都附帶小例子(主要是參考MANNING - LDAP Programming, Management and Intergration一書,自己做了一些修改並通過驗證)。閱讀本文要有一定的LDAP知識,其實如果你自己配過LDAP服務器以後再來看這篇文章應該沒什麼難度(參見上一篇文章《在windows上配置openldap》)
連接LDAP服務器
String dn; //包括連接LDAP服務器的用戶及要操作的根節點
DirContext dc; //相當於這個樹的一個映像
Properties env = new Properties();
env.put(DirContext.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(DirContext.PROVIDER_URL, "ldap://" + host + ":" + port);
if (dn != null) {
env.put(DirContext.SECURITY_PRINCIPAL, dn);
env.put(DirContext.SECURITY_CREDENTIALS, password);
}
dc = new InitialDirContext(env);
dn舉例: dn=” cn=Manager,dc=kkk,dc=com”,password就是這個dn對應的密碼。Host是LDAP服務器的主機地址,port是端口(openLDAP默認開放的是389)
查詢這棵樹的所有節點
有點類似sql裏邊的select * from tableName;
/**
* @param base :根節點(在這裏是”dc=kkk,dc=com”)
* @param scope :搜索範圍
* @param filter :指定子節點(格式爲”(objectclass=*)”,*是指全部,你也可以指定某一特定類型的樹節點)
* @param attributes :屬性集合(格式爲{“*”}如果要指定搜索某一指定的屬性列,就把*改成響應的屬性列名稱就行了)
* @return result :result裏邊存的就是查詢的結果集合
*/
public Vector searchInformation(String base, String scope, String filter,
String[] attributes)
{
Vector results = new Vector();
SearchControls sc = new SearchControls();
if (scope.equals("base")) {
sc.setSearchScope(SearchControls.OBJECT_SCOPE);
} else if (scope.equals("one")) {
sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
} else {
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
// Reduce data provided by the LDAP server by listing
// only those attributes we want to return.
if (attributes.length > 0) {
sc.setReturningAttributes(attributes);
}
NamingEnumeration ne = null;
try {
ne = dc.search(base, filter, sc);
// Use the NamingEnumeration object to cycle through
// the result set.
while (ne.hasMore()) {
Entry entry = new Entry();
SearchResult sr = (SearchResult) ne.next();
String name = sr.getName();
if (base != null && !base.equals("")) {
entry.setDN(name + "," + base);
} else {
entry.setDN(name);
}
Attributes at = sr.getAttributes();
NamingEnumeration ane = at.getAll();
while (ane.hasMore()) {
Attribute attr = (Attribute) ane.next();
String attrType = attr.getID();
NamingEnumeration values = attr.getAll();
Vector vals = new Vector();
// Another NamingEnumeration object, this time
// to iterate through attribute values.
while (values.hasMore()) {
Object oneVal = values.nextElement();
if (oneVal instanceof String) {
vals.addElement((String) oneVal);
} else {
vals.addElement(new String((byte[]) oneVal));
}
}
entry.put(attrType, vals);
}
results.addElement(entry);
}
// The search() method can throw a number of exceptions.
// Here we just handle and print the exception.
// In real life we might want to pass the exception along
// to a piece of the software that might have a better
// context for correcting or presenting the problem.
} catch (Exception nex) {
System.err.println("Error: " + nex.getMessage());
nex.printStackTrace();
lc.close();
}
return results;
}
由於時間的關係,今天就先寫到這,改天再把增加、修改、刪除節點加上來:) 。