I find it strange that on querying ldap, it returns the information in LDIF form(hopefully am right about this inference) which is fine, but the information is returned as String object instead of a (some) ldap object (like user, name or group etc). The problem is to extract any user or group info I am required to do string processing which is tedious and error prone. So I am trying to explore if there is any means where I can still use JDK inbuilt API and get the query response as LDAP objects.
Below is the code with which I am not glad - (quick reference to last five lines will help)
//code to setup env object - followed by below code
DirContext context = new InitialDirContext(env);
SearchControls searchCtls = new SearchControls();
searchCtls.setCountLimit(0);
searchCtls.setReturningAttributes(new String[] { "memberOf", "cn", "member"});
// searchCtls.setReturningAttributes(ldapSearchAttributes.split(","));
// searchCtls.setReturningAttributes(("member").split(","));
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer = context.search(searchBase, "(" + "CN=" + "someldapgroup" + ")", searchCtls);
System.out.println("answer:" + answer);
Map<String, Object> amap = null;
if (answer.hasMoreElements()) {
SearchResult sr = answer.next();
System.out.println("sr: " + sr);
System.out.println();
//Attributes attrs = answer.next().getAttributes();
Attributes attrs = sr.getAttributes();
System.out.println("attrs: " + attrs);
if (attrs != null) {
amap = new HashMap<String, Object>();
NamingEnumeration<? extends Attribute> ne = attrs.getAll();
//Attributes a = attrs.get(attrID);
while (ne.hasMore()) {
Attribute attr = ne.next();
System.out.println("attr: " + attr);
if (attr.getID().equalsIgnoreCase("memberOf") || attr.getID().equalsIgnoreCase("member")) {
NamingEnumeration emueration = attr.getAll();
List groups = new ArrayList();
while (emueration.hasMore()) {
Object obj =emueration.next();
groups.add(obj);
System.out.println(obj.getClass());
//LdapName name = (LdapName) obj;
System.out.println("obj: " + obj);
The last few lines are what I am bothered. The last but third line System.out.println(obj.getClass());
prints class String, I would like this obj type as some ldap object like LdapName
or Name
etc. Casting as done on line //LdapName name = (LdapName) obj;
does not work so commented it out.
Is there anyway using JDK api to get the query result as ldap objects not as String?? If not with JDK API what is the next best API to use for JAVA folks.