java根据ad域 转换为实体类,copy即用

背景
业务需要将ad域里面的信息加载 转为列表

Person.java 实体类
ADUtil.java 工具类

Person.java

import lombok.Data;
import lombok.ToString;
import org.springframework.ldap.odm.annotations.Attribute;

/**
 * 这个方法是用来放你 ad域中的 属性
 * 自行填写域中的属性
 * Attribute 这里用于记录名称。 实际上这种方式没有用上。
 */
@Data
@ToString
public class Person {
    /**
     * 主键
     */
    @Attribute
    private String personId;

    /**
     * 人员姓名
     */
    @Attribute(name = "cn")
    private String personName;
    /**
     * description 描述
     */
    @Attribute(name = "description")
    private String description;

    /**
     * objectCategory 对象类别
     */
    @Attribute(name = "objectCategory")
    private String objectCategory;
    /**
     * 邮箱
     */
    @Attribute(name = "mail")
    private String mail;

    /**
     * memberOf 成员
     */
    @Attribute(name = "memberOf")
    private String memberOf;

    /**
     * badPasswordTime 错误密码的时间
     */
    @Attribute(name = "badPasswordTime")
    private String badPasswordTime;

    /**
     * objectClass 对象属性
     */
    @Attribute(name = "objectClass")
    private String objectClass;

    /**
     * company 公司
     */
    @Attribute(name = "company")
    private String company;

    /**
     * name
     */
    @Attribute(name = "name")
    private String name;

    /**
     * sn 姓
     */
    @Attribute(name = "sn")
    private String sn;

    /**
     * telephoneNumber 座机
     */
    @Attribute(name = "telephoneNumber")
    private String telephoneNumber;

    /**
     * primaryGroupID 主要 组ID
     */
    @Attribute(name = "primaryGroupID")
    private String primaryGroupID;

    /**
     * lastLogon 最后登录时间
     */
    @Attribute(name = "lastLogon")
    private String lastLogon;

    /**
     * lockoutTime 锁定时间
     */
    @Attribute(name = "lockoutTime")
    private String lockoutTime;

    /**
     * physicalDeliveryOfficeName 实物交付办公室名称
     */
    @Attribute(name = "physicalDeliveryOfficeName")
    private String physicalDeliveryOfficeName;

    /**
     * msDS-RevealedDSAs  ms DS公开的DS为
     */
    @Attribute(name = "msDS-RevealedDSAs")
    private String msDSRevealedDSAs;
    /**
     * title  职位
     */
    @Attribute(name = "title")
    private String title;
    /**
     * logonCount 登录次数
     */
    @Attribute(name = "logonCount")
    private String logonCount;
    /**
     * givenName 名
     */
    @Attribute(name = "givenName")
    private String givenName;
    /**
     * displayName 名称
     */
    @Attribute(name = "displayName")
    private String displayName;
    /**
     * pwdLastSet 最后设置密码时间
     */
    @Attribute(name = "pwdLastSet")
    private String pwdLastSet;
    /**
     * userPrincipalName 用户主题名称,用于登录的名称
     */
    @Attribute(name = "userPrincipalName")
    private String userPrincipalName;
    /**
     * department 部门
     */
    @Attribute(name = "department")
    private String department;
    /**
     * distinguishedName 专有名称
     */
    @Attribute(name = "distinguishedName")
    private String distinguishedName;
    /**
     * manager 管理信息
     */
    @Attribute(name = "manager")
    private String manager;
    /**
     * sAMAccountName OP
     */
    @Attribute(name = "sAMAccountName")
    private String sAMAccountName;

}

ADUtil.java

import cn.hutool.json.JSONUtil;
import org.apache.commons.lang.StringUtils;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Optional;

public class ADUtil {

