JAVA链接ldap读取数据,并写入MySQL数据库

java链接ldap读取数据,并写入数据到MySQL数据库:

package mysql;

public class MysqlInfo {
    /*public static String url = "jdbc:mysql://10.122.23.164:3306/lenovo_upp?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8";
    public static String user = "upp";
    public static String password = "test";
    public static String driver = "com.mysql.jdbc.Driver";*/

    //测试环境
    public static String url = "jdbc:mysql://10.96.91.186:3306/lenovo_upp_test?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8";
    public static String user = "root";
    public static String password = "test";
    public static String driver = "com.mysql.jdbc.Driver";
}

package ldap;

public class LDAPBean {
    private String itcode;
    private String city;
    private String country;
    private String email;
    private String job_title;
    private String display_name;
    private String employee_type;
    private String department;
    private String manager;
    private String office_address;
    private String ou;
    private String mobile_phone;
    private String work_phone;
    private String when_created;
    private String pwd_last_set;
    private String account_expires;
    private String user_account_control;

    public LDAPBean() {
        this.itcode = "";
        this.city = "";
        this.country = "";
        this.email = "";
        this.job_title = "";
        this.display_name = "";
        this.employee_type = "";
        this.department = "";
        this.manager = "";
        this.office_address = "";
        this.ou = "";
        this.mobile_phone = "";
        this.work_phone = "";
        this.when_created = "";
        this.pwd_last_set = "";
        this.account_expires = "";
        this.user_account_control = "";
    }

    public void setItcode(String itcode) {
        this.itcode = itcode;
    }
    public void setCity(String city) {
        this.city = city;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public void setMail(String email) {
        this.email = email;
    }

    public void setTitle(String job_title) {
        this.job_title = job_title;
    }
    public void setDisplay_name(String display_name) {
        this.display_name = display_name;
    }

    public void setEmployee_type(String employee_type) {
        this.employee_type = employee_type;
    }
    public void setDepartment(String department) {
        this.department = department;
    }

    public void setManager(String manager) {
        this.manager = manager;
    }
    public void setOffice_address(String office_address) {
        this.office_address = office_address;
    }
    public void setOU(String ou) {
        this.ou = ou;
    }
    public void setMobile_phone(String mobile_phone) {
        this.mobile_phone = mobile_phone;
    }

    public void setWork_phone(String work_phone) {
        this.work_phone = work_phone;
    }
    public void setWhenCreated(String when_created) {
        this.when_created = when_created;
    }

    public void setPwdLastSet(String pwd_last_set) {
        this.pwd_last_set = pwd_last_set;
    }
    public void setAccount_expires(String account_expires){
        this.account_expires = account_expires;
    }
    public void  setUserAccountControl(String user_account_control){
        this.user_account_control = user_account_control;
    }

    //getter

    public String getItcode() {
        return itcode;
    }

    public String getCity() {
        return city;
    }

    public String getCountry() {
        return country;
    }

    public String getMail() {
        return email;
    }

    public String getTitle() {
        return job_title;
    }

    public String getDisplay_name() {
        return display_name;
    }

    public String getEmployee_type() {
        return employee_type;
    }

    public String getDepartment() {
        return department;
    }

    public String getManager() {
        return manager;
    }

    public String getOffice_address() {
        return office_address;
    }


    public String getMobile_phone() {
        return mobile_phone;
    }

    public String getWork_phone() {
        return work_phone;
    }

    public String getWhenCreated() {
        return when_created;
    }

    public String getOU() {
        return ou;
    }

    public String getPwdLastSet() {
        return pwd_last_set;
    }
    public String getAccount_expires() {
        return account_expires;
    }

    public String getUserAccountControl() {
        return user_account_control;
    }
}

package ldap;

import mysql.MysqlInfo;

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.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;

public class GetDataFromLdap {
    public static void main(String[] args) {

        String user = "lenovo\\" + "uppladp01";
        String password = "test";

        String tb = "ad_user_ldap_disabled_test_02";

        LdapContext ldapConnect = ldapConnect(user, password);
        ArrayList userInfo = pageSearch(ldapConnect, "disabled accounts");
        System.out.println(userInfo.size());

        Connection conn = mysqlConnect(MysqlInfo.url, MysqlInfo.user, MysqlInfo.password);

        try {
            conn.prepareStatement("truncate " + tb).execute();
            writeToMysql(userInfo,conn,tb);
        } catch (Exception e) {
            e.printStackTrace();
        }

        close(conn,ldapConnect);

        System.out.println("success");
    }

