Search and Lookup Using ContextMapper

The DefaultDirObjectFactory is registered with the ContextSource by default, which means that whenever a context is found in the LDAP tree, its Attributes and Distinguished Name (DN) will be used to construct a DirContextAdapter. This enables us to use a ContextMapper instead of an AttributesMapper to transform found values:

Example 3.1. Searching using a ContextMapper

package com.example.dao;

public class PersonDaoImpl implements PersonDao {
   ...
   private static class PersonContextMapper implements ContextMapper {
      public Object mapFromContext(Object ctx) {
         DirContextAdapter context = (DirContextAdapter)ctx;
         Person p = new Person();
         p.setFullName(context.getStringAttribute("cn"));
         p.setLastName(context.getStringAttribute("sn"));
         p.setDescription(context.getStringAttribute("description"));
         return p;
      }
   }

   public Person findByPrimaryKey(
      String name, String company, String country) {
      Name dn = buildDn(name, company, country);
      return ldapTemplate.lookup(dn, new PersonContextMapper());
   }
}

The above code shows that it is possible to retrieve the attributes directly by name, without having to go through the Attributes and BasicAttribute classes. This is particularly useful when working with multi-value attributes. Extracting values from multi-value attributes normally requires looping through a NamingEnumeration of attribute values returned from the Attributes implementation. The DirContextAdapter can do this for you, using the getStringAttributes() or getObjectAttributes() methods:

Example 3.2. Getting multi-value attribute values using getStringAttributes()

private static class PersonContextMapper implements ContextMapper {
   public Object mapFromContext(Object ctx) {
      DirContextAdapter context = (DirContextAdapter)ctx;
      Person p = new Person();
      p.setFullName(context.getStringAttribute("cn"));
      p.setLastName(context.getStringAttribute("sn"));
      p.setDescription(context.getStringAttribute("description"));
      // The roleNames property of Person is an String array
      p.setRoleNames(context.getStringAttributes("roleNames"));
      return p;
   }
}

The AbstractContextMapper

Spring LDAP provides an abstract base implementation of ContextMapper, AbstractContextMapper. This automatically takes care of the casting of the supplied Object parameter to DirContexOperations. The PersonContextMapper above can thus be re-written as follows:

Example 3.3. Using an AbstractContextMapper

  private static class PersonContextMapper extends AbstractContextMapper {
      public Object doMapFromContext(DirContextOperations ctx) {
         Person p = new Person();
         p.setFullName(context.getStringAttribute("cn"));
         p.setLastName(context.getStringAttribute("sn"));
         p.setDescription(context.getStringAttribute("description"));
         return p;
      }
  }