项目中用的到一个简单查询ldap AD 的东西。

package com.ibm.gps.services;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.PagedResultsControl;
import javax.naming.ldap.PagedResultsResponseControl;

import com.ibm.gps.model.AccountInfo;
import com.ibm.gps.util.JsonUtil;



public class LdapOperationService {
    public int UF_ACCOUNTDISABLE = 0x0002;
    public int UF_PASSWD_NOTREQD = 0x0020;
    public int UF_PASSWD_CANT_CHANGE = 0x0040;
    public int UF_NORMAL_ACCOUNT = 0x0200;
    public int UF_DONT_EXPIRE_PASSWD = 0x10000;
    public int UF_PASSWORD_EXPIRED = 0x800000;    
    public int pageSize = 500;    
    public boolean supportsPagedResults = true;
    public LdapContext  context = null;
    

    /**
     * TEST CONNECTING TO LDAP .
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        LdapOperationService ldapop=new LdapOperationService();
        ldapop.init();
        try{            
            ldapop.searchLdapUserListByName("a");            
        }
        catch(Exception e){
            throw new Exception("search ldap error!");
        }
        finally{
            ldapop.close();
        }    
    }
    
    public void init(){        
        String user = "administrator@ecm.ibm.local";
        String pwd = "filenet";
        String hostportname = "ldap://9.181.24.136:389/cn=users,dc=ecm,dc=ibm,dc=local";
        
        Hashtable m_env = new Hashtable();        
        m_env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");        
        m_env.put(Context.PROVIDER_URL, hostportname);        
        m_env.put(Context.SECURITY_AUTHENTICATION, "simple");
        m_env.put(Context.SECURITY_PRINCIPAL, user);
        m_env.put(Context.SECURITY_CREDENTIALS, pwd);        
        System.out.println("Ok, authenticated");
        try{
            context = new InitialLdapContext(m_env,null);    
        }catch(javax.naming.AuthenticationException e){
                System.out.println("fail");
             }catch(Exception e){
                     System.out.println("error��"+e);
             }    
    }
    
    public void close(){
        if(context != null)
        {
            try
            {
                context.close();
            }
            catch (NamingException e)
            {
                System.out.println("NamingException in close():"+e);
            }
        }    
    }
    
    public List<AccountInfo> listIncrementally(String username) throws NamingException, Exception{
        List<AccountInfo> accountList=new ArrayList<AccountInfo>();
        if (supportsPagedResults){
            context.setRequestControls(new Control[] {new PagedResultsControl(pageSize, Control.CRITICAL)});
        }
        String userFilter=null==username?"":username.trim();
        userFilter="".equals(userFilter)?"*":userFilter+"*";
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] retAtt =  {"cn", "sn", "telephonenumber", "name", "mail", "givenName","userAccountControl" };
        constraints.setReturningAttributes(retAtt);
        String searchCondition =  "(&(objectClass=user)(cn="+userFilter+")(!(userAccountControl:1.2.840.113556.1.4.803:=" + Integer.toString(UF_ACCOUNTDISABLE) + ")))";
        System.out.println("-");
        int counter = 0;
        byte[] b = null;
        do {        
            NamingEnumeration results = context.search("", searchCondition,constraints);
            if (results != null){
                int subcounter = 0;
                while (results.hasMoreElements()) {
                    subcounter++;
                    SearchResult si = (SearchResult)results.nextElement();
                    counter++;                    
                    AccountInfo accountInfo=new AccountInfo();
                    accountInfo.setUserName(si.getName().substring(3));
                    accountInfo.setEmail(null==si.getAttributes().get("mail")?"":si.getAttributes().get("mail").toString().substring(6));
                    accountInfo.setFirstName(null==si.getAttributes().get("givenName")?"":si.getAttributes().get("givenName").toString());
                    accountList.add(accountInfo);
                }
                System.out.println(searchCondition + " returned " + subcounter );
            }
            
            if (supportsPagedResults){
                b =((PagedResultsResponseControl)context.getResponseControls()[0]).getCookie();
            }
            
            if((b != null)&&(supportsPagedResults))
            {
                System.out.println("--NEW PAGE-");
                context.setRequestControls(new Control[] {new PagedResultsControl(pageSize,b, Control.CRITICAL)});
            }
        } while(b != null);
        System.out.println("Returned overall:" + counter );
        return accountList;
    }
    
    public String searchLdapUserListByName(String username) throws Exception{
        String jsonStr="";
        try{
            init();            
            List<AccountInfo> accountList=listIncrementally(username);
            jsonStr=JsonUtil.list2json(accountList);
            System.out.println(jsonStr);
        }
        finally{
            close();
        }
        return jsonStr;
    }

}


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.