Implementing a Request Control DirContextProcessor

The LDAPv3 protocol uses Controls to send and receive additional data to affect the behavior of predefined operations. In order to simplify the implementation of a request control DirContextProcessor, Spring LDAP provides the base class AbstractRequestControlDirContextProcessor. This class handles the retrieval of the current request controls from the LdapContext, calls a template method for creating a request control, and adds it to the LdapContext. All you have to do in the subclass is to implement the template method createRequestControl, and of course the postProcess method for performing whatever you need to do after the search.

public abstract class AbstractRequestControlDirContextProcessor implements
      DirContextProcessor {

   public void preProcess(DirContext ctx) throws NamingException {
      ...
   }

   public abstract Control createRequestControl();
}

A typical DirContextProcessor will be similar to the following:

Example 5.1. A request control DirContextProcessor implementation

package com.example.control;

public class MyCoolRequestControl extends AbstractRequestControlDirContextProcessor {
   private static final boolean CRITICAL_CONTROL = true;
   private MyCoolCookie cookie;
   ...
   public MyCoolCookie getCookie() {
      return cookie;
   }

   public Control createRequestControl() {
      return new SomeCoolControl(cookie.getCookie(), CRITICAL_CONTROL);
   }

   public void postProcess(DirContext ctx) throws NamingException {
      LdapContext ldapContext = (LdapContext) ctx;
      Control[] responseControls = ldapContext.getResponseControls();

      for (int i = 0; i < responseControls.length; i++) {
         if (responseControls[i] instanceof SomeCoolResponseControl) {
            SomeCoolResponseControl control = (SomeCoolResponseControl) responseControls[i];
            this.cookie = new MyCoolCookie(control.getCookie());
         }
      }
   }
}

Note

Make sure you use LdapContextSource when you use Controls. The Control interface is specific for LDAPv3 and requires that LdapContext is used instead of DirContext. If an AbstractRequestControlDirContextProcessor subclass is called with an argument that is not an LdapContext, it will throw an IllegalArgumentException.