---
title: "OpenLDAP在 JAVA中添加，修改，删除"
author: "jieming"
date: "2010-11-10T20:49:56Z"
tags: []
categories: ["编程语言"]
slug: "openldap-java"
draft: false
lastmod: "2010-11-10T20:49:56Z"
id: 808001
url: "https://jieming.iteye.com/blog/808001"
---

今天终于把添加，删除，修改节点名，属性，遍历节点都弄出来了，先把代码贴出来吧

/\**  
 *  
 * @author   
 \*/  
import java.util.Hashtable;  
import javax.naming.directory.\*;  
import java.util.\*;  
import javax.naming.\*;

public class ChenYi {

    DirContext dc = null;  
    String account = "Manager";//操作LDAP的帐户。默认就是Manager。  
    String password = "secret";//帐户Manager的密码。  
    String root = "dc=example,dc=com"; //LDAP的根节点的DC

    public ChenYi() {  
        init();  
        //add();//添加节点  
        //delete("ou=hi,dc=example,dc=com");//删除"ou=hi,dc=example,dc=com"节点  
        //modifyInformation("ou=hi,dc=example,dc=com");//修改"ou=hi,dc=example,dc=com"属性  
        //renameEntry("ou=new,o=neworganization,dc=example,dc=com","ou=neworganizationalUnit,o=neworganization,dc=example,dc=com");//重命名节点"ou=new,o=neworganization,dc=example,dc=com"  
        searchInformation("dc=example,dc=com", "", "(objectclass=\*)");//遍历所有根节点  
        //searchInformation("o=neworganization,dc=example,dc=com","","(objectclass=\*)");//遍历指定节点的分节点  
        close();  
    }

    public void init() {  
        Hashtable env = new Hashtable();  
        env.put(Context.INITIAL\_CONTEXT\_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");  
        env.put(Context.PROVIDER\_URL, "[ldap://192.168.100.221:389/]()");  
        env.put(Context.SECURITY\_AUTHENTICATION, "simple");  
        env.put(Context.SECURITY\_PRINCIPAL, "cn=" + account + "," + root);  
        env.put(Context.SECURITY\_CREDENTIALS, password);  
        try {  
            dc = new InitialDirContext(env);//初始化上下文  
            System.out.println("认证成功");//这里可以改成异常抛出。  
        } catch (javax.naming.AuthenticationException e) {  
            System.out.println("认证失败");  
        } catch (Exception e) {  
            System.out.println("认证出错：" + e);  
        }  
    }

    public void close() {  
        if (dc != null) {  
            try {  
                dc.close();  
            } catch (NamingException e) {  
                System.out.println("NamingException in close():" + e);  
            }  
        }  
    }

    public void add() {  
        try {  
            String newUserName = "hi";  
            BasicAttributes attrs = new BasicAttributes();  
            BasicAttribute objclassSet = new BasicAttribute("objectClass");  
            objclassSet.add("top");  
            objclassSet.add("organizationalUnit");  
            attrs.put(objclassSet);  
            attrs.put("ou", newUserName);  
            dc.createSubcontext("ou=" + newUserName + "," + root, attrs);  
        } catch (Exception e) {  
            e.printStackTrace();  
            System.out.println("Exception in add():" + e);  
        }  
    }

    public void delete(String dn) {  
        try {  
            dc.destroySubcontext(dn);  
        } catch (Exception e) {  
            e.printStackTrace();  
            System.out.println("Exception in delete():" + e);  
        }  
    }

    public boolean modifyInformation(String dn) {  
        try {  
            ModificationItem\[] mods = new ModificationItem\[1];

            /\*添加属性\*/  
//            Attribute attr0 = new BasicAttribute("description",  
//                    "测试");  
//            mods\[0] = new ModificationItem(DirContext.ADD\_ATTRIBUTE,attr0);

            /\*修改属性\*/  
//            Attribute attr0 = new BasicAttribute("description", "陈轶");  
//            mods\[0] = new ModificationItem(DirContext.REPLACE\_ATTRIBUTE,  
//                    attr0);

            /\*删除属性\*/  
            Attribute attr0 = new BasicAttribute("description",  
                    "陈轶");  
            mods\[0] = new ModificationItem(DirContext.REMOVE\_ATTRIBUTE,  
                    attr0);  
            dc.modifyAttributes(dn, mods);  
            return true;  
        } catch (NamingException ne) {  
            ne.printStackTrace();  
            System.err.println("Error: " + ne.getMessage());  
            return false;  
        }

    }

    /\**  
     * @param base ：根节点(在这里是"dc=example,dc=com")  
     * @param scope ：搜索范围,分为"base"(本节点),"one"(单层),""(遍历)  
     * @param filter ：指定子节点(格式为"(objectclass=\*)",\*是指全部，你也可以指定某一特定类型的树节点)  
     \*/  
    public void searchInformation(String base, String scope, String filter) {  
        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);  
        }

        NamingEnumeration ne = null;  
        try {  
            ne = dc.search(base, filter, sc);  
            // Use the NamingEnumeration object to cycle through  
            // the result set.  
            while (ne.hasMore()) {  
                System.out.println();  
                SearchResult sr = (SearchResult) ne.next();  
                String name = sr.getName();  
                if (base != null && !base.equals("")) {  
                    System.out.println("entry: " + name + "," + base);  
                } else {  
                    System.out.println("entry: " + 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) {  
                            System.out.println(attrType + ": " + (String) oneVal);  
                        } else {  
                            System.out.println(attrType + ": " + new String((byte\[]) oneVal));  
                        }  
                    }  
                }  
            }  
        } catch (Exception nex) {  
            System.err.println("Error: " + nex.getMessage());  
            nex.printStackTrace();  
        }  
    }

    public boolean renameEntry(String oldDN, String newDN) {  
        try {  
            dc.rename(oldDN, newDN);  
            return true;  
        } catch (NamingException ne) {  
            System.err.println("Error: " + ne.getMessage());  
            return false;  
        }  
    }

    public static void main(String\[] args) {  
        new ChenYi();  
    }  
}

 

本文来自CSDN博客，转载请标明出处：[http://blog.csdn.net/zhangjunfangkaixin/archive/2009/03/04/3957198.aspx](http://blog.csdn.net/zhangjunfangkaixin/archive/2009/03/04/3957198.aspx)