I want to fetch data from LDAP server. I can retrieve all users from the list. But now, what I want to do is get the person list under ‘directReports’ attribute. It returns users as java Objects. I cannot convert them to any type other than toString(). What I have done is convert objects to String and use string operations to get users’ names. But I think this is not a proper way to do this. Please give me a suggestion. Thanks!
@Override public Object mapFromAttributes(Attributes attributes) throws NamingException { List<LdapUserDetail> ldapUserDetails = new ArrayList<>(); Attribute directReports = attributes.get("directReports"); NamingEnumeration ne = directReports.getAll(); while(ne.hasMore()){ try { Object item = ne.next(); String emp = item.toString(); emp = Arrays.stream(emp.split(",")).filter(name -> name.startsWith("CN")).collect(Collectors.toList()).get(0).split("CN")[1]; LdapUserDetail ldapUserDetail = new LdapUserDetail(); ldapUserDetail.setName(emp);; ldapUserDetails.add(ldapUserDetail); } catch (Exception e){ e.printStackTrace(); } } logger.info("checklist "+ldapUserDetails.size()); return ldapUserDetails; } } ```
Advertisement
Answer
In LDAP, the directReports
attribute (==field) is of Distinguished Name (DN) type. That is a pointer to another object in the database, in this case a user. When you read it in Java, you get a list of strings.
Typically, the DN is of the format CN=username,OU=department,O=organization
.
CN may also be UID in some implementations. If the CN is what you want, then simply parsing the DN string value with two split()
commands will work:
// We take off at your line String emp = item.toString(); String[] dnParts = emp.split(","); String cnValue = dnParts[0].split("=")[1];
It is wise to do some sanity checking for null
values in between.
If you want to retrieve other details about the user that the DN value is pointing to, you will need to read that object from LDAP in a second operation (LDAP reads are very fast):
// We take off at your line String emp = item.toString(); // Create controls for the LDAP operation SearchControls ctrl = new SearchControls(); // Tell LDAP this is a read ctrl.setSearchScope(SearchControls.OBJECT_SCOPE); // Request all attributes for this object ctrl.setReturningAttributes(new String[] {"*", "+"}); // I assume you have an LdapContext object called ctx NamingEnumeration<SearchResult> results = ctx.search(emp, "objectclass=*", controls); while (results.hasMore()) { // This is your user object with all its attributes SearchResult result = results.next(); // Always close the enumeration to prevent memory leaks results.close(); break; }