Ldap 之API 简单运用

白越
2023-12-01

直接上代码

package com.bms.service.ldapimpl;

import java.util.ArrayList;
import java.util.List;

import org.jboss.logging.Logger;

import com.bms.service.LdapApi;
import com.bms.utils.PropertyUtil;
import com.unboundid.ldap.sdk.Attribute;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.ldap.sdk.controls.SubentriesRequestControl;

/**
 * @author YeChunBo
 * @time 2017年7月27日
 *
 *       类说明 Ldap java api 操作
 */

public class LdapApiImpl implements LdapApi {

    private static Logger log = Logger.getLogger(LdapApiImpl.class);
    // 当前配置信息
    private static String ldapHost = PropertyUtil.getProperty("ldapHost");
    private static String ldapPort = PropertyUtil.getProperty("ldapPort");
    private static String ldapBindDN = PropertyUtil.getProperty("ldapBindDN");
    private static String ldapPassword = PropertyUtil.getProperty("ldapPassword");
    private static LDAPConnection connection = null;

    /** entry 已存在*/
    private static final Integer EntryIsExist = 0;
    /** entry 不存在*/
    private static final Integer EntryIsNotExist = 3;
    /** entry 操作成功*/
    private static final Integer operateEntrySuccess = 1;
    /** entry 操作失败*/
    private static final Integer operateEntryFail = 2;

    static {
        if (connection == null) {
            try {
                connection = new LDAPConnection(ldapHost, Integer.parseInt(ldapPort), ldapBindDN, ldapPassword);
            } catch (Exception e) {
                log.error("Connect to ldap is failed, the fail message is:" + e.getMessage());
            }
        }
    }

    public Integer createEntry(String baseDN, String uid, String userPwd) {

        Integer operateFlag = new Integer(operateEntryFail);
        log.info("CreateEntry the base DN is: " + baseDN + " ,and the uid is: " + uid + " ,and the usePwd is: "
                + userPwd);

        String entryDN = "uid=" + uid + "," + baseDN;
        try {
            SearchResultEntry entry = connection.getEntry(entryDN);
            if (entry == null) {
                // 不存在则创建
                ArrayList<Attribute> attributes = new ArrayList<Attribute>();
                attributes.add(new Attribute("objectClass", "organizationalPerson", "person", "inetOrgPerson", "top"));
                attributes.add(new Attribute("sn", "person"));
                attributes.add(new Attribute("cn", "person"));
                attributes.add(new Attribute("uid", uid));

                // 如果传的密码参数为空则将其uid设置为其密码
                if ("".equals(userPwd) || userPwd == null)
                    attributes.add(new Attribute("userPassword", uid));
                else
                    attributes.add(new Attribute("userPassword", userPwd));

                connection.add(entryDN, attributes);

                operateFlag = operateEntrySuccess;
                log.info("CreateEntry of 【" + entryDN + "】 is successed, and the operateFlag is " + operateFlag);
            } else {
                operateFlag = EntryIsExist;
                log.warn("The entry of 【" + entryDN + "】 already exists.");
            }
        } catch (Exception e) {
            operateFlag = operateEntryFail;
            log.error("Create entry of 【" + entryDN + "】 is failed, the error message is: " + e.getMessage());
        }
        return operateFlag;
    }

    public List<String> queryLdap(String searchDN, String filter) {
        log.info("QueryLdap the searchDn is: " + searchDN + " ,and the filter is: " + filter);
        ArrayList<String> entryList = new ArrayList<String>();
        try {
            SearchRequest searchRequest = new SearchRequest(searchDN, SearchScope.SUB, "(" + filter + ")");
            searchRequest.addControl(new SubentriesRequestControl());
            SearchResult searchResult = connection.search(searchRequest);

            log.info("A total of 【" + searchResult.getSearchEntries().size() + "】 entry was queried. ");

            int index = 1;
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
                entryList.add(entry.getDN());
                log.info((index++) + "\t" + entry.getDN());
            }
        } catch (Exception e) {
            log.error("Query failed, the fail message is:" + e.getMessage());
        }
        return entryList;
    }

    public Integer deleteEntry(String requestDN) {

        Integer deleteFlag = new Integer(EntryIsNotExist);
        log.info("Delete entry of requestDN " + requestDN);

        try {
            SearchResultEntry entry = connection.getEntry(requestDN);

            if (entry == null) {
                log.warn("DeleteEntry of 【" + requestDN + "】 is not exist.");
                return deleteFlag;
            }
            // 删除
            connection.delete(requestDN);
            deleteFlag = operateEntrySuccess;
            log.info("Delete of 【" + requestDN + "】 is successed.");
        } catch (Exception e) {
            deleteFlag = operateEntryFail;
            log.error("Delete of 【" + requestDN + "】 is failed the error message is : " + e.getMessage());
        }
        return deleteFlag;
    }