    /**
     * 连接 ad域
     *
     * @param adLdapIP
     * @param port
     * @param username
     * @param password
     * @return
     */
    public static DirContext getDirContext(String adLdapIP, int port, String username, String password) {
        Hashtable<String, String> env = new Hashtable<String, String>();
        DirContext ctx = null;
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://" + adLdapIP + ":" + port);//AD域路径和端口号 一般端口是389
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.REFERRAL, "throw");
        env.put("java.naming.ldap.attributes.binary", "objectGUID");// objectGUID也可以指定为其它属性
        try {
            ctx = new InitialDirContext(env);// 初始化上下文
            System.out.println("身份验证成功!");
        } catch (AuthenticationException e) {
            System.out.println("身份验证失败!");
            e.printStackTrace();
        } catch (javax.naming.CommunicationException e) {
            System.out.println("AD域连接失败!");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("身份验证未知异常!");
            e.printStackTrace();
        }
        return ctx;
    }

    public  ArrayList<Person> getByNameClose(DirContext ctx, String filter) {
        return getByNameClose(ctx,filter);
    }

    /**
         * 根据  filter关键字 连接并且获取 AD 域信息放到 Person List
         *
         * @param ctx
         * @param filter 过滤的关键字.如果关键字为空就查询所有
         * @param close  是否关闭连接,true 关闭连接,flase 不关闭连接
         * @return
         */
        public  ArrayList<Person> getByNameClose(DirContext ctx, String filter, Boolean close) {
            ArrayList<Person> list = new ArrayList<>();
        try {
            //搜索控制器
            SearchControls searchCtls = new SearchControls();
            //设置搜索范围 深度
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            //LDAP搜索过滤器类,此处只获取AD域用户,所以条件为用户user或者person均可
            //语法 https://www.cnblogs.com/chenne69163/p/12084086.html
            //(&(objectCategory=person)(objectClass=user)(name=*))
            // LDAP搜索过滤器类 cn=*name*模糊查询 cn=name 相等查询
            //(|(name=*op1768*)(name=*op546*))
            String searchFilter="(&(objectCategory=person)(objectClass=user)(name=*))";
            if(!StringUtils.isBlank(filter)){
                searchFilter = "(|(name=*" + filter + "*)" + "(mail=*" + filter + "*)" + ")";
            }
            //AD域节点结构

            // 域节点
            String searchBase = "OU=CPCNet User,DC=cpcnet,DC=local";
            searchBase = "DC=cpcnet,DC=local";


            String returnedAtts[] = {"objectClass", "sAMAccountName", "userPrincipalName", "displayName", "name", "mail",
                    "department", "telephoneNumber", "mobile"};
     /*       String returnedAtts[] = { "displayName","url", "employeeID",  "mail",
                    "name", "userPrincipalName", "physicalDeliveryOfficeName",
                    "departmentNumber", "telephoneNumber", "homePhone",
                    "mobile", "department", "sAMAccountName", "whenChanged","mail"}; // 定制返回属性*/
            //设置指定返回的字段,不设置则返回全部
//            searchCtls.setReturningAttributes(returnedAtts);
            // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
            NamingEnumeration<SearchResult> answer = ctx.search(searchBase, searchFilter, searchCtls);

            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) answer.next();
//                System.out.println("<<<::[" + sr.getName() + "]::>>>>");//返回格式一般是CN=xxxx,OU=xxxx
                Attributes attrs = sr.getAttributes();//得到符合条件的属性集
                Person person = new Person();
                person.setPersonName(get(attrs,"cn"));
                person.setDescription(get(attrs,"description"));
                person.setObjectCategory(get(attrs,"objectCategory"));
                person.setMail(get(attrs,"mail"));
                person.setMemberOf(get(attrs,"memberOf"));
                person.setBadPasswordTime(get(attrs,"badPasswordTime"));
                person.setObjectClass(get(attrs,"objectClass"));
                person.setCompany(get(attrs,"company"));
                person.setName(get(attrs,"name"));
                person.setSn(get(attrs,"sn"));
                person.setTelephoneNumber(get(attrs,"telephoneNumber"));
                person.setPrimaryGroupID(get(attrs,"primaryGroupID"));
                person.setLastLogon(get(attrs,"lastLogon"));
                person.setLockoutTime(get(attrs,"lockoutTime"));
                person.setPhysicalDeliveryOfficeName(get(attrs,"physicalDeliveryOfficeName"));
                person.setMsDSRevealedDSAs(get(attrs,"msDSRevealedDSAs"));
                person.setTitle(get(attrs,"title"));
                person.setLogonCount(get(attrs,"logonCount"));
                person.setGivenName(get(attrs,"description"));
                person.setDisplayName(get(attrs,"givenName"));
                person.setPwdLastSet(get(attrs,"pwdLastSet"));
                person.setUserPrincipalName(get(attrs,"userPrincipalName"));
                person.setDepartment(get(attrs,"department"));
                person.setDistinguishedName(get(attrs,"distinguishedName"));
                person.setManager(get(attrs,"manager"));
                person.setSAMAccountName(get(attrs,"sAMAccountName"));
                list.add(person);
            }
            if (close) {
                closeDirContext(ctx);
            }
            return  list;
        } catch (NamingException e) {
            e.printStackTrace();
            System.err.println("Problem searching directory: " + e);
        }
        return  list;
    }



    public  String get(Attributes attrs,String attrID) throws NamingException {
        return Optional.ofNullable(attrs.get((attrID))).isPresent() ? attrs.get(attrID).get().toString(): "";
    }

    public void closeDirContext(DirContext ctx){
        try {
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public  void getRest() {
        String adLdapIP = "10.180.4.249";
        int port = 389;
        String username = "[email protected]";//账号
        String password = "xxxxxx";//密码
        DirContext dirContext = getDirContext(adLdapIP, port, username, password);
        //测试例子
        String filter="op1768";
        List<Person> list=getByNameClose(dirContext,filter,false);
        System.out.println(JSONUtil.toJsonStr(list));
        filter="movie";
        List<Person> list1=getByNameClose(dirContext,filter,false);
        System.out.println(JSONUtil.toJsonStr(list1));

        list=getByNameClose(dirContext,null,false);
        System.out.println(JSONUtil.toJsonStr(list));
        closeDirContext(dirContext);

    }

    public static void main(String[] args) {
        ADUtil adUtil=new ADUtil();
        adUtil.getRest();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章