Spring LDAPでデータを読み込みJava Beanにマッピングする
2737 ワード
この小文を書いて普段の仕事の収穫をまとめます.
本題に入ると、仕事はLDAPに対するCRUD操作に関わり、同僚がJLDAPで書いた冗長コード(主にJLDAPの間違いではない.冗長コード問題はコード再構築とJava反射によって解決できる)に耐えられない.Spring LDAPはLDAP関連プログラムを書くための良い選択の一つであることが分かった(他のフレームワークを深く理解していない).コードを直接入力し、LDAPを操作する必要がある友人に助けを求めます.
LDAP entryとJava Beanマッピングの条件は、LDAP attribute nameがJava Beanの属性名とマッピング関係を持つことであり、ここでLDAP属性名除去接頭辞がJava Beanの属性名である.Spring LDAPドキュメントには、ORMのようなJava BeanとLDAPデータ間のマッピングについて説明する特別な章があります.http://static.springsource.org/spring-ldap/docs/1.3.x/reference/html/odm.html
BTW.個人でテストをする場合、OpenDSは良いLDAPサーバーの選択であり、Apache DSもOpenLDAPも使いにくい.
本題に入ると、仕事はLDAPに対するCRUD操作に関わり、同僚がJLDAPで書いた冗長コード(主にJLDAPの間違いではない.冗長コード問題はコード再構築とJava反射によって解決できる)に耐えられない.Spring LDAPはLDAP関連プログラムを書くための良い選択の一つであることが分かった(他のフレームワークを深く理解していない).コードを直接入力し、LDAPを操作する必要がある友人に助けを求めます.
LdapTemplate ldapTemplate = buildLdapTemplate();
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("oacAttrMsisdn", "1"));
filter.and(new EqualsFilter("oacAttrCategory", "UserProfileRule"));
List list = ldapTemplate.search("oacAttrCategory=UserProfileRule",
filter.encode(), new BeanAttributesMapper(new UserProfileRule()));
private static LdapTemplate buildLdapTemplate() throws Exception {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl("ldap://localhost:389");
contextSource.setBase("dc=example,dc=com");
contextSource.setUserDn("cn=Directory Manage");
contextSource.setPassword("ds");
contextSource.afterPropertiesSet();
LdapTemplate ldapTemplate = new LdapTemplate();
ldapTemplate.setContextSource(contextSource);
return ldapTemplate;
}
public class BeanAttributesMapper implements AttributesMapper {
private List<String> skipAttrs;
private Object bean;
public Object mapFromAttributes(Attributes attributes)
throws NamingException {
NamingEnumeration attrEnumeration = attributes.getAll();
while (attrEnumeration.hasMore()) {
Attribute attr = (Attribute) attrEnumeration.next();
System.out.println(attr.getID() + " : " + attr.get());
String ldapAttr = attr.getID().replace("oacAttr", "");
if (!skipAttrs.contains(ldapAttr))
setProperty(bean, attr.getID().replace("oacAttr", ""),
attr.get());
}
return bean;
}
public 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);
}
}
}
LDAP entryとJava Beanマッピングの条件は、LDAP attribute nameがJava Beanの属性名とマッピング関係を持つことであり、ここでLDAP属性名除去接頭辞がJava Beanの属性名である.Spring LDAPドキュメントには、ORMのようなJava BeanとLDAPデータ間のマッピングについて説明する特別な章があります.http://static.springsource.org/spring-ldap/docs/1.3.x/reference/html/odm.html
BTW.個人でテストをする場合、OpenDSは良いLDAPサーバーの選択であり、Apache DSもOpenLDAPも使いにくい.