//  public static void main(String[] args) {
//      
//      String filter = "objectClass=person";
//
//      LdapApiImpl ldapApiImpl = new LdapApiImpl();
//
//      // 创建entry
        Integer intFlag = ldapApiImpl.createEntry("ou=people,dc=hadoop,dc=apache,dc=org", "bms_test4", "");
        System.out.println(intFlag);
//      
//        // 删除entry
        Integer deleteflag = ldapApiImpl.deleteEntry("uid=bms_test6,ou=people,dc=hadoop,dc=apache,dc=org");
        System.out.println("deleteEntryFlag is " + deleteflag);
//        
//      // 查询entry
        List<String> entryList = ldapApiImpl.queryLdap("ou=people,dc=hadoop,dc=apache,dc=org", filter);
        for (String entry : entryList) {
            System.out.println(entry);
        }
//      
        ldapApiImpl.queryLdap("ou=people,dc=hadoop,dc=apache,dc=org", filter);
//  }

}
package com.bms.service;

import java.util.List;

/**
* @author YeChunBo
* @time 2017年7月27日 
*
* 类说明 
*/

public interface LdapApi {

    /**
     * 查询
     * @param searchDN
     * @param filter
     */
    public List<String> queryLdap(String searchDN, String filter);

    /**
     * 创建条目
     * @param baseDN
     * @param uid
     * @param userPwd
     * @return 0:已存在;1:创建成功; 2: 创建失败
     */
    public Integer createEntry(String baseDN, String uid, String userPwd);

    /**
     * 删除条目
     * @param requestDN
     * @return 0:不存在;1:删除成功; 2: 删除失败
     */
    public Integer deleteEntry(String requestDN);

}

pom.xml 文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>LdapApi</groupId>
  <artifactId>LdapApi</artifactId>
  <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.unboundid/unboundid-ldapsdk -->
        <dependency>
            <groupId>com.unboundid</groupId>
            <artifactId>unboundid-ldapsdk</artifactId>
            <version>4.0.0</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <type>jar</type>
        </dependency>

    </dependencies>

</project>

PropertyUtil.java

package com.bms.utils;

/**
* @author YeChunBo
* @time 2017年7月27日 
*
* 类说明 :properties文件获取工具类
*/
import java.io.*;
import java.util.Properties;

import org.apache.log4j.Logger;

public class PropertyUtil {
    private static final Logger logger = Logger.getLogger(PropertyUtil.class);
    private static Properties props;
    static {
        loadProps();
    }

    synchronized static private void loadProps() {
        logger.info("开始加载properties文件内容.......");
        props = new Properties();
        InputStream in = null;
        try {
            // <!--第一种,通过类加载器进行获取properties文件流-->
            in = PropertyUtil.class.getClassLoader().getResourceAsStream("ldap.properties");
            // <!--第二种,通过类进行获取properties文件流-->
            // in = PropertyUtil.class.getResourceAsStream("/ldap.properties");
            props.load(in);
        } catch (FileNotFoundException e) {
            logger.error("ldap.properties文件未找到");
        } catch (IOException e) {
            logger.error("出现IOException");
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("ldap.properties文件流关闭出现异常");
            }
        }
        logger.info("加载properties文件内容完成...........");
//      logger.info("properties文件内容:" + props);
    }

    public static String getProperty(String key) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }

    public static void main(String[] args) {
        String property = getProperty("ldapHost");
        System.out.println(property);
    }
}

log4j.properties

### \u8bbe\u7f6e###
log4j.rootLogger = INFO,stdout,D,E

### \u8f93\u51fa\u4fe1\u606f\u5230\u63a7\u5236\u62ac ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### \u8f93\u51faDEBUG \u7ea7\u522b\u4ee5\u4e0a\u7684\u65e5\u5fd7\u5230=log/message.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = log/ldap_message.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO  
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### \u8f93\u51faERROR \u7ea7\u522b\u4ee5\u4e0a\u7684\u65e5\u5fd7\u5230=log/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = log/ldap_error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n



 类似资料: