java對Ldap操作2

LdapPersonInfo:

 

package ldap.pojo;

import java.util.List;

/**
 * 
@author 張亮 
 * ldap用戶屬性信息數據類
 
*/

public class LdapPersonInfo {

    
// ldap中用戶的uid屬性
    private String uid;

    
// ldap中用戶的givenName屬性
    private String firstName;

    
// ldap中用戶的sn屬性

    
private String lastName;

    
// ldap中用戶的cn屬性

    
private List cn;

    
// ldap中用戶的telephonenumber屬性
    private String telephone;

    
// ldap中用戶的facsimiletelephonenumber屬性
    private String fax;

    
// ldap中用戶的mail屬性
    private String mail;

    
public LdapPersonInfo() {

    }


    
public LdapPersonInfo(String uid, String firstName, String lastName,
            List cn, String telephone, String fax, String mail) 
{
        
this.uid = uid;
        
this.firstName = firstName;
        
this.lastName = lastName;
        
this.cn = cn;
        
this.telephone = telephone;
        
this.fax = fax;
        
this.mail = mail;
    }


    
public String getFax() {
        
return fax;
    }


    
public void setFax(String fax) {
        
this.fax = fax;
    }


    
public String getFirstName() {
        
return firstName;
    }


    
public void setFirstName(String firstName) {
        
this.firstName = firstName;
    }


    
public String getLastName() {
        
return lastName;
    }


    
public void setLastName(String lastName) {
        
this.lastName = lastName;
    }


    
public String getMail() {
        
return mail;
    }


    
public void setMail(String mail) {
        
this.mail = mail;
    }


    
public String getTelephone() {
        
return telephone;
    }


    
public void setTelephone(String telephone) {
        
this.telephone = telephone;
    }


    
public String getUid() {
        
return uid;
    }


    
public void setUid(String uid) {
        
this.uid = uid;
    }


    
public List getCn() {
        
return cn;
    }


    
public void setCn(List cn) {
        
this.cn = cn;
    }

}

UserDaoLdapImpl for jdk1.42

 

package ldap.imp;

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

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

import ldap.UserDaoLdap;
import ldap.pojo.LdapPersonInfo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;

/**
 * 
@author 張亮 UserDaoLdap接口的實現類,主要實現ldap用戶認證、查詢接口
 * 
 
*/

public class UserDaoLdapImpl implements UserDaoLdap {
    
/**
     * 定義使用springframework對ldap的訪問操作對象 藉助LdapTemplate可以實現大部分對ldap的操作
     * 
     
*/

    
private LdapTemplate ldapTemplate;
    
    
private final String BASEDN_KEY="org.springframework.ldap.base.path";

    
/**
     * 
@param ldapTemplate
     *            spring setter 注入
     
*/

    
public void setLdapTemplate(LdapTemplate ldapTemplate) {
        
this.ldapTemplate = ldapTemplate;
    }


    
/**
     * 獲得所有的用戶名(ldap稱cn),可根據第二個參數指定返回值是否重複
     * 
     * 
     * 
@param scope
     *            取值爲0、1、2,分別對應 SearchControls 類 OBJECT_SCOPE, ONELEVEL_SCOPE,
     *            SUBTREE_SCOPE三個查詢範圍,分別代表 當前對象查詢、當前節點下對象查詢、當前節點所有子目錄查詢
     * 
     * 
@param distinct
     *            true,去掉結構中的重複值;false 允許結果中包含重複值
     * 
     * 
@return 查詢範圍下返回的cn列表
     
*/

    
public List getAllPersonNames(int scope, boolean distinct) {
        
// 存儲查詢結果的集合

        
final ArrayList allPersonCnList = new ArrayList();
        
// 使用ldapTemplate提供的接口查詢,objectclass=person 表示對象爲person的對象

        ldapTemplate.search(
"""(objectclass=person)",
                createSearchControls(scope), 
new AttributesMapper() {
                    
public Object mapFromAttributes(Attributes attrs)
                            
throws NamingException {
                        
// 獲取cn的屬性,用戶名存在cn中

                        Attribute attr 
= attrs.get("cn");
                        
// 若沒有該屬性返回null
                        if (attr == null{
                            
return null;
                        }
 else // 獲取屬性

                            
// 若包含多個cn屬性,需要循環獲取

                            Enumeration ent 
= attr.getAll();
                            
while (ent.hasMoreElements()) {
                                allPersonCnList.add(ent.nextElement()
                                        .toString());
                            }

                        }

                        
return null;
                    }

                }
);
        
// true,去掉結果中的重複值

        
if (distinct) {
            ArrayList templist 
= new ArrayList();
            
for (int i = 0; i < allPersonCnList.size(); i++)
                
if (!templist.contains(allPersonCnList.get(i))) {
                    templist.add(allPersonCnList.get(i));
                }

            
// 返回無重複值的結果
            return templist;
        }

        
// 返回包含重複值的結果
        return allPersonCnList;
    }


    
/**
     * 查詢指定範圍下的所有用戶信息
     * 
     * 
     * 
@param scope
     *            取值爲0、1、2,分別對應 SearchControls 類 OBJECT_SCOPE, ONELEVEL_SCOPE,
     *            SUBTREE_SCOPE三個查詢範圍,分別代表 當前對象查詢、當前節點下對象查詢、當前節點所有子目錄查詢
     * 
     * 
@return 查詢範圍下返回的所有用戶信息列表
     * 
     
*/

    
public List getAllPersons(int scope) {
        
// 使用ldapTemplate提供的接口查詢,objectclass=person 表示對象爲person的對象

        
return ldapTemplate.search("""(objectclass=person)",
                createSearchControls(scope), 
new LdapObjectAttributesMapper());
    }


    
/**
     * 根據Uid查詢用戶信息,*代表任意長度的任意字符
     * 
     * 
     * 
@param uid
     *            用戶的uid
     * 
@param scope
     *            取值爲0、1、2,分別對應 SearchControls 類 OBJECT_SCOPE, ONELEVEL_SCOPE,
     *            SUBTREE_SCOPE三個查詢範圍,分別代表 當前對象查詢、當前節點下對象查詢、當前節點所有子目錄查詢
     * 
     * 
@return 用戶信息
     
*/

    
public List getPersonByUid(String uid, int scope) {
        
// 使用ldapTemplate提供的接口查詢,objectclass=person 表示對象爲person的對象

        
// uid 和 objectclass 組成聯合查詢條件,兩個同時滿足的查詢結果
        return ldapTemplate.search("""(&(objectclass=person)(uid=" + uid
                
+ "))", createSearchControls(scope),
                
new LdapObjectAttributesMapper());
    }


    
/**
     * 查詢包含當前Cn信息的所有用戶,*代表任意長度的任意字符
     * 
     * 
     * 
@param cn
     *            用戶的cn
     * 
@param scope
     *            取值爲0、1、2,分別對應 SearchControls 類 OBJECT_SCOPE, ONELEVEL_SCOPE,
     *            SUBTREE_SCOPE三個查詢範圍,分別代表 當前對象查詢、當前節點下對象查詢、當前節點所有子目錄查詢
     * 
     * 
@return 用戶列表
     
*/

    
public List getPersonByCn(String cn, int scope) {
        
// 使用ldapTemplate提供的接口查詢,objectclass=person 表示對象爲person的對象

        
// cn 和 objectclass 組成聯合查詢條件,兩個同時滿足的查詢結果
        return ldapTemplate.search("",
                
"(&(objectclass=person)(cn=" + cn + "))",
                createSearchControls(scope), 
new LdapObjectAttributesMapper());
    }


    
/**
     * 
@param scope
     *            取值爲0、1、2,分別對應 SearchControls 類 OBJECT_SCOPE, ONELEVEL_SCOPE,
     *            SUBTREE_SCOPE三個查詢範圍,分別代表 當前對象查詢、當前節點下對象查詢、當前節點所有子目錄查詢
     * 
     * 
@return 返回查詢控制器對象
     * 
     
*/

    
private SearchControls createSearchControls(int scope) {
        
// 查詢控制類SearchControls設定查詢範圍
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(scope);
        
return constraints;
    }


    
/**
     * 使用LdapPersonInfo類對象實現複合查詢,屬性中可使用通配符*,*代表任意長度的任意字符
     * 
     * 
     * 
@param ldapPersonInfo
     *            查詢條件
     * 
@param scope
     *            取值爲0、1、2,分別對應 SearchControls 類 OBJECT_SCOPE, ONELEVEL_SCOPE,
     *            SUBTREE_SCOPE三個查詢範圍,分別代表 當前對象查詢、當前節點下對象查詢、當前節點所有子目錄查詢
     * 
     * 
@return 用戶列表
     
*/

    
public List getPersonByPersonEnty(LdapPersonInfo ldapPersonInfo, int scope) {
        
// strb存儲、組裝查詢條件集合

        StringBuffer strb 
= new StringBuffer("(&(objectclass=person)");
        
// uid 屬性

        
if (ldapPersonInfo.getUid() != null && ldapPersonInfo.getUid() != ""{
            strb.append(
"(uid=" + ldapPersonInfo.getUid() + ")");
        }

        
// givenname 屬性

        
if (ldapPersonInfo.getFirstName() != null
                
&& ldapPersonInfo.getFirstName() != ""{
            strb.append(
"(givenname=" + ldapPersonInfo.getFirstName() + ")");
        }

        
// sn 屬性

        
if (ldapPersonInfo.getLastName() != null
                
&& ldapPersonInfo.getLastName() != ""{
            strb.append(
"(sn=" + ldapPersonInfo.getLastName() + ")");
        }

        
// cn 屬性

        
if (ldapPersonInfo.getCn() != null && ldapPersonInfo.getCn().size() > 0{
            
for (int i = 0; i < ldapPersonInfo.getCn().size(); i++)
                strb.append(
"(cn=" + ldapPersonInfo.getCn().get(i) + ")");
        }

        
// telephonenumber 屬性

        
if (ldapPersonInfo.getTelephone() != null
                
&& ldapPersonInfo.getTelephone() != ""{
            strb.append(
"(telephonenumber=" + ldapPersonInfo.getTelephone()
                    
+ ")");
        }

        
// facsimiletelephonenumber 屬性

        
if (ldapPersonInfo.getFax() != null && ldapPersonInfo.getFax() != ""{
            strb.append(
"(facsimiletelephonenumber=" + ldapPersonInfo.getFax()
                    
+ ")");
        }

        
// mail 屬性

        
if (ldapPersonInfo.getMail() != null && ldapPersonInfo.getMail() != ""{
            strb.append(
"(mail=" + ldapPersonInfo.getMail() + ")");
        }

        String filter 
= strb.append(")").toString();
        
return ldapTemplate.search("", filter, createSearchControls(scope),
                
new LdapObjectAttributesMapper());
    }


    
/**
     * 根據dn查找用戶,dn爲base dn 的相對dn.(若basedn爲:dc=koal,dc=com,user
     * dn爲:uid=123,dc=koal,dc=com,則此處只需要提供 123 作爲參數)
     * 
     * 
@param dn
     *            相對base dn的dn參數
     * 
@return 用戶信息
     
*/

    
public LdapPersonInfo getLdapObjectByDn(String dn) {
        
return (LdapPersonInfo) ldapTemplate.lookup(dn,
                
new LdapObjectAttributesMapper());
    }


    
/**
     * 登陸驗證
     * 
     * 
@param userDn
     *            用戶的user dn
     * 
@param password
     *            用戶登陸密碼
     * 
@return 登陸成功返回true,不成功返回false
     
*/

    
private boolean loginCheack(String userDn, String password) {
        
// 獲取DirContext對象
        DirContext ctxs = ldapTemplate.getContextSource().getReadOnlyContext();
        
try {
            
// 組裝登陸ldap需要的信息數據
            Hashtable ht = new Hashtable();
            
// 獲取已有的登陸信息

            ht 
= (Hashtable) ctxs.getEnvironment();
            
// 設置用戶
            ht.put(Context.SECURITY_PRINCIPAL, userDn);
            
// 設置用戶登陸密碼
            ht.put(Context.SECURITY_CREDENTIALS, password);
            
// 設置用戶驗證方式爲simple
            ht.put(Context.SECURITY_AUTHENTICATION, "simple");
            
// 出現異常時表示用當前登陸人登陸失敗

            DirContext c 
= new InitialDirContext(ht);
            c.close();
            
return true;
        }
 catch (Exception e) {
            
// e.printStackTrace();
            System.out.println("login false");
            
return false;
        }
 finally {
            
try {
                ctxs.close();
            }
 catch (Exception ie) {

            }

        }

    }


    
/**
     * 驗證用戶登陸
     * 
     * 
@param uid
     *            用戶uid
     * 
@param password
     *            用戶密碼
     * 
     * 
@return 是否登陸成功
     
*/

    
public boolean userLogin(String uid, String password) {
        
// 獲取用戶id所在ldap中的user dn
        List dnlist = getUserDnByUid(uid);
        
// 根據查詢到的所有dn遍歷,檢查是否某一user dn與用戶密碼可以登陸ldap
        for (int i = 0; i < dnlist.size(); i++{
            
if (loginCheack(dnlist.get(i).toString(), password) == true{
                
return true;
            }

        }

        
return false;
    }


    
/**
     * 查詢用戶user dn
     * 
     * 
@param uid
     *            用戶uid
     * 
     * 
@return 用戶dn列表,當前目錄節點下可能存在多個相同uid的多個user dn
     
*/

    
public List getUserDnByUid(String uid) {
        
// 獲取DirContext對象
        DirContext ctx = ldapTemplate.getContextSource().getReadOnlyContext();
        
// 存儲用戶dn
        ArrayList dn = new ArrayList();
        
try {
            SearchControls constraints 
= new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration en 
= ctx.search("""uid=" + uid, constraints);
            
// 查詢所有用戶

            
while (en != null && en.hasMoreElements()) {
                Object obj 
= en.nextElement();
                
if (obj instanceof SearchResult) {
                    SearchResult si 
= (SearchResult) obj;
                    
// 獲取dn並添加到查詢列表
                    si.getName();
                    Hashtable ht 
= new Hashtable();
                    
// 獲取已有的登陸信息
                    ht = (Hashtable) ctx.getEnvironment();
                    
// 設置用戶
                    String str = ht.get(this.BASEDN_KEY).toString();
                    dn.add(si.getName()
+","+str);
                }

            }

            ctx.close();
        }
 catch (Exception e) {
            e.printStackTrace();
            
try {
                ctx.close();
            }
 catch (Exception ee) {
                ee.printStackTrace();
            }

        }

        
return dn;
    }


    
/**
     * ldap用戶信息數據填充類 將獲取的屬性信息封裝爲LdapObject對象
     * 
     
*/

    
private class LdapObjectAttributesMapper implements AttributesMapper {
        
public Object mapFromAttributes(Attributes attrs)
                
throws NamingException {
            LdapPersonInfo LdapObject 
= new LdapPersonInfo();
            
try {
                
// 獲取並封裝uid屬性

                LdapObject.setUid((String) getAttribute(attrs, 
"uid"));
                
// 獲取並封裝givenname屬性

                LdapObject.setFirstName((String) getAttribute(attrs,
                        
"givenname"));
                
// 獲取並封裝sn屬性

                LdapObject.setLastName((String) getAttribute(attrs, 
"sn"));
                
// 獲取並封裝cn屬性

                LdapObject.setCn(getMoreSameAttributes(attrs, 
"cn"));
                
// 獲取並封裝telephonenumber屬性

                LdapObject.setTelephone((String) getAttribute(attrs,
                        
"telephonenumber"));
                
// 獲取並封裝facsimiletelephonenumber屬性

                LdapObject.setFax((String) getAttribute(attrs,
                        
"facsimiletelephonenumber"));
                
// 獲取並封裝mail屬性

                LdapObject.setMail((String) getAttribute(attrs, 
"mail"));
            }
 catch (NamingException n) {
                n.printStackTrace();
            }

            
// 返回封裝後的用戶對象
            return LdapObject;
        }


        
/**
         * 從屬性列表中獲取指定的屬性
         * 
         * 
         * 
@param attrs
         *            屬性列表
         * 
         * 
@param attrName
         *            需要獲取的屬性
         * 
         * 
@return 返回獲取的屬性值
         * 
         * 
@throws NamingException
         
*/

        
private String getAttribute(Attributes attrs, String attrName)
                
throws NamingException {
            Attribute attr 
= attrs.get(attrName);
            
// 若沒有指定的屬性返回空字符串

            
if (attr == null{
                
return "";
            }
 else {
                
return (String) attr.get();
            }

        }


        
/**
         * 從屬性列表中獲取指定的屬性的所有屬性值
         * 
         * 
         * 
@param attrs
         *            屬性列表
         * 
         * 
@param attrName
         *            需要獲取的屬性
         * 
         * 
@return 返回獲取的屬性值
         * 
         * 
@throws NamingException
         
*/

        
private List getMoreSameAttributes(Attributes attrs, String attrName)
                
throws NamingException {

            Attribute attr 
= attrs.get(attrName);
            List elelist 
= new ArrayList();
            
// 若沒有指定的屬性返回null
            if (attr == null{
                
return null;
            }
 else {
                
// 獲取當前屬性的所有值,添加到返回列表中
                Enumeration ent = attr.getAll();
                
while (ent.hasMoreElements())
                    elelist.add(ent.nextElement().toString());
                
return elelist;
            }

        }

    }


    
private void dispPerson(LdapPersonInfo temp) {
        System.out.println(
"-----------------------------");
        System.out.println(
"User(uid: " + temp.getUid() + ") listing...");
        System.out.println(
"First Name: " + temp.getFirstName());
        System.out.println(
"Last Name: " + temp.getLastName());
        System.out.println(
"Common Name: " + temp.getCn());
        System.out.println(
"User ID: " + temp.getUid());
        System.out.println(
"E-Mail: " + temp.getMail());
        System.out.println(
"Phone: " + temp.getTelephone());
        System.out.println(
"Fax: " + temp.getFax());
        System.out.println(
"List completed.");
        System.out.println(
"-----------------------------n");
    }



}

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