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;
        }

    }

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值