I’ve got a fairly straight forward program that performs an LDAP search based on a CN and maps all the returned attributes, here’s the program:
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.query.ConditionCriteria;
import org.springframework.ldap.query.ContainerCriteria;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
public class LDAPSearchTest {
public static void main(String[] args) {
LdapContextSource contextSource = new DefaultSpringSecurityContextSource("ldaps://localhost:636");
contextSource.setUserDn("");
contextSource.setPassword("");
contextSource.setAnonymousReadOnly(false);
contextSource.afterPropertiesSet();
LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
ConditionCriteria condition
= query()
.base("baseDNValue")
.where("cn");
ContainerCriteria filter = condition.is("cnValue");
List<Map<String, List<Object>>> results = ldapTemplate.search(
filter,
new DefaultAttributesMapper());
for (Map<String, List<Object>> groupSearchResult : results) {
for (String attributeName : groupSearchResult.keySet()) {
System.out.println(String.format("t%s", attributeName));
for (Object attributeValue : groupSearchResult.get(attributeName)) {
System.out.println(String.format("tt%s", attributeValue == null ? null : attributeValue.toString()));
}
}
}
}
private static class DefaultAttributesMapper implements AttributesMapper<Map<String, List<Object>>> {
@Override
public Map<String, List<Object>> mapFromAttributes(Attributes attributes) throws NamingException {
Map<String, List<Object>> mappedAttributes = new LinkedHashMap<>();
NamingEnumeration<? extends Attribute> attributesEnumeration = attributes.getAll();
while (attributesEnumeration.hasMore()) {
Attribute nextAttribute = attributesEnumeration.next();
mappedAttributes.put(nextAttribute.getID(), new ArrayList<>());
NamingEnumeration attributeValuesEnumeration = nextAttribute.getAll();
while (attributeValuesEnumeration.hasMore()) {
Object nextAttributeValue = attributeValuesEnumeration.next();
mappedAttributes.get(nextAttribute.getID()).add(nextAttributeValue);
}
}
return mappedAttributes;
}
}
}
For some reason the attribute dn
is not included in the return attributes list, but every other one is (as far as I can see). When I do an equivalent search using ldapsearch
, the dn
attribute is returned in the result. Any insight as to why I’m not able to retrieve the dn back from the Java code would be helpful.