【ldap】ldap系列-java对ldap的翻页查询

本文介绍了在Java中如何进行LDAP的翻页查询,以处理大量数据并避免内存溢出,同时提到了高级功能如AD域密码修改和查询翻页等。通过示例展示了查询结果,包括多个cn值,并提供了进阶讨论的QQ群和微信联系方式。
摘要由CSDN通过智能技术生成

有时候ldap管理的数据较多,需要全部查询的时候使用翻页程序,避免内存溢出等异常,并提高查询效率,

一些高级功能,可以加qq群:669293878 或微信:codearch讨论:例如ad域密码(unicodePwd)修改、查询翻页,对ad域的jdk免证书登录等.

查询结果如下:

name: cn=lisi
name: cn=myhrename
>>Next Page 

name: cn=IT-GZ
name: cn=myh
>>Next Page 

name: uid=codearch
name: cn=myhtest
>>Next Page 

Total entries: 6

代码如下:

 

package com.ad.ldaps;

import javax.naming.Context;
import javax.naming.NameClassPair;
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.ldap.*;
import java.util.ArrayList;
import java.util.Hashtable;

/**
 * 翻页获取ldap账号信息
 * 
 * @author codearch qq群:669293878
 *
 */
class LdapPaged {

	static LdapContext ctx = null;
    final static String LDAPURL = "ldap://localhost:389";
    //Set the page size and initialize the cookie that we pass back in subsequent pages
    final static int pageSize = 2;

