IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Java向OpenDs-LDAP中插入数据 -> 正文阅读

[Java知识库]Java向OpenDs-LDAP中插入数据

废话少说,上代码。

import javax.naming.*;
import javax.naming.directory.*;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LdapInsert {

    private static String url = "ldap://192.168.88.146:1389";// ldap服务器地址
    private static String user = "cn=Directory Manager";// ldap用户信息
    private static String passwd = "123456";

    static LdapInsert insertEr = new LdapInsert();
    static LDAPConnection connection = null;

    public static void main(String[] args) {
        try {
            connection = insertEr.getConnection(url, user, passwd);
            Boolean result = insertEr.updateCert(insertEr.initCertEntity("", new Random().nextInt(100)), connection);
            System.out.println("插入结果:" + result);
            connection.close();
            System.out.println("关闭连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private CertEntity initCertEntity(String cerPath, int j) throws Exception {
        CertEntity c = new CertEntity();
        String CN = "CN=注入测试";
        if (cerPath != null && cerPath.trim().length() > 0) {
            CN += "-带证书-";
            byte[] cerFile = readCer(cerPath);
            c.setContent(cerFile);
        } else {
            CN += "-无证书-";
        }
        String i = new Random().nextInt(100000) + "_" + new Random().nextInt(100000) + "_" + j;
        Date d = new Date();
        c.setDn(CN + i + ",OU=OU-" + formatDate4(d) /*+ "-" + new Random().nextInt(16)*/ + ",O=ZYYDD-" + formatDate3(d) + ",C=CN");
        c.setSn(i + "_" + formatDate4(d) + "_" + formatDate3(d));
        c.setTemlateId("1000");
        c.setStatus("5");
        c.setBaseDn("O=ZYYDD Operation CA2,C=CN");
        System.out.println("初始化DN:" + c.getDn());
        return c;
    }

    public String formatDate3(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
        return format.format(date.getTime());
    }

    public String formatDate4(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(date.getTime());
    }

    public byte[] readCer(String cerPath) throws Exception {
        File readfile = new File(cerPath);
        FileInputStream fis = new FileInputStream(readfile);
        int filelength = (int) readfile.length();
        byte[] bytesFile = new byte[filelength];
        fis.read(bytesFile);
        fis.close();
        return bytesFile;
    }

    public LDAPConnection getConnection(String url, String user, String passwd) throws NamingException {
        this.initEnv(url, user, passwd);
        DirContext ctx = new InitialDirContext(this.env);
        LDAPConnection conn = new LDAPConnection(ctx);
        System.out.println("获取连接成功");
        return conn;
    }

    public void initEnv(String url, String user, String passwd) {
        System.setProperty("com.sun.jndi.ldap.connect.pool.initsize", String.valueOf(10));
        System.setProperty("com.sun.jndi.ldap.connect.pool.maxsize", String.valueOf(20));
        System.setProperty("com.sun.jndi.ldap.connect.pool.prefsize", String.valueOf(15));
        System.setProperty("com.sun.jndi.ldap.connect.pool.timeout", String.valueOf(300));
        System.setProperty("com.sun.jndi.ldap.connect.pool.debug", "false");
        this.env = new Hashtable();
        this.env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
        this.env.put("java.naming.provider.url", url);
        this.env.put("com.sun.jndi.ldap.connect.pool", "true");
        this.env.put("java.naming.security.authentication", "simple");
        this.env.put("java.naming.security.principal", user);
        this.env.put("java.naming.security.credentials", passwd);
    }

    public Boolean updateCert(CertEntity cert, LDAPConnection conn) throws Exception {
        try {
            CertEntity entity = new CertEntity();
            entity.setDn(cert.getDn());
            entity.setBaseDn(cert.getBaseDn());
            entity.setContent(cert.getContent());
            entity.setSn(cert.getSn());
            entity.setTemlateId(cert.getTemlateId());
            addDistributionDN(conn, entity);
            return true;
        } catch (Exception ex) {
            System.out.println(cert.getDn() + " 插入异常 " + ex.getMessage());
            return false;
        }
    }

    private void addDistributionDN(LDAPConnection conn, CertEntity entity)
            throws NamingException {
        String baseDN = entity.getBaseDn();
        String distributionDN = entity.getDn();
        Pattern pattern = Pattern.compile("\\s*,\\s*", 2);
        Matcher matcher = pattern.matcher(distributionDN.trim());
        distributionDN = matcher.replaceAll(",");
        int baseDNLen = baseDN.length();
        int distributionDNLen = distributionDN.length();
        String tempEntryDn = "," + distributionDN;
        String tempBaseDn = "," + baseDN;
        if (tempEntryDn.toUpperCase().indexOf(tempBaseDn.toUpperCase()) != -1) {
            String subDN = "";
            if (distributionDNLen > baseDNLen) {
                subDN =
                        distributionDN.substring(0, distributionDN.length() - baseDN.length() - 1).trim();
            }
            boolean baseDNExist = conn.checkEntryExist(baseDN);
            if (!baseDNExist) {
                List<String> dnList = new ArrayList();
                String tDN = baseDN;
                while (tDN.indexOf(",") != -1) {
                    dnList.add(tDN.substring(0, tDN.indexOf(",")));
                    tDN = tDN.substring(tDN.indexOf(",") + 1, tDN.length());
                    if (conn.checkEntryExist(tDN)) {
                        break;
                    }
                }
                dnList.add(tDN);
                String entryDN = null;
                StringBuffer entryDNBF = null;
                int tCount = 0;
                int tSize = dnList.size();
                for (int i = tSize - 1; i >= 0; i--) {
                    entryDNBF = new StringBuffer();
                    if (tCount == 0) {
                        entryDNBF.append((String) dnList.get(i));
                    } else {
                        entryDNBF.append((String) dnList.get(i));
                        entryDNBF.append(",");
                        entryDNBF.append(entryDN);
                    }
                    tCount++;
                    entryDN = entryDNBF.toString().trim();
                    boolean e = conn.checkEntryExist(entryDN);
                    if (!e) {
                        addEntry(conn, entryDN, entity);
                    }
                }
            }
            if (subDN.equals("")) {
                return;
            }
            List<String> dnList = new ArrayList();
            String tDN = subDN;
            while (tDN.indexOf(",") != -1) {
                dnList.add(tDN.substring(0, tDN.indexOf(",")));
                tDN = tDN.substring(tDN.indexOf(",") + 1, tDN.length());
                if (conn.checkEntryExist(tDN)) {
                    break;
                }
            }
            dnList.add(tDN);
            String entryDN = null;
            StringBuffer entryDNBF = null;
            int tCount = 0;
            int tSize = dnList.size();
            for (int i = tSize - 1; i >= 0; i--) {
                entryDNBF = new StringBuffer();
                if (tCount == 0) {
                    entryDNBF.append((String) dnList.get(i));
                } else {
                    entryDNBF.append((String) dnList.get(i));
                    entryDNBF.append(",");
                    entryDNBF.append(entryDN);
                }
                tCount++;
                entryDN = entryDNBF.toString().trim();
                boolean e = conn.checkEntryExist(entryDN + "," + baseDN);
                if (!e) {
                    addEntry(conn, entryDN + "," + baseDN, entity);
                }
            }
        } else {
            List<String> dnList = new ArrayList();
            String tDN = distributionDN;
            while (tDN.indexOf(",") != -1) {
                dnList.add(tDN.substring(0, tDN.indexOf(",")));
                tDN = tDN.substring(tDN.indexOf(",") + 1, tDN.length());
                if (conn.checkEntryExist(tDN)) {
                    break;
                }
            }
            dnList.add(tDN);
            String entryDN = null;
            StringBuffer entryDNBF = null;
            int tCount = 0;
            int tSize = dnList.size();
            for (int i = tSize - 1; i >= 0; i--) {
                entryDNBF = new StringBuffer();
                if (tCount == 0) {
                    entryDNBF.append((String) dnList.get(i));
                } else {
                    entryDNBF.append((String) dnList.get(i));
                    entryDNBF.append(",");
                    entryDNBF.append(entryDN);
                }
                tCount++;
                entryDN = entryDNBF.toString().trim();
                boolean e = conn.checkEntryExist(entryDN);
                if (!e) {
                    addEntry(conn, entryDN, entity);
                }
            }
        }
    }

    private void addEntry(LDAPConnection conn, String dn, CertEntity entity) throws NamingException {
        String headInfo = dn.substring(0, dn.indexOf("=")).toLowerCase();
        String value = "";
        if (dn.indexOf(",") == -1) {
            value = dn.substring(dn.indexOf("=") + 1);
        } else {
            value = dn.substring(dn.indexOf("=") + 1, dn.indexOf(","));
        }
        if (headInfo.trim().equals("c")) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass");
            att.add("top");
            att.add("country");
            atts.put(att);
            conn.add(dn, atts);
        } else if ((headInfo.trim().equals("l")) || (headInfo.trim().equals("st")) || (headInfo.trim().equals("street"))) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass");
            att.add("top");
            att.add("locality");
            atts.put(att);
            conn.add(dn, atts);
        } else if (headInfo.trim().equals("o")) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass", true);
            att.add("top");
            att.add("organization");
            atts.put(att);
            conn.add(dn, atts);
        } else if (headInfo.trim().equals("ou")) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass");
            att.add("top");
            att.add("organizationalUnit");
            atts.put(att);
            conn.add(dn, atts);
        } else if (headInfo.trim().equals("cn")) {
            Attributes atts = new BasicAttributes(true);
            atts.put(new BasicAttribute("objectClass", "jitUser"));
            atts.put(new BasicAttribute("cn", value));
            atts.put(new BasicAttribute("sn", value));
            atts.put(new BasicAttribute("uid", entity.getSn(), true));
            atts.put(new BasicAttribute("jitcertpos", "0"));

            //Attributes atts = new BasicAttributes(true);
            atts.put(new BasicAttribute("objectClass", "jitUser"));
            atts.put(new BasicAttribute("jitDn", entity.getDn()));
            atts.put(new BasicAttribute("cn", getCnFromDn(entity.getDn())));
            atts.put(new BasicAttribute("sn", getCnFromDn(entity.getDn())));
            atts.put(new BasicAttribute("jituserstatus", "5"));
            atts.put(new BasicAttribute("jitusertype", entity.getTemlateId()));
            if (entity.getContent() != null) {
                atts.put(new BasicAttribute("userCertificate;binary", entity.getContent()));
            }
            conn.add(dn, atts);
        } else if (headInfo.trim().equals("sn")) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass");
            att.add("top");
            att.add("inetOrgPerson");
            att.add("idaPerson");
            atts.put(att);
            atts.put(new BasicAttribute("cn", value));
            conn.add(dn, atts);
        } else if (headInfo.trim().equals("dc")) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass");
            att.add("top");
            att.add("domain");
            atts.put(att);
            conn.add(dn, atts);
        } else if (headInfo.trim().equals("uid")) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass");
            att.add("top");
            att.add("inetOrgPerson");
            att.add("idaPerson");
            atts.put(att);
            atts.put(new BasicAttribute("sn", value));
            atts.put(new BasicAttribute("cn", value));
            conn.add(dn, atts);
        } else if (headInfo.trim().equals("e")) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass");
            att.add("top");
            att.add("email");
            atts.put(att);
            conn.add(dn, atts);
        } else if (headInfo.trim().equals("t")) {
            Attributes atts = new BasicAttributes(true);
            Attribute att = new BasicAttribute("objectClass");
            att.add("top");
            att.add("titleObject");
            atts.put(att);
            conn.add(dn, atts);
        }
    }

    public String getCnFromDn(String dn) {
        String cn = null;
        StringTokenizer strToken = new StringTokenizer(dn, ",");
        while (strToken.hasMoreTokens()) {
            String tempCN = strToken.nextToken();
            if (tempCN.trim().toUpperCase().indexOf("CN=") == 0) {
                cn = tempCN.substring(tempCN.indexOf("=") + 1);
            }
        }
        if (cn == null) {
            cn = dn.substring(dn.indexOf("=") + 1, dn.indexOf(","));
        }
        return cn;
    }

    private Hashtable<String, String> env = null;

    public class LDAPConnection {
        private DirContext ctx;
        public Set<String> ENTRY_CACHE = new HashSet();

        public LDAPConnection(DirContext ctx) {
            this.ctx = ctx;
        }

        public void add(String entryDN, Attributes attrs)
                throws NamingException {
            Name compositeName = new CompositeName().add(entryDN);
            this.ctx.createSubcontext(compositeName, attrs);
        }

        public boolean checkEntryExist(String entryDN)
                throws NamingException {
            if (ENTRY_CACHE.contains(entryDN)) {
                return true;
            }
            NamingEnumeration tResults = null;
            if (entryDN == null) {
                return false;
            }
            SearchControls tConstraints = new SearchControls();
            tConstraints.setSearchScope(0);
            try {
                Name searchedName = new CompositeName().add(entryDN);
                tResults = this.ctx.search(searchedName, "(objectclass=*)", tConstraints);

            } catch (NameNotFoundException ex) {
                return false;
            }
            if (tResults != null) {
                tResults.close();
                try {
                    String tmp = entryDN.toUpperCase();
                    if ((tmp.startsWith("C=")) || (tmp.startsWith("O=")) || (tmp.startsWith("OU="))) {
                        ENTRY_CACHE.add(entryDN);
                    }
                } catch (Exception localException) {
                }
                return true;
            }
            return false;
        }

        public void close() {
            try {
                if (this.ctx != null) {
                    this.ctx.close();
                    System.gc();
                }
            } catch (NamingException e) {
                System.out.println("关闭LDAP连接失败:" + e.toString());
            }
        }
    }

    public class CertEntity {
        protected String baseDn = null;
        protected String dn = null;
        private String sn = null;
        private String status = "3";
        private String temlateId = "0";
        private byte[] content = null;

        public String getBaseDn() {
            return baseDn;
        }

        public void setBaseDn(String baseDn) {
            this.baseDn = baseDn;
        }

        public String getDn() {
            return dn;
        }

        public void setDn(String dn) {
            this.dn = dn;
        }

        public byte[] getContent() {
            return this.content;
        }

        public void setContent(byte[] content) {
            this.content = content;
        }

        public String getSn() {
            return this.sn;
        }

        public void setSn(String sn) {
            this.sn = sn;
        }

        public String getStatus() {
            return this.status;
        }

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

        public String getTemlateId() {
            return this.temlateId;
        }

        public void setTemlateId(String temlateId) {
            this.temlateId = temlateId;
        }

    }

}

?

?

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-05-01 15:33:33  更:2022-05-01 15:35:35 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 2:21:01-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码