    //建立ldap链接
    private static LdapContext ldapConnect(String user,String password){
        Hashtable env = new Hashtable<>();

        String url     = "ldap://lenovo.com";
        String factory =  "com.sun.jndi.ldap.LdapCtxFactory";

        env.put(Context.INITIAL_CONTEXT_FACTORY,factory);
        env.put(Context.SECURITY_AUTHENTICATION,"simple");
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_PRINCIPAL, user);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.BATCHSIZE, "1000");

        LdapContext ldapContext = null;
        try {
            ldapContext = new InitialLdapContext(env, null);
            System.out.println("ldap connect success");
        } catch (javax.naming.AuthenticationException e) {
            System.out.println("ldap认证失败");
        } catch (NamingException e) {
            System.out.println("ldap参数有误导致连接失败");
        }
        return ldapContext;
    }

    //建立mysql数据库链接
    private static Connection mysqlConnect(String url,String user,String password){
        Connection conn = null;
        try {
            Class.forName(MysqlInfo.driver);
            conn = DriverManager.getConnection(url,user,password);
            System.out.println("mysql connect success");
        } catch (Exception e) {
            System.out.println("mysql url,user,password 参数异常");
        }
        return conn;
    }

    //关闭 mysql连接 和 ldap连接
    private static void close(Connection conn,LdapContext ldapContext){
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("An closed error occurred of mysql");
            }
        }
        if (ldapContext != null){
            try {
                ldapContext.close();
            } catch (NamingException e) {
                System.out.println("An closed error occurred of ldap");
            }
        }
        System.out.println("ldapContext and mysqlConnection has close !!!");
    }

    //ldap的时间戳是从1601年1月1日0时起经过的1E-7秒(即100纳秒)的个数(时间是GMT的,中国的北京的时间需要加上8个小时)
    //例如:以lastLogon、pwdLastSet、accountExpires等属性为代表(输出没有'Z'结尾)
    private static String timeChange(String ldapTime,SimpleDateFormat sdf){
        /*long javaTime = Long.parseLong(ldapTime) - 116445312000000000L;
        long BJTime = Long.parseLong(String.valueOf(javaTime).substring(0, 13)) + 57599875L;
        11644473600125L = 116445312000000000L/10000 - 57599875L
        */
        long BJTime =  Long.parseLong(ldapTime)/10000 - 11644473600125L;
        Date pwdDate = new Date(BJTime);
        return sdf.format(pwdDate);
    }

    //分页从LDAP上查询数据
    private static ArrayList pageSearch(LdapContext ldapContext,String ou){
        //目录树查询参数设置
        SearchControls searchControls = new SearchControls();
        //设置搜索范围(所有目录树的子树)
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        //设置搜索字段
        String[] searchWords = {
                "name"      ,"l"                         ,"c"             ,"mail",
                "title"     ,"displayName"               ,"employeeType"  ,"department",
                "manager"   ,"physicalDeliveryOfficeName","mobile"        ,"telephoneNumber",
                "pwdLastSet","whenCreated"               ,"accountExpires","userAccountControl"
        };
        searchControls.setReturningAttributes(searchWords);

        int pageSize = 1000;
        //用户搜索的过滤表达式(所有用户账号)
        String filter = "sAMAccountName=*";

        //用户目录com/lenovo/User Accounts/+ ou
        //String baseDir = "OU=" + ou +",OU=User Accounts,DC=lenovo,DC=com";

        //CN=0065lo,OU=disabled accounts,DC=lenovo,DC=com
        String baseDir = "OU=" + ou +",DC=lenovo,DC=com";
        //记录进入数据量
        int entryNum = 0;

        byte[] cookie = null;

        ArrayList arr = new ArrayList<>();
        SimpleDateFormat sdf_from = new SimpleDateFormat("yyyyMMddhhmmss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            //分页读取控制
            ldapContext.setRequestControls(new Control[]{new PagedResultsControl(pageSize,Control.CRITICAL)});
            //循环检索数据
            do{
                NamingEnumeration results = ldapContext.search(baseDir, filter, searchControls);
                while (results != null && results.hasMoreElements()){
                    SearchResult searchResult = results.next();
                    LDAPBean ldapBean = new LDAPBean();
                    entryNum ++;
                    Attributes attributes = searchResult.getAttributes();
                    if(attributes != null){
                        NamingEnumeration allAttr = attributes.getAll();

                        ldapBean.setOU(ou);
                        while (allAttr.hasMore()){
                            Attribute attribute = allAttr.next();
                            String key = attribute.getID();
                            String value = attribute.get().toString();

                            if("name".equals(key)){
                                ldapBean.setItcode(value);
                            }else if("l".equals(key)){
                                ldapBean.setCity(value);
                            }else if("c".equals(key)) {
                                ldapBean.setCountry(value);
                            }else if ("mail".equals(key)){
                                ldapBean.setMail(value);
                            }else if ("title".equals(key)){
                                ldapBean.setTitle(value);
                            }else if ("displayName".equals(key)){
                                ldapBean.setDisplay_name(value);
                            }else if ("employeeType".equals(key)){
                                ldapBean.setEmployee_type(value);
                            }else if ("department".equals(key)){
                                ldapBean.setDepartment(value);
                            }else if ("manager".equals(key)) {
                                //对manager字段数据进行清洗
                                ldapBean.setManager(value.split(",")[0].split("=")[1]);
                            }else if ("physicalDeliveryOfficeName".equals(key)){
                                ldapBean.setOffice_address(value);
                            }else if ("mobile".equals(key)){
                                ldapBean.setMobile_phone(value);
                            }else if ("telephoneNumber".equals(key)){
                                ldapBean.setWork_phone(value);
                            }else if ("whenCreated".equals(key)){
                                ldapBean.setWhenCreated((sdf.format(sdf_from.parse(value.substring(0,14)))));
                            }else if ("pwdLastSet".equals(key)) {
                                // ldap 上取到的时间是 nt时间, 需要转化为北京时间
                                ldapBean.setPwdLastSet(timeChange(value,sdf));
                            }else if ("accountExpires".equals(key)){
                                //标记内部员工的信息时,有两个值: 0 和 9223 37203 68547 75807
                                //标记外部员工的信息时,标记为正常的nt时间, 为18个字符的数字
                                if (value.length() == 18){
                                    // ldap 上取到的时间是 nt时间, 需要转化为 北京时间
                                    value = timeChange(value,sdf);
                                }
                                ldapBean.setAccount_expires(value);
                            }else if("userAccountControl".equals(key)){
                                ldapBean.setUserAccountControl(value);
                            }
                        }
                    }
                    arr.add(ldapBean);
                }
                cookie = parseControls(ldapContext.getResponseControls());
                ldapContext.setRequestControls(new Control[]{
                        new PagedResultsControl(pageSize,cookie,Control.CRITICAL)
                });
            }while (cookie != null && cookie.length != 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arr;
    }
    //用于判断数据是否遍历完全
    private static byte[] parseControls(Control[] controls) {
        byte[] cookie = null;
        if (controls != null){
            for (int i=0;i>Next page \n");
                }
            }
        }
        return cookie == null ?  new byte[0]:cookie;
    }

    //写数据到mysql
    private static void writeToMysql(ArrayList arr,Connection conn,String tb) throws Exception{
        //准备写数据
        conn.setAutoCommit(false);
        String sql = "insert INTO "+tb+" (itcode,city,country,mail,title,display_name,employee_type," +
                "department,manager,office_address,ou,mobile_phone,work_phone,when_created,pwd_last_set," +
                "account_expires,user_account_control)"
                + " values (?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?)";
        PreparedStatement pps = conn.prepareStatement(sql);
        pps.clearBatch();
        Iterator ite = arr.iterator();
        while (ite.hasNext()){
            LDAPBean ldapBean = ite.next();
            pps.setString(1,ldapBean.getItcode());
            pps.setString(2,ldapBean.getCity());
            pps.setString(3,ldapBean.getCountry());
            pps.setString(4,ldapBean.getMail());
            pps.setString(5,ldapBean.getTitle());
            pps.setString(6,ldapBean.getDisplay_name());
            pps.setString(7,ldapBean.getEmployee_type());
            pps.setString(8,ldapBean.getDepartment());
            pps.setString(9,ldapBean.getManager());
            pps.setString(10,ldapBean.getOffice_address());
            pps.setString(11,ldapBean.getOU());
            pps.setString(12,ldapBean.getMobile_phone());
            pps.setString(13,ldapBean.getWork_phone());
            pps.setString(14,ldapBean.getWhenCreated());
            pps.setString(15,ldapBean.getPwdLastSet());
            pps.setString(16,ldapBean.getAccount_expires());
            pps.setString(17,ldapBean.getUserAccountControl());
            pps.addBatch();
        }
        pps.executeBatch();
        conn.commit();
    }
}

你可能感兴趣的:(ldap)