	public static void main(String[] args) {

	
		ArrayList<String> list  = new ArrayList<String>();
        Hashtable env = new Hashtable();
        String adminName = "cn=Manager,dc=maxcrc,dc=com";
        String adminPassword = "secret";
        String searchBase = "ou=people,dc=maxcrc,dc=com";
        String searchFilter = "cn=*";

        
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

 

        //set security credentials, note using simple cleartext authentication
        env.put(Context.SECURITY_AUTHENTICATION,"simple");
        env.put(Context.SECURITY_PRINCIPAL,adminName);
        env.put(Context.SECURITY_CREDENTIALS,adminPassword);

                

        //connect to my domain controller
        env.put(Context.PROVIDER_URL, LDAPURL);

        try {

 

            // Create the initial directory context

            ctx = new InitialLdapContext(env,null);

        

            // Create the search controls       

            SearchControls searchCtls = new SearchControls();

        

            //Specify the attributes to return

            String returnedAtts[]={"sn","givenName","mail"};

            searchCtls.setReturningAttributes(returnedAtts);

        

            //Specify the search scope

            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

 



            byte[] cookie = null;

 

            //Request the paged results control

            Control[] ctls = new Control[]{new PagedResultsControl(pageSize,true)};

            ctx.setRequestControls(ctls);

 

            //initialize counter to total the results

            int totalResults = 0;
            int max_uid = 1000;
            

 

            // Search for objects using the filter
            String[] attributeNames = {"uidNumber"};
 

            do {

                NamingEnumeration results = ctx.search(searchBase, searchFilter, searchCtls);

 

                    // loop through the results in each page
                    while (results != null && results.hasMoreElements()) {

                    	NameClassPair sr = (NameClassPair)results.next();
		
		 
                    	String ncpName = sr.getName();
		                //print out the name 
		
		                System.out.println("name: " + ncpName);
		                //increment the counter
		
		                totalResults++; 
		                list.add(ncpName);
		                
		                /**
		                // 对特殊字符的DN跳过
		                //if ((ncpName + "," + searchBase).indexOf("\"") != -1 || (ncpName + "," + searchBase).indexOf("/") != -1) {continue;}
		                Attributes atts = ctx.getAttributes(ncpName + "," + searchBase, attributeNames);
		                //获取对象属性
		                Attribute uidnumber = atts.get("uidNumber");
		                if(uidnumber!=null) {
		                	String value = (String) uidnumber.get();
		                	//System.out.println(value+"uidNumber:"+uidnumber.toString());
		                	int uidn = Integer.valueOf(value);
		                	//System.out.println(ncpName+" "+uidn); 
		                	if(uidn > max_uid) {
		                		max_uid = uidn;
		                	}
		                	
		                }
		                */

                    }

    

    

            // examine the response controls

            cookie = parseControls(ctx.getResponseControls());

 

            // pass the cookie back to the server for the next page
            ctx.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

 

            } while ((cookie != null) && (cookie.length != 0));
                System.out.println("Total entries: " + totalResults);
            } 

        catch (NamingException e) {

            System.err.println("Paged Search failed." + e);

            }   

        catch (java.io.IOException e) {

            System.err.println("Paged Search failed." + e);

            } 
       LdapPaged p = new LdapPaged();
       System.out.println(list.size());
       long maxid = 1000;
       for(String userName : list) {
    	   searchBase = "ou=people,dc=maxcrc,dc=com";
    	   try {
    		   
			long uid = p.searchByUserNameUidNumber(searchBase, userName);
			if(uid > maxid) {
				maxid = uid;
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       }
       
       maxid = maxid+1;
       
       System.out.println("最大uid:"+maxid);
       
       if (ctx != null) {
    	   try {
			ctx.close();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       }
       

    }

 

    static byte[] parseControls(Control[] controls) throws NamingException 
{

        byte[] cookie = null;

 

        if (controls != null) {

 

                for (int i = 0; i < controls.length; i++) {

                if (controls[i] instanceof PagedResultsResponseControl) {

                    PagedResultsResponseControl prrc = (PagedResultsResponseControl)controls[i];

                    cookie = prrc.getCookie();

                    System.out.println(">>Next Page \n");

                }

                }

        }

 

        return (cookie == null) ? new byte[0] : cookie;

        }
    
    
    /**
     * @Description:指定搜索节点搜索指定域用户
     * @author erek
     * @throws Exception 
     * @date 2018-07-03
     */
    public long searchByUserNameUidNumber(String searchBase, String userName) throws Exception {
    	long uidn = 0;
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchFilter = userName;
        String returnedAtts[] = { "memberOf" }; //定制返回属性
        searchCtls.setReturningAttributes(returnedAtts); //设置返回属性集
        String[] attributeNames = { "memberOf", "uidNumber","name","objectClass"};
        
		/*
		 * try { NamingEnumeration<SearchResult> answer = dc.search(searchBase,
		 * searchFilter, searchCtls);
		 * 
		 * return answer.next(); } catch (Exception e) {
		 * System.err.println("指定搜索节点搜索指定域用户失败"); e.printStackTrace(); }
		 */
        
        NamingEnumeration<?> answer = ctx.search(searchBase, searchFilter, searchCtls);
        //NamingEnumeration<SearchResult> answer = dc.search(searchBase, searchFilter, searchCtls);
        while (answer.hasMoreElements()) {
            //SearchResult sr = (SearchResult) answer.next();
        	//System.out.println(sr.getName());
            NameClassPair ncp = (NameClassPair) answer.next();
            String ncpName = ncp.getName();
            // 对特殊字符的DN跳过
            //if ((ncpName + "," + searchBase).indexOf("\"") != -1 || (ncpName + "," + searchBase).indexOf("/") != -1) {continue;}
            Attributes atts = ctx.getAttributes(ncpName + "," + searchBase, attributeNames);
            //获取对象属性
            
            Attribute uidnumber = atts.get("uidNumber");
            /**
            if(uidnumber!=null) {
            	String value = (String) uidnumber.get();
            	System.out.println(ncpName+" "+uidnumber.toString()); 
            }
            */
            
            if(uidnumber!=null) {
            	String value = (String) uidnumber.get();
            	//System.out.println(value+"uidNumber:"+uidnumber.toString());
            	uidn = Long.valueOf(value);
            	System.out.println(ncpName+" "+uidn); 
            }
            
            /**
            Attribute objectClassAuttribute = atts.get("objectClass");
            if(objectClassAuttribute != null) {
            	
				 	if (objectClassAuttribute.toString().indexOf("user") != -1) {
					 //获取用户是user
					 System.out.println(atts+ncpName + "," + searchBase);
				 	}
            }
            */

                       
        
            
        }
        
        return uidn;
        
    }
    

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ErekSZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值