使用JLDAP操作LDAP,包含匿名連接、ldif導入導出、獲取根節點、對數據的操作、LDAP錯誤碼解析等


bean類

package com.cn.ccc.ggg.ldap.model;

import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;

/**
 * 目錄服務連接信息
 * dq
 */
@Entity
@Table(name = "bo_ldap_info")//用戶表
public class LDAPConectionInfo  extends  IdEntity{

    private static final long serialVersionUID = 7300555212960602097L;

    public static final Integer ENABLE_STATUS = 1;//1:表示啟用狀態

    public static final Integer DISABLE_STATUS = 0;// 0:表示停用狀態

    public static final Integer LDAP_VERSION_3 = 3;// 3:表示ldap協議版本為3.0

    public static final Integer LDAP_VERSION_2 = 2;// 2:表示ldap協議版本為2.0

    public static final Integer LDAP_PORT_389 = 389; //389:默認端口

    private Integer userId; //用戶的ID

    private String serverName;  //服務名稱

    private String ip;  //ip

    private Integer port = LDAP_PORT_389;   //端口

    private Integer version = LDAP_VERSION_3;   //協議版本

    private String baseDN;  //根節點

    private Integer isAnonymousBind = DISABLE_STATUS; //是否匿名訪問

    private String userDN;  //用戶DN

    private Integer isAppendBaseDN = DISABLE_STATUS; //是否追加根節點

    private String password;    //密碼

    private Date optTime = new Date();//操作時間

