写此小文总结一下平时工作的收获。
入正题,工作涉及到了对 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 文档中有专门一章是介绍 Java Bean 与 LDAP 数据间的映射,类似 ORM:http://static.springsource.org/spring-ldap/docs/1.3.x/reference/html/odm.html
BTW. 如果是个人做测试的话,OpenDS 是个不错的 LDAP 服务器的选择,Apache DS 和 OpenLDAP 用起来都不太方便。