使用 Spring LDAP 读取数据并映射到 Java Bean 中

[i]写此小文总结一下平时工作的收获。[/i]

入正题,工作涉及到了对 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 用起来都不太方便。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值