    @Override
    public String toString() {
        return "LDAPConectionInfo{" +
                "userId=" + userId +
                ", serverName='" + serverName + '\'' +
                ", ip='" + ip + '\'' +
                ", port=" + port +
                ", version=" + version +
                ", baseDN='" + baseDN + '\'' +
                ", isAnonymousBind=" + isAnonymousBind +
                ", userDN='" + userDN + '\'' +
                ", isAppendBaseDN=" + isAppendBaseDN +
                ", password='" + password + '\'' +
                ", optTime=" + optTime +
                '}';
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getServerName() {
        return serverName;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public String getBaseDN() {
        return baseDN;
    }

    public void setBaseDN(String baseDN) {
        this.baseDN = baseDN;
    }

    public Integer getIsAnonymousBind() {
        return isAnonymousBind;
    }

    public void setIsAnonymousBind(Integer isAnonymousBind) {
        this.isAnonymousBind = isAnonymousBind;
    }

    public String getUserDN() {
        return userDN;
    }

    public void setUserDN(String userDN) {
        this.userDN = userDN;
    }

    public Integer getIsAppendBaseDN() {
        return isAppendBaseDN;
    }

    public void setIsAppendBaseDN(Integer isAppendBaseDN) {
        this.isAppendBaseDN = isAppendBaseDN;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getOptTime() {
        return optTime;
    }

    public void setOptTime(Date optTime) {
        this.optTime = optTime;
    }

    public LDAPConectionInfo(Integer userId, String serverName, String ip, Integer port, Integer version, String baseDN, Integer isAnonymousBind, String userDN, Integer isAppendBaseDN, String password, Date optTime) {
        this.userId = userId;
        this.serverName = serverName;
        this.ip = ip;
        this.port = port;
        this.version = version;
        this.baseDN = baseDN;
        this.isAnonymousBind = isAnonymousBind;
        this.userDN = userDN;
        this.isAppendBaseDN = isAppendBaseDN;
        this.password = password;
        this.optTime = optTime;
    }

    public LDAPConectionInfo() {
    }
}

Service類

package com.cn.ccc.ggg.ldap.service;

import com.cn.ccc.ggg.encrypt.core.dao.HibernateEntityDao;
import com.cn.ccc.ggg.encrypt.core.dao.support.Page;
import com.cn.ccc.ggg.ldap.bean.entryInfo.PersonEntry;
import com.cn.ccc.ggg.ldap.core.common.LDIFReader;
import com.cn.ccc.ggg.ldap.core.novell.LDAPExport;
import com.cn.ccc.ggg.ldap.exception.LDAPException;
import com.cn.ccc.ggg.ldap.model.CertList;
import com.cn.ccc.ggg.ldap.model.LDAPConectionInfo;


import com.novell.ldap.*;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

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.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.io.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * 目錄服務連接信息管理
 */
@Service("ldapConectionInfoService")
public class LDAPConectionInfoService extends HibernateEntityDao<LDAPConectionInfo> {

    public static int DEFAULT_PAGE_SIZE = 500;

    private int pageSize = DEFAULT_PAGE_SIZE; // 每頁的記錄數

    private String msg = new String();

    private Integer d = new Integer(0);


    /**
     * @description:查詢目錄服務列表
     * @param: [condition, pageNo, pageSize]
     * @return: com.cn.ccc.ggg.encrypt.core.dao.support.Page
     * @exception:
     * @author: dq
     * @date: 13:39 2018/1/26
     */
    public Page findserverList(Map<String, Object> condition, int pageNo, int pageSize) throws LDAPException {
        ArrayList<Criterion> criteria = new ArrayList<Criterion>();
        if (condition.get("userId") != null) {
            Integer id = (Integer) condition.get("userId");
            criteria.add(Restrictions.eq("userId", id));
        }
        return pagedQuery(LDAPConectionInfo.class, pageNo, pageSize, "optTime", false, criteria.toArray(new Criterion[]{}));
    }

    public LDAPConectionInfo findServerInfoByUserIdAndServerName(int id, String serverName) {
        List<LDAPConectionInfo> list = createCriteria(LDAPConectionInfo.class, Restrictions.and(Restrictions.eq("userId", id), Restrictions.eq("serverName", serverName))).list();
        if (list.size() > 0)
            return list.get(0);
        else
            return null;
    }


    /**
     * @description:連接並綁定目錄服務系統,支持匿名訪問,簡單認證。不支持ssl連接。自動追加數據庫名稱
     * @param: [currinfo]   連接信息
     * @return: com.novell.ldap.LDAPConnection
     * @exception:
     * @author: dq
     * @date: 13:39 2018/1/26
     */
    public LDAPConnection connectionLDAP(LDAPConectionInfo currinfo) {
        LDAPConnection lc = new LDAPConnection();
        try {
            //連接目錄服務
            lc.connect(currinfo.getIp(), currinfo.getPort());
            //綁定服務
            if (currinfo.getIsAnonymousBind() == 1) {     //匿名訪問
                lc.bind(null, null);
            } else {                                      //簡單認證
                String loginDN = currinfo.getUserDN();
                if (currinfo.getIsAppendBaseDN().equals(LDAPConectionInfo.ENABLE_STATUS))  //檢查是否追加數據庫名稱
                    loginDN = currinfo.getUserDN() + "," + currinfo.getBaseDN();
                lc.bind(currinfo.getVersion(), loginDN, currinfo.getPassword().getBytes("UTF8"));
            }
        } catch (com.novell.ldap.LDAPException e) {
            d = 1;
            getErrorMsg(e);
            //連接失敗
            return null;
        } catch (UnsupportedEncodingException e) {
            //轉碼異常
            msg = "編碼異常";
        }
        return lc;
    }



    public Map<String,Object> getNumberOfEntries(LDAPConectionInfo info,String searchDN){
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        String searfiler = "(objectclass=*)";
        LDAPConnection lc = connectionLDAP(info);
        long total = 0L;
        d = 0;
        try {
            String attrs[] = {LDAPConnection.NO_ATTRS};
            LDAPSearchResults s = lc.search(searchDN, LDAPConnection.SCOPE_SUB,searfiler,attrs,true);
            while (s.hasMore()) {
                s.next();
                total++;
                //TODO 異常處理
            }

        } catch (com.novell.ldap.LDAPException e) {
            d = 1;
            getErrorMsg(e);
        }
        hashMap.put("status",d);
        hashMap.put("msg",msg);
        hashMap.put("total",total);
        return hashMap;
    }

    /**
     * @description:根據ip、port獲取ldap的根節點
     * @param: [ip, port]
     * @return: java.util.List<java.util.Map < java.lang.String , java.lang.Object>>
     * @exception:
     * @author: dq
     * @date: 9:54 2018/2/26
     */
    public List<Map<String,Object>> getSuffix(String ip,int  port) {
        d = 0;msg = "";
        LDAPConnection lc = new LDAPConnection();
        List<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            lc.connect(ip,port);
        } catch (com.novell.ldap.LDAPException e) {
            d = 1;
            msg = "獲取數據庫名稱失敗,請檢查ip和端口是否正確以及服務是否開啟";
            logger.error(msg);
            return null;
        }
        String [] context = {"namingContexts"};
        try {
            LDAPSearchResults search = lc.search("", 0, "objectclass=*", context, false);
            while (search.hasMore()){
                LDAPEntry ldapEntry = search.next();
                LDAPAttributeSet attributeSet = ldapEntry.getAttributeSet();
                Iterator iterator = attributeSet.iterator();
                while (iterator.hasNext()){
                    LDAPAttribute next = (LDAPAttribute)iterator.next();
                    String nextName = next.getName();
                    if(nextName.equals("namingContexts")){
                        Enumeration stringValues = next.getStringValues();
                        while (stringValues.hasMoreElements()){
                            HashMap<String, Object> hashMap = new HashMap<String, Object>();
                            String dn = (String)stringValues.nextElement();
                            hashMap.put("DN",dn);
                            arrayList.add(hashMap);
                        }
                    }
                }
            }
        } catch (com.novell.ldap.LDAPException e) {
            e.printStackTrace();
            d = 1;
            msg = "獲取數據庫名稱失敗";
            return null;
        }
        return arrayList;

    }

    public Map<String,Object> importLDIF(LDAPConectionInfo info, File ldifFile){
        Integer errorSign = 0;
        Integer successSign = 0;
        LDIFReader reader = null;
        LDAPEntry entry;
        LDAPMessage msg, retMsg;
        LDAPConnection lc = new LDAPConnection();
        Map<String, Object> hashMap = new HashMap<String, Object>();
        try {
            FileInputStream fis = new FileInputStream(ldifFile);
            reader = new LDIFReader(fis, 1);
        } catch (Exception e) {
            logger.error("讀取 " + ldifFile +"文件失敗"+e.getMessage());
        }
        try {
            lc.connect( info.getIp(), info.getPort() );
            String loginDN = info.getUserDN();
            if(info.getIsAppendBaseDN().equals(LDAPConectionInfo.ENABLE_STATUS))  //檢查是否追加數據庫名稱
                loginDN = info.getUserDN()+","+info.getBaseDN();
            lc.bind( info.getVersion(), loginDN, info.getPassword().getBytes("UTF8") );
            if (!reader.isRequest()) {
                while ( (msg = reader.readMessage()) != null) {
                    entry = ((LDAPSearchResult)msg).getEntry();
                }
            } else {
                while ( (msg = reader.readMessage()) != null) {
                    LDAPMessageQueue queue = lc.sendRequest(msg, null, null);
                    if ((retMsg = queue.getResponse()) != null) {
                        LDAPResponse response = (LDAPResponse)retMsg;
                        int status = response.getResultCode();
                        if ( status == com.novell.ldap.LDAPException.SUCCESS )
                            successSign++;
                        else  {
                            if(status == com.novell.ldap.LDAPException.ENTRY_ALREADY_EXISTS){
                                successSign++;
                            } else{
                                errorSign++;
                                if(response.getErrorMessage().length() != 0){
                                    logger.error("錯誤代碼為:"+ status +response.getErrorMessage());
                                }

                            }

                        }
                    }
                }
            }
        } catch( UnsupportedEncodingException e ) {
            logger.error( "錯誤信息為:UnsupportedEncodingException");
        } catch ( IOException ioe ) {
            logger.error("錯誤信息為:IOException");
        } catch ( com.novell.ldap.LDAPException le ) {
            logger.error("錯誤信息為:LDAPException :"+le.getMessage());
        }
        hashMap.put("errorSign", errorSign);
        hashMap.put("successSign", successSign);
        return hashMap;
    }

   /**
    * @description:LDIF文件導出
    * @param: [info, baseDN, filePath]  連接信息;導出的根節點;導出的路徑
    * @return: void
    * @exception:
    * @author: dq
    * @date: 13:37 2018/1/26
    */
    public void exportLDIF(LDAPConectionInfo info,String baseDN,String filePath){
        String loginDN = info.getUserDN();
        if(info.getIsAppendBaseDN().equals(LDAPConectionInfo.ENABLE_STATUS))  //檢查是否追加數據庫名稱
            loginDN = info.getUserDN()+","+info.getBaseDN();
        String [] args = {info.getIp(),loginDN,info.getPassword(),baseDN,"objectClass=*",filePath};
        LDAPExport export = new LDAPExport();
        export.export(args);

    }

    /**
     * @description:重命名屬性名稱,若該屬性不是子節點則失敗
     * @param: [info, oldDN, newDN, parentDN]
     * @return: java.util.Map<java.lang.String , java.lang.Object>
     * @exception:
     * @author: dq
     * @date: 13:32 2018/1/26
     */
    public  Map<String,Object> renameRDN(LDAPConectionInfo info,String oldDN,String newDN,String parentDN){
        d= 0;msg = "";
        Map<String, Object> map = new HashMap<String, Object>();
        LDAPConnection lc = connectionLDAP(info);
        if(null == lc){
            map.put("status",d);
            map.put("msg",msg);
            return map;
        }
        try {
            lc.rename(oldDN,newDN,parentDN,true);
            lc.disconnect();
        } catch (com.novell.ldap.LDAPException e) {
            d = 1;


        }
        map.put("status",d);
        map.put("msg",msg);
        return map;
    }
    /**
     * @description:修改指定條目的屬性
     * @param: [info, searchDN, attrsVal]
     * @return: java.util.Map<java.lang.String , java.lang.Object>
     * @exception:
     * @author: dq
     * @date: 13:50 2018/1/26
     */
    public Map<String,Object> modifyAttrs(LDAPConectionInfo info,String searchDN,List<Map<String,Object>> attrsVal){
        d= 0;msg = "";
        HashMap<String, Object> map = new HashMap<String, Object>();
        LDAPConnection lc = connectionLDAP(info);

        if(null == lc){
            map.put("status",d);
            map.put("msg",msg);
            return map;
        }
        String searchFilter = "(objectclass=*)";
        try {
            LDAPSearchResults search = lc.search(searchDN, LDAPConnection.SCOPE_BASE, searchFilter, null, false);
            while (search.hasMore()){
                LDAPEntry next = search.next();
                LDAPAttributeSet attributeSet = next.getAttributeSet();
                Iterator iterator = attributeSet.iterator();
                while (iterator.hasNext()){
                    LDAPAttribute attribute = (LDAPAttribute) iterator.next();
                    String attributeName = attribute.getName();
                    for (Map m: attrsVal){  //新的屬性值
                        //動態修改條目屬性值
                        if(m.containsKey(attributeName)) //檢查key是否存在
                             lc.modify(searchDN,new LDAPModification(LDAPModification.ADD,new LDAPAttribute( attributeName, (String) m.get(attributeName))));
                    }
                }
            }

        } catch (com.novell.ldap.LDAPException e) {
            d =1;
            getErrorMsg(e);
        }
        map.put("status",d);
        map.put("msg",msg);
        return map;
    }

    /**
     * @description:添加條目(只支持用戶和組織)
     * @param: [info, person, searchDN]
     * @return: java.util.Map<java.lang.String , java.lang.Object>
     * @exception:
     * @author: dq
     * @date: 13:49 2018/1/26
     */
    public Map<String,Object> addEntry(LDAPConectionInfo info, PersonEntry person,String searchDN) {
        d= 0;msg = "";
        Map<String, Object> map = new HashMap<String,Object>();
        LDAPConnection lc = connectionLDAP(info);
        if(null == lc){
            map.put("status",d);
            map.put("msg",msg);
            return  map;
        }
        LDAPAttributeSet attributeSet = new LDAPAttributeSet();
        String [] att = {"top",person.getObjectclass()};
        attributeSet.add(new LDAPAttribute("objectclass",att));
        if(person.getSn().length() > 0)
            attributeSet.add(new LDAPAttribute("sn",person.getSn()));
        if(person.getUserPassword().length() > 0 )
            attributeSet.add(new LDAPAttribute("userpassword",person.getUserPassword()));
        if( person.getTelephoneNumber().length() > 0)
            attributeSet.add(new LDAPAttribute("telephoneNumber",person.getTelephoneNumber()));
        if( person.getDescription().length() > 0)
            attributeSet.add(new LDAPAttribute("description",person.getDescription()));
        if( person.getSeeAlso().length() > 0  )
            attributeSet.add(new LDAPAttribute("seeAlso",person.getSeeAlso()));

        String dn = person.getDn() + "," + searchDN;
        LDAPEntry newEntry = new LDAPEntry(dn, attributeSet);
        try {
            lc.add(newEntry);
            lc.disconnect();
        } catch (com.novell.ldap.LDAPException e) {
            d= 1;
            getErrorMsg(e);
        }
        map.put("status",d);
        map.put("msg",msg);
        return map;

    }

    /**
     * @description:刪除指定的節點,若該節點存在子節點將一並刪除
     * @param: [info, base, baseDN]
     * @return: java.util.Map<java.lang.String , java.lang.Object>
     * @exception:
     * @author: dq
     * @date: 13:47 2018/1/26
     */
    public Map<String, Object> delete(LDAPConectionInfo info,int base, String baseDN){
        d= 0;msg = "";
        Map<String, Object> map = new HashMap<String, Object>();
        LDAPConnection lc = connectionLDAP(info);
        if(null == lc){
            map.put("status",d);
            map.put("msg",msg);
            return  map;
        }
        String searchFilter = "(objectclass=*)";
        try {
            LDAPSearchResults search = lc.search(baseDN, base, searchFilter, null, false);
            while (search.hasMore()){
                String dn = search.next().getDN();
                delete(info,LDAPConnection.SCOPE_ONE,dn);
                lc.delete(dn);
            }
        } catch (com.novell.ldap.LDAPException e) {
            d = 1;
            getErrorMsg(e);
        }
        map.put("msg",msg);
        map.put("status",d);

        return map;
    }

    /**
     * @description:返回子節點的條目。
     * @param: [currInfo, searchBase, searchFilter, scope, currentPageNo]
     * @return: java.util.List<java.util.Map < java.lang.String , java.lang.Object>>
     * @exception:
     * @author: dq
     * @date: 13:46 2018/1/26
     */
    public List<Map<String, Object>> search(LDAPConectionInfo currInfo, String searchBase, String searchFilter, int scope,int currentPageNo) {
        d= 0;msg = "";
        StringBuffer str = new StringBuffer();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        LDAPConnection lc = connectionLDAP(currInfo);
        if(null == lc){
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("status",d);
            map.put("msg",msg);
            mapList.add(map);
            return  mapList;
        }
        long l = 0L;

        try {
            String attrs[] = {LDAPConnection.NO_ATTRS};
            LDAPSearchResults searchResults = lc.search(searchBase,
                    scope, // 搜索的類型,遍歷、子節點、 LDAPConnection.SCOPE_BASE base 0:自身,one 1:子節點,sub 2:所有
                    searchFilter,
                    attrs,          // “1.1”只返回條目名稱
                    true);// 不返回屬性和屬性值
            long totalCount = (long)currentPageNo * pageSize ;
            long current = (long)( currentPageNo - 1 ) * pageSize + 1;
            while (searchResults.hasMore()) {   //遍歷所有條目
                Map<String, Object> map = new HashMap<String, Object>();
                LDAPEntry nextEntry = null;
                try {
                    nextEntry = searchResults.next();
                } catch (com.novell.ldap.LDAPException e) {
                    d = 1;
                    HashMap<String, Object> m = new HashMap<String, Object>();
                    getErrorMsg(e);
                    m.put("status",d);
                    m.put("msg",msg);
                    mapList.add(m);

                    // 拋出異常,進入下一個條目
                    if (e.getResultCode() == com.novell.ldap.LDAPException.LDAP_TIMEOUT || e.getResultCode() == com.novell.ldap.LDAPException.CONNECT_ERROR)
                        break;
                    else
                        continue;
                }
                l++;
                 if(l >= current && l <= totalCount){     //查詢需要的條目數是介於current條至totalCount條
                    map.put("isParent", true);
                    int a = currentPageNo != 1 ? currentPageNo : 1;
                    map.put("pageNo",a);
                    String dn = nextEntry.getDN();
                    map.put("baseDN", dn);   //保存DN
                     long total = getTotal(searchFilter, lc, dn);
                     map.put("totalRecord",total);
                    if (scope != 0) dn = dn.substring(0, dn.indexOf(","));
                    map.put("text", dn);    //去除父節點名稱,用於前端顯示
                     mapList.add(map);
                }
            }
            lc.disconnect();
        } catch (com.novell.ldap.LDAPException e) {
            //getErrorMsg(e);
        }
        return mapList;
    }

    /**
     * @description:獲取節點自身的屬性和屬性值
     * @param: [currInfo, searchBase, searchFilter]
     * @return: java.util.List<java.util.Map < java.lang.String , java.lang.Object>>
     * @exception:
     * @author: dq
     * @date: 13:45 2018/1/26
     */
    public List<Map<String, Object>> attAndValue(LDAPConectionInfo currInfo, String searchBase, String searchFilter) {
        d= 0;msg = "";
        StringBuffer str = new StringBuffer();
        LDAPConnection lc = connectionLDAP(currInfo);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if(null == lc){
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("status",d);
            map.put("msg",msg);
            mapList.add(map);
            return  mapList;
        }

        try {
            LDAPSearchResults searchResults = lc.search(searchBase,
                    LDAPConnection.SCOPE_BASE, // 搜索的類型,遍歷、子節點、 LDAPConnection.SCOPE_BASE base 0:自身,one 1:子節點,sub 2:所有
                    searchFilter,
                    null,          // return all attributes
                    false);// return attrs and values

            while (searchResults.hasMore()) {   //遍歷所有條目
                Map<String, Object> map = new HashMap<String, Object>();
                LDAPEntry nextEntry = null;
                try {
                    nextEntry = searchResults.next();
                } catch (com.novell.ldap.LDAPException e) {
                    System.out.println("Error: " + e.toString());
                    // Exception is thrown, go for next entry
                    if (e.getResultCode() == com.novell.ldap.LDAPException.LDAP_TIMEOUT || e.getResultCode() == com.novell.ldap.LDAPException.CONNECT_ERROR)
                        break;
                    else
                        continue;
                }
                map.put("baseDN", nextEntry.getDN());   //保存DN
                LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
                Iterator allAttributes = attributeSet.iterator();
                HashMap<String, Object> hashMap = new HashMap<String, Object>();

                while (allAttributes.hasNext()) { //遍歷所有屬性
                    LDAPAttribute attribute = (LDAPAttribute) allAttributes.next();
                    String attributeName = attribute.getName();
                    byte[] byteValue = attribute.getByteValue();
                    String s = new String(byteValue);
                    Enumeration byteValues = attribute.getByteValues();
                    if(byteValues != null){
                        while (byteValues.hasMoreElements()){
                            Object oneVal = byteValues.nextElement();
                            if(attributeName .endsWith("binary")){
                                try {
                                    StringBuffer buffer = readCer(attributeName, oneVal);
                                    hashMap.put(attributeName,buffer.toString());
                                } catch (CertificateException e) {
                                    System.out.println(e.getMessage());
                                }
                            }else  if(oneVal instanceof  String ){
                                hashMap.put(attributeName ,(String) oneVal);
                            } else if(oneVal instanceof  byte []){
                                try {
                                    hashMap.put(attributeName ,new String ((byte[] )oneVal,"UTF-8"));
                                } catch (UnsupportedEncodingException e) {
                                    //TODO
                                }
                            }
                        }
                    }
                }
                map.put("attributes",hashMap);
                mapList.add(map);
                }
            lc.disconnect();
        } catch (com.novell.ldap.LDAPException e) {
            e.printStackTrace();
        }
        return mapList;
    }


    /**
     * @description:統計該節點下的所有數據量
     * @param: [searchFilter, lc, nextEntry]
     * @return: long
     * @exception:
     * @author: dq
     * @date: 13:44 2018/1/26
     */
    public long getTotal(String searchFilter, LDAPConnection lc, String dn) throws com.novell.ldap.LDAPException {
        String attrs[] = {LDAPConnection.NO_ATTRS};
        LDAPSearchResults s = lc.search(dn, LDAPConnection.SCOPE_ONE,searchFilter,attrs,true);
        long total = 0L;
        while (s.hasMore()) {
            s.next();
            total++;
            //TODO 異常處理
        }
        return total;
    }

    /**
     * @description:解析證書
     * @param: [attributeName, oneVal]
     * @return: java.lang.StringBuffer 返回StringBuffer類型的字符串
     * @exception:
     * @author: dq
     * @date: 13:43 2018/1/26
     */
    public  StringBuffer readCer( String attributeName, Object oneVal) throws CertificateException{
        byte[] byteCert = (byte[]) oneVal;
        //轉換成二進制流
        ByteArrayInputStream bain = new ByteArrayInputStream(byteCert);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate oCert = null;
        StringBuffer buffer = new StringBuffer();
        try {
            oCert = (X509Certificate) cf.generateCertificate(bain);
            if (null != oCert) {
                String serianNum = oCert.getSerialNumber().toString();    //序列號
                String issuerDn = oCert.getIssuerDN().getName();        //發布方標識名
                String subDN = oCert.getSubjectDN().getName();            //主體標識
                String sigAlgOID = oCert.getSigAlgOID();                //證書算法OID字符串
                String noAfter = oCert.getNotAfter().toGMTString();        //證書有效期
                String sigAlg = oCert.getSigAlgName().toString();        //簽名算法
                int version = oCert.getVersion();                        //版本號
                String publicKey = oCert.getPublicKey().getFormat();    //公鑰

                buffer.append("版本號: " + version);
                buffer.append("; 序列號: " + serianNum);
                buffer.append("; 簽名算法: " + sigAlg);
                buffer.append("; 簽發者: " + issuerDn);
                buffer.append("; 有效期: " + noAfter);
                buffer.append("; 使用者: " + subDN);
                buffer.append("; 算法OID: " + sigAlgOID);
                buffer.append("; 公鑰: " + publicKey);
            } else {
                organizeCer(buffer);
            }
        } catch (Exception e) {
            //無法解析或者解析失敗
            if(attributeName.equals("userCertificate;binary")){
                organizeCer(buffer);
            }else{
                buffer.append("binary");
            }
        }
        return  buffer;
    }

    /**
     * @description:若解析證書失敗則顯示N/A
     * @param: [buffer]
     * @return: void
     * @exception:
     * @author: dq
     * @date: 13:42 2018/1/26
     */
    public void organizeCer(StringBuffer buffer) {
        buffer.append("版本號: N/A");
        buffer.append("; 序列號: N/A");
        buffer.append("; 簽名算法: N/A");
        buffer.append("; 簽發者: N/A");
        buffer.append("; 有效期: N/A");
        buffer.append("; 使用者: N/A");
        buffer.append("; 算法OID: N/A");
        buffer.append("; 公鑰: N/A");
    }

    /**
     * @description:將List<Map<K,V>>對象轉為String類型
     * @param: [search]
     * @return: java.lang.String
     * @exception:
     * @author: dq
     * @date: 13:41 2018/1/26
     */
    public static String getJsonByListMap(List<Map<String, Object>> search) {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        JSONArray json = JSONArray.fromObject(search, jsonConfig);
        return json.toString();
    }
    /**
     * @description:將Map對象轉為String類型
     * @param: [search]
     * @return: java.lang.String
     * @exception:
     * @author: dq
     * @date: 13:40 2018/1/26
     */
    public static String getJsonByMap(Map<String, Object> search) {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        JSONArray json = JSONArray.fromObject(search, jsonConfig);
        return json.toString();
    }

    private void getErrorMsg(com.novell.ldap.LDAPException e) {
        if(e.getResultCode() == com.novell.ldap.LDAPException.OPERATIONS_ERROR) {//1
            msg = "操作錯誤";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.PROTOCOL_ERROR){//2
            msg = "服務器收到來自客戶端的無效或格式錯誤的請求";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.TIME_LIMIT_EXCEEDED){//3
            msg = "已超出客戶端或服務器指定的操作時間限制";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.SIZE_LIMIT_EXCEEDED){//4
            msg = "超出了客戶端或服務器指定的大小限制";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.AUTH_METHOD_NOT_SUPPORTED){//7
            msg = "綁定操作期間,客戶端請求LDAP服務器時,采用了不支持的身份驗證方法";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.STRONG_AUTH_REQUIRED){//8
            msg = "客戶端請求了需要強認證的操作,如刪除操作";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.LDAP_PARTIAL_RESULTS){//9
            msg = "LDAP部分結果";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.REFERRAL){//10
            msg = "REFERRAL";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.ADMIN_LIMIT_EXCEEDED){//11
            msg = "已超出由管理權限設置的LDAP服務器限制";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.UNAVAILABLE_CRITICAL_EXTENSION){//12
            msg = "服務器不支持該控件或該控件不適合該操作類型";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.CONFIDENTIALITY_REQUIRED){//13
            msg = "會話不受諸如傳輸層安全性(TLS)之類的提供會話機密性的協議的保護";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.SASL_BIND_IN_PROGRESS){//14
            msg = "需要SASL綁定";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.NO_SUCH_ATTRIBUTE){//16
            msg = "指定的屬性在條目中不存在";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.UNDEFINED_ATTRIBUTE_TYPE){//17
            msg = "指定的屬性在LDAP服務器的模式中不存在";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.INAPPROPRIATE_MATCHING){//18
            msg = "搜索過濾器中指定的匹配規則與為該屬性的語法定義的規則不匹配";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.CONSTRAINT_VIOLATION){//19
            msg = "指定的屬性值違反了放置在屬性上的約束。約束可以是大小或內容之一(例如,僅字符串,不是二進制數據)";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.ATTRIBUTE_OR_VALUE_EXISTS){//20
            msg = "指定的屬性值已經作為該屬性的值存在";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.INVALID_ATTRIBUTE_SYNTAX){//21
            msg = "無效的屬性語法";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.NO_SUCH_OBJECT){//32
            msg = "無法找到目標對象";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.ALIAS_PROBLEM){//33
            msg = "取消別名時發生錯誤";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.INVALID_DN_SYNTAX){//34
            msg = "DN的語法不正確";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.ALIAS_DEREFERENCING_PROBLEM){//36
            msg = "無權讀取別名對象的名稱,或者不允許取消引用";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.INAPPROPRIATE_AUTHENTICATION){//48
            msg = "無法正確使用的身份驗證方法";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.INVALID_CREDENTIALS){//49
            msg = "無效的憑證,請檢查用戶和密碼是否正確";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.INSUFFICIENT_ACCESS_RIGHTS){//50
            msg = "訪問權限不夠";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.BUSY){//51
            msg = "無法處理客戶端請求,但重新提交請求,服務器可能會處理該請求";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.UNAVAILABLE){//52
            msg = "正在關閉中,無法處理綁定請求";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.UNWILLING_TO_PERFORM){//53
            msg = "請求違反了服務器的結構規則,定義的限制,無法處理該請求";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.LOOP_DETECT){//54
            msg = "發現別名或引用循環,因此無法完成此請求";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.NAMING_VIOLATION){//64
            msg = "違反了模式的結構規則";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.OBJECT_CLASS_VIOLATION){//65
            msg = "違反條目的對象類規則";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.NOT_ALLOWED_ON_NONLEAF){//66
            msg = "不允許在非葉結點執行此操作";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.NOT_ALLOWED_ON_RDN){//67
            msg = "不允許對RDN執行此操作";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.ENTRY_ALREADY_EXISTS){//68
            msg = "條目已存在";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.OBJECT_CLASS_MODS_PROHIBITED){//69
            msg = "禁止更改對象類的結構規則";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.OTHER){//80
            msg = "未知的錯誤情況";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.LOCAL_ERROR){//82
            msg = "本地錯誤";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.ENCODING_ERROR){//83
            msg = "編碼錯誤";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.DECODING_ERROR){//84
            msg = "解碼錯誤";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.LDAP_TIMEOUT){//85
            msg = "等待結果時超出LDAP客戶端的時間限制";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.AUTH_UNKNOWN){//86
            msg = "未知的身份驗證方法調用綁定方法";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.FILTER_ERROR){//87
            msg = "使用無效的搜索過濾器調用搜索方法";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.USER_CANCELLED){//88
            msg = "用戶取消了LDAP操作";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.NO_MEMORY){//90
            msg = "調用LDAP方法時動態內存分配方法失敗";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.CONNECT_ERROR){//91
            msg = "連接失敗,請檢查配置信息是否正確以及服務是否開啟";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.LDAP_NOT_SUPPORTED){//92
            msg = "請求的功能不支持";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.CONTROL_NOT_FOUND){//93
            msg = "控制未發現";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.NO_RESULTS_RETURNED){//94
            msg = "沒有返回結果";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.MORE_RESULTS_TO_RETURN){//95
            msg = "更多的結果返回";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.CLIENT_LOOP){//96
            msg = "客戶端循環";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.REFERRAL_LIMIT_EXCEEDED){//97
            msg = "超過限制";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.INVALID_RESPONSE){//100
            msg = "無效的響應";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.AMBIGUOUS_RESPONSE){//101
            msg = "請求的響應不明確";
        }else if(e.getResultCode() == com.novell.ldap.LDAPException.TLS_NOT_SUPPORTED){//112
            msg = "不支持TLS";
        } else {
            msg = "操作失敗,錯誤代碼:"+e.getResultCode()+" "+e.getMessage();
        }

    }


}

action類

package com.cn.ccc.ggg.ldap.web.action.clientManager;

import com.cn.ccc.ggg.ldap.LDAPConstants;
import com.cn.ccc.ggg.ldap.bean.entryInfo.PersonEntry;
import com.cn.ccc.ggg.ldap.common.ISysLog;
import com.cn.ccc.ggg.ldap.exception.LDAPException;
import com.cn.ccc.ggg.ldap.model.LDAPConectionInfo;
import com.cn.ccc.ggg.ldap.model.ManagerLog;
import com.cn.ccc.ggg.ldap.service.LDAPConectionInfoService;
import com.cn.ccc.ggg.ldap.util.GGGLDAPUtils;
import com.cn.ccc.ggg.ldap.util.LDAPContextUtils;
import com.cn.ccc.ggg.ldap.web.action.BasePageAction;
import com.opensymphony.xwork2.Preparable;
import net.sf.json.JSONArray;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * 對目錄服務數據進行相應操作
 */
@Namespace("/ldapData")
public class LDAPDataOperaAction extends BasePageAction implements Preparable,ISysLog {

    @Autowired
    private LDAPConectionInfoService ldapConectionInfoService;

    public LDAPConectionInfo ldapConectionInfo;

    private PersonEntry personEntry = new PersonEntry();

    private String searchDN;

    private long totalRecord;

    private String jsonByMap; //操作成功或失敗標識 0:成功,1:失敗

    private InputStream inputStream;// 輸入字節流

    private String downName;//下載文件名稱

    private File ldifFile;// ldif 文件

    private ManagerLog log = new ManagerLog();

    public void prepare() throws Exception {
        log.setOptObj(LDAPContextUtils.getClassMap().get(this.getClass().getSimpleName()));
    }

    public void setLog(ManagerLog log) {
        this.log = log;
    }

    public ManagerLog getLog() {
        return log;
    }


    public File getLdifFile() {
        return ldifFile;
    }

    public void setLdifFile(File ldifFile) {
        this.ldifFile = ldifFile;
    }

    public String getDownName() {
        return downName;
    }

    public void setDownName(String downName) {
        this.downName = downName;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public PersonEntry getPersonEntry() {
        return personEntry;
    }

    public void setPersonEntry(PersonEntry personEntry) {
        this.personEntry = personEntry;
    }

    public String getStatus() {
        return jsonByMap;
    }

    public void setStatus(String jsonByMap) {
        this.jsonByMap = jsonByMap;
    }

    public long getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(long totalRecord) {
        this.totalRecord = totalRecord;
    }

    public String getSearchDN() {
        return searchDN;
    }

    public void setSearchDN(String searchDN) {
        this.searchDN = searchDN;
    }

    public LDAPConectionInfo getLdapConectionInfo() {
        return ldapConectionInfo;
    }

    public void setLdapConectionInfo(LDAPConectionInfo ldapConectionInfo) {
        this.ldapConectionInfo = ldapConectionInfo;
    }

    /**
     * @description:到數據列表界面
     * @param: []
     * @return: java.lang.String
     * @exception:
     * @author: dq
     * @date: 14:10 2018/1/26
     */
    @Action(value = "dataList", results = {@Result(name = "success", location = "/WEB-INF/pages/clientManager/dataList.jsp")})
    public String dataList() throws LDAPException {
        ldapConectionInfo = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        return SUCCESS;
    }

    /**
     * @description:到新增節點界面
     * @param: []
     * @return: java.lang.String
     * @exception:
     * @author: dq
     * @date: 14:09 2018/1/26
     */
    @Action(value = "addDN", results = {@Result(name = "success", location = "/WEB-INF/pages/clientManager/addDN.jsp")})
    public String addDN() throws LDAPException, UnsupportedEncodingException {
        ldapConectionInfo = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        searchDN = new String(ServletActionContext.getRequest().getParameter("searchDN").getBytes("iso-8859-1"),"UTF-8");
        //System.out.println(searchDN+ServletActionContext.getRequest().getParameter("searchDN"));
        return SUCCESS;
    }

    /**
     * @description:到修改屬性值界面
     * @param: []
     * @return: java.lang.String
     * @exception:
     * @author: dq
     * @date: 14:09 2018/1/26
     */
    @Action(value = "toModifyAttrs", results = {@Result(name = "success", location = "/WEB-INF/pages/clientManager/modifyAttrs.jsp")})
    public String toModifyAttrs() throws LDAPException {
        ldapConectionInfo = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        searchDN = ServletActionContext.getRequest().getParameter("baseDN");
        return SUCCESS;
    }

    /**
     * @description:初始化樹形結構,獲取根節點
     * @param: []
     * @return: void
     * @exception:
     * @author: dq
     * @date: 14:08 2018/1/26
     */
    @Action(value = "initBaseDN")
    public void initBaseDN() throws LDAPException {
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        List<Map<String, Object>> search = ldapConectionInfoService.search(info, info.getBaseDN(), "(objectclass=*)", 0, 1);
        String json = LDAPConectionInfoService.getJsonByListMap(search);
        GGGLDAPUtils.sendMsgHttp(json.toString());
    }

    /**
     * @description:搜索指定節點下的子節點,不包括屬性和屬性值
     * @param: []
     * @return: void
     * @exception: 
     * @author: dq
     * @date: 14:06 2018/1/26
     */
    @Action(value = "search")
    public void search() throws LDAPException {
        searchDN = ServletActionContext.getRequest().getParameter("baseDN");
        String currentPageNo = ServletActionContext.getRequest().getParameter("pageNo");
        Integer page = Integer.valueOf(currentPageNo);
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        List<Map<String, Object>> search = ldapConectionInfoService.search(info, searchDN, "(objectclass=*)", 1, page);
        String json = LDAPConectionInfoService.getJsonByListMap(search);
        GGGLDAPUtils.sendMsgHttp(json.toString());
    }

    /**
     * @description:獲取指定節點的屬性和屬性值
     * @param: []
     * @return: void
     * @exception: 
     * @author: dq
     * @date: 14:03 2018/1/26
     */
    @Action(value = "attAndVal")
    public void attAndVal() throws LDAPException {
        searchDN = ServletActionContext.getRequest().getParameter("baseDN");
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        List<Map<String, Object>> search = ldapConectionInfoService.attAndValue(info, searchDN, "(objectclass=*)");
        String json = LDAPConectionInfoService.getJsonByListMap(search);
        GGGLDAPUtils.sendMsgHttp(json.toString());
    }

    /**
     * @description:刪除節點,包括子節點
     * @param: []
     * @return: void
     * @exception: 
     * @author: dq
     * @date: 14:03 2018/1/26
     */
    @Action(value = "deleteDN")
    public void deleteDN() throws LDAPException {
        searchDN = ServletActionContext.getRequest().getParameter("baseDN");
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        Map<String, Object> delete = ldapConectionInfoService.delete(info, 0, searchDN);
        Object status1 = delete.get("status");
        int status = Integer.parseInt(status1.toString());
        if(status == 0){
            StringBuffer inf = new StringBuffer("");
            inf.append("刪除的DN:'").append(searchDN).append("'; ");
            inf.append("服務別名:'").append(info.getServerName()).append("'; ");
            inf.append("IP地址:'").append(info.getIp()).append("'; ");
            inf.append("端口:'").append(info.getPort()).append("'; ");
            inf.append("數據庫:'").append(info.getBaseDN()).append("'; ");
            log.setOptEvent("刪除LDAP數據");
            log.setOperation(info.toString());
            log.setOptType("waring");
        }
        String json = LDAPConectionInfoService.getJsonByMap(delete);

        GGGLDAPUtils.sendMsgHttp(json.toString());
    }

    /**
     * @description:添加節點
     * @param: []
     * @return: void
     * @exception: 
     * @author: dq
     * @date: 14:02 2018/1/26
     */
    @Action(value = "addDNInfo")
    public void addDNInfo() throws LDAPException, UnsupportedEncodingException {
        //System.out.println("dddddd"+searchDN);
        //searchDN = new String(ServletActionContext.getRequest().getParameter("searchDN").getBytes("iso-8859-1"),"UTF-8");
        System.out.println(searchDN);
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        Map<String, Object> stringObjectMap = ldapConectionInfoService.addEntry(info, personEntry, searchDN);
        jsonByMap = LDAPConectionInfoService.getJsonByMap(stringObjectMap);
        Object status1 = stringObjectMap.get("status");
        int status = Integer.parseInt(status1.toString());
        if(status == 0){
            StringBuffer inf = new StringBuffer("");
            inf.append("添加的父條目:'").append(searchDN).append("'; ");
            inf.append("服務別名:'").append(info.getServerName()).append("'; ");
            inf.append("IP地址:'").append(info.getIp()).append("'; ");
            inf.append("端口:'").append(info.getPort()).append("'; ");
            inf.append("數據庫:'").append(info.getBaseDN()).append("'; ");
            log.setOptEvent("新增LDAP數據");
            log.setOperation(info.toString());
            log.setOptType("waring");
        }

        GGGLDAPUtils.sendMsgHttp(jsonByMap.toString());
    }


    /**
     * @description:搜索指定節點的屬性和屬性值
     * @param: []
     * @return: void
     * @exception: 
     * @author: dq
     * @date: 13:57 2018/1/26
     */
    @Action(value = "searchAttrs")
    public void searchAttrs() throws LDAPException {
        searchDN = ServletActionContext.getRequest().getParameter("baseDN");
        System.out.println(searchDN);
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        List<Map<String, Object>> maps = ldapConectionInfoService.attAndValue(info, searchDN, "(objectclass=*)");
        jsonByMap = LDAPConectionInfoService.getJsonByListMap(maps);
        System.out.println(jsonByMap.toString());
        GGGLDAPUtils.sendMsgHttp(jsonByMap.toString());
    }

    /**
     * @description:修改指定節點的屬性值
     * @param: []
     * @return: void
     * @exception: 
     * @author: dq
     * @date: 13:57 2018/1/26
     */
    @Action(value = "modifyAttrs")
    public void modifyAttrs() throws LDAPException {
        searchDN = ServletActionContext.getRequest().getParameter("baseDN");
        System.out.println(searchDN);
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        String json = ServletActionContext.getRequest().getParameter("newAttrVal");
        JSONArray jsonArray = JSONArray.fromObject(json);
        List<Map<String,Object>> mapListJson = (List)jsonArray;
        Map<String, Object> objectMap = ldapConectionInfoService.modifyAttrs(info, searchDN, mapListJson);
        String jsonByMap = LDAPConectionInfoService.getJsonByMap(objectMap);
        Object status1 = objectMap.get("status");
        int status = Integer.parseInt(status1.toString());
        if(status == 0){
            StringBuffer inf = new StringBuffer("");
            inf.append("修改的條目:'").append(searchDN).append("'; ");
            inf.append("服務別名:'").append(info.getServerName()).append("'; ");
            inf.append("IP地址:'").append(info.getIp()).append("'; ");
            inf.append("端口:'").append(info.getPort()).append("'; ");
            inf.append("數據庫:'").append(info.getBaseDN()).append("'; ");
            log.setOptEvent("修改LDAP數據屬性值");
            log.setOperation(info.toString());
            log.setOptType("waring");
        }

        GGGLDAPUtils.sendMsgHttp(jsonByMap.toString());
    }

    /**
     * @description:重命名節點名稱
     * @param: []
     * @return: void
     * @exception: 
     * @author: dq
     * @date: 13:55 2018/1/26
     */
    @Action(value = "renameDN")
    public void renameDN() throws LDAPException {
        String oldDN = ServletActionContext.getRequest().getParameter("oldDN");
        System.out.println(oldDN);
        String newDN = ServletActionContext.getRequest().getParameter("newDN");
        System.out.println(newDN);
        String parentDN = ServletActionContext.getRequest().getParameter("parentDN");
        System.out.println(parentDN);
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        Map<String, Object> stringObjectMap = ldapConectionInfoService.renameRDN(info, oldDN, newDN, parentDN);
        String jsonByMap = LDAPConectionInfoService.getJsonByMap(stringObjectMap);
        Object status = stringObjectMap.get("status");
        int d = Integer.parseInt(status.toString());
        if(d == 0){
            StringBuffer inf = new StringBuffer("");
            inf.append("重命名條目:'").append(oldDN).append("'; ");
            inf.append("服務別名:'").append(info.getServerName()).append("'; ");
            inf.append("IP地址:'").append(info.getIp()).append("'; ");
            inf.append("端口:'").append(info.getPort()).append("'; ");
            inf.append("數據庫:'").append(info.getBaseDN()).append("'; ");
            log.setOptEvent("重命名LDAP條目");
            log.setOperation(info.toString());
            log.setOptType("waring");
        }


        GGGLDAPUtils.sendMsgHttp(jsonByMap.toString());

    }


    /**
     * @description:導出LDIF文件,默認文件名為ldapdb.ldif,下載路徑為berkeleydb環境路徑下
     * @param: [] 
     * @return: java.lang.String
     * @exception: 
     * @author: dq
     * @date: 13:52 2018/1/26
     */
    @Action(value = "exportLDIF", results = { @Result(name = "success", type = "stream", params = {
            "contentType", "application/octet-stream", "inputName",
            "inputStream", "contentDisposition", "attachment;filename=${downName}","bufferSize", "1024" }) })
    public String exporterLDIF() throws LDAPException, FileNotFoundException {
        String bindirpath = GGGLDAPUtils.getLdapWorkPath()+ LDAPConstants.BERKELEYDB_ENVPATH;
        String ldiffilepath = bindirpath + "/"+downName;
        searchDN = ServletActionContext.getRequest().getParameter("baseDN");
        System.out.println(searchDN);
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        ldapConectionInfoService.exportLDIF(info,searchDN,ldiffilepath);
        inputStream = new FileInputStream(ldiffilepath);
        return SUCCESS;
    }

    /**
     * @description:到LDIF導入界面
     * @param: []
     * @return: java.lang.String
     * @exception:
     * @author: dq
     * @date: 17:40 2018/1/26
     */
    @Action(value = "toImportLDIF", results = {@Result(name = "success", location = "/WEB-INF/pages/clientManager/importLDIF.jsp")})
    public String toImportLDIF() throws LDAPException {
        ldapConectionInfo = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        searchDN = ServletActionContext.getRequest().getParameter("baseDN");
        System.out.println(searchDN);
        return SUCCESS;
    }

    /**
     * @description:根據節點導入ldif文件
     * @param: []
     * @return: void
     * @exception: `
     * @author: dq
     * @date: 17:42 2018/1/26
     */
    @Action(value = "importLDIF")
    public void importLDIF() throws LDAPException, UnsupportedEncodingException {
        searchDN = new String(ServletActionContext.getRequest().getParameter("baseDN").getBytes("iso-8859-1"),"UTF-8");
        System.out.println(searchDN);
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        Map<String, Object> stringIntegerMap = ldapConectionInfoService.importLDIF(info, ldifFile);
        String jsonByMap = LDAPConectionInfoService.getJsonByMap(stringIntegerMap);
        System.out.println(jsonByMap);
        GGGLDAPUtils.sendMsgHttp(jsonByMap.toString());

    }

    @Action(value = "numberOfEntries")
    public void numberOfEntries() throws LDAPException {
        System.out.println(searchDN);
        LDAPConectionInfo info = ldapConectionInfoService.findUniqueBy("id", ldapConectionInfo.getId());
        Map<String, Object> numberOfEntries = ldapConectionInfoService.getNumberOfEntries(info, searchDN);
        String jsonByMap = LDAPConectionInfoService.getJsonByMap(numberOfEntries);
        GGGLDAPUtils.sendMsgHttp(jsonByMap.toString());

    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM