背景
使用spring-ldap操作LDAP,完成LdapTemplate設(shè)置后,進(jìn)行多條件查詢,因?yàn)樾枨笫悄軌蚨鄺l件查詢,所以在使用ldapTemplate.search系列方法時(shí),著重考慮了下面的重載實(shí)現(xiàn),第二個(gè)參數(shù)直接寫過濾條件,只要按過濾語法書寫即可,勝任各種復(fù)雜查詢。
List<LdapUser> users = ldapTemplate.search("ou=People", "(&(objectClass=person)(smart-type=E1))", new AttributesMapper<LdapUser>() {
@Override
public LdapUser mapFromAttributes(Attributes attributes) throws NamingException {
return null;
}
});
但是這個(gè)查詢的,不能使用spring-ldap的ODM,不能把LDAP返回的查詢結(jié)果,直接轉(zhuǎn)成POJO;也就是需要自己把Attributes attributes轉(zhuǎn)成我需要的LdapUser實(shí)體對(duì)象。
LdapUser.java如下
import lombok.Getter;
import lombok.Setter;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;
import javax.naming.Name;
@Setter
@Getter
@Entry(objectClasses = { "inetOrgPerson" ,"top","person" },base="ou=People") // ou=Internal, (只指定People,可按uid查詢單個(gè)人員)
public class LdapUser extends BaseDTO {
@Id
protected Name dn;
@Attribute(name = "uid")
protected String uid;
@Attribute(name = "smart-type")
protected String userType;
@Attribute(name = "mail")
protected String mail;
@Attribute(name = "mobile")
protected String mobile;
@Attribute(name = "departmentNumber")
protected String deptId;
@Attribute(name = "departmentName")
protected String deptName;
// ...
}
}
這個(gè)POJO使用了spring-ldap 的ODM注解,類和屬性分別使用了@Entry
和@Attribute(name = "uid"),其中@Attribute 中的name則標(biāo)識(shí)LDAP查詢返回的Attributes 中的一個(gè)屬性的名稱。
下面要做的反射任務(wù)
就是讀取到POJO 這個(gè)LdapUser實(shí)體類中所有有帶Attribute的屬性,拿取到name后,從查詢返回結(jié)果的Attributes 中遍歷拿到對(duì)應(yīng)name的 值,利用反射,給bean設(shè)置屬性值。實(shí)現(xiàn)如下:
List<LdapUser> users = ldapTemplate.search("ou=People", "(&(objectClass=person)(smart-type=E1))", new AttributesMapper<LdapUser>() {
@Override
public LdapUser mapFromAttributes(Attributes attributes) throws NamingException {
LdapUser bean = null;
if (LdapUser.class.isAnnotationPresent(Entry.class)) {//是否加@Entry
try {
bean = LdapUser.class.newInstance();
} catch (Exception e) {
throw new RuntimeException("反射創(chuàng)建PIJO[<T extends BaseDTO>]實(shí)例對(duì)象失敗",e);
}
Field[] fields = LdapUser.class.getDeclaredFields();//拿到bean對(duì)應(yīng)的屬性
for (Field field : fields) {//遍歷POJO 所有屬性
boolean fieldHasAnno = field.isAnnotationPresent(Attribute.class);//類屬性上是否加@Attribute(name = "smart-type")
if (fieldHasAnno) {
Attribute fieldAnno = field.getAnnotation(Attribute.class);
String name = fieldAnno.name();//注解的name值,如smart-type
for (NamingEnumeration attrEnumeration = attributes.getAll(); attrEnumeration.hasMore(); ) {
javax.naming.directory.Attribute attr = (javax.naming.directory.Attribute) attrEnumeration.next();
String ldapAttr = attr.getID();
if (ldapAttr.equals(name)) {
String ldapValue = attr.get().toString();
setProperty(bean, field.getName(), ldapValue);//反射:給bean設(shè)置屬性值
} else {
continue;
}
}
}
}
} else {
throw new RuntimeException("PIJO[<T extends BaseDTO>]需使用@Entry注解");
}
return bean;
}
});
/**
* 反射:給bean設(shè)置屬性值
*
* @param bean
* @param name
* @param value
*/
private void setProperty(Object bean, String name, Object value) {
String setterName = "set" + StringUtils.capitalize(name);
Method setter;
try {
setter = bean.getClass().getMethod(setterName, value.getClass());
setter.invoke(bean, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
因?yàn)榭紤]到通用性,就把這一部分反射的工作抽象出來,用泛型替換具體類型,
實(shí)現(xiàn)了一個(gè)通用的轉(zhuǎn)化ConvertAttributesMapper
import org.apache.commons.lang3.StringUtils;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.Entry;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 實(shí)現(xiàn)Attributes 轉(zhuǎn)成POJO
*/
public class ConvertAttributesMapper<T extends BaseDTO> implements AttributesMapper {
Class<T> clazz;
public ConvertAttributesMapper(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public T mapFromAttributes(Attributes attributes) throws NamingException {
T bean = null;
if (clazz.isAnnotationPresent(Entry.class)) {//是否加@Entry
try {
bean = clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException("反射創(chuàng)建PIJO[<T extends BaseDTO>]實(shí)例對(duì)象失敗",e);
}
Field[] fields = clazz.getDeclaredFields();//拿到bean對(duì)應(yīng)的屬性
for (Field field : fields) {//遍歷POJO 所有屬性
boolean fieldHasAnno = field.isAnnotationPresent(Attribute.class);//類屬性上是否加@Attribute(name = "smart-type")
if (fieldHasAnno) {
Attribute fieldAnno = field.getAnnotation(Attribute.class);
String name = fieldAnno.name();//注解的name值,如smart-type
for (NamingEnumeration attrEnumeration = attributes.getAll(); attrEnumeration.hasMore(); ) {
javax.naming.directory.Attribute attr = (javax.naming.directory.Attribute) attrEnumeration.next();
String ldapAttr = attr.getID();
if (ldapAttr.equals(name)) {
String ldapValue = attr.get().toString();
setProperty(bean, field.getName(), ldapValue);//反射:給bean設(shè)置屬性值
} else {
continue;
}
}
}
}
} else {
throw new RuntimeException("PIJO[<T extends BaseDTO>]需使用@Entry注解");
}
return bean;
}
/**
* 反射:給bean設(shè)置屬性值
*
* @param bean
* @param name
* @param value
*/
private void setProperty(Object bean, String name, Object value) {
String setterName = "set" + StringUtils.capitalize(name);
Method setter;
try {
setter = bean.getClass().getMethod(setterName, value.getClass());
setter.invoke(bean, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
//使用樣例
AttributesMapper attributesMapper = new ConvertAttributesMapper<LdapUser>(LdapUser.class);
List<LdapUser> users = ldapTemplate.search("ou=People", "(&(objectClass=person)(smart-type=E1))", attributesMapper);
ps:BaseDTO是一個(gè)空的抽象類。