/**
  * Returns the dir sync flags in the supplied response or -1 if no flags exists.
  *
  * @param response of a previous dir sync operation
  * @return dir sync flags or -1
  */
 protected long getDirSyncFlags(final Response<SearchResult> response) {
   long flags = -1;
   final DirSyncControl ctl = (DirSyncControl) response.getControl(DirSyncControl.OID);
   if (ctl != null) {
     flags = ctl.getFlags();
   }
   return flags;
 }
 /**
  * Returns the dir sync cookie in the supplied response or null if no cookie exists.
  *
  * @param response of a previous dir sync operation
  * @return dir sync cookie or null
  */
 protected byte[] getDirSyncCookie(final Response<SearchResult> response) {
   byte[] cookie = null;
   final DirSyncControl ctl = (DirSyncControl) response.getControl(DirSyncControl.OID);
   if (ctl != null) {
     if (ctl.getCookie() != null && ctl.getCookie().length > 0) {
       cookie = ctl.getCookie();
     }
   }
   return cookie;
 }
 /**
  * Performs a search operation with the {@link DirSyncControl}. The supplied request is modified
  * in the following way:
  *
  * <ul>
  *   <li>{@link SearchRequest#setControls( org.ldaptive.control.RequestControl...)} is invoked
  *       with {@link DirSyncControl}, {@link ShowDeletedControl}, and {@link ExtendedDnControl}
  * </ul>
  *
  * <p>This method will continue to execute search operations until all dir sync search results
  * have been retrieved from the server. The returned response contains the response data of the
  * last dir sync operation plus the entries and references returned by all previous search
  * operations.
  *
  * @param request search request to execute
  * @return search operation response of the last dir sync operation
  * @throws LdapException if the search fails
  */
 public Response<SearchResult> executeToCompletion(final SearchRequest request)
     throws LdapException {
   Response<SearchResult> response = null;
   final SearchResult result = new SearchResult();
   final SearchOperation search = new SearchOperation(connection);
   byte[] cookie = null;
   long flags;
   do {
     if (response != null && response.getResult() != null) {
       result.addEntries(response.getResult().getEntries());
       result.addReferences(response.getResult().getReferences());
     }
     request.setControls(createRequestControls(cookie));
     response = search.execute(request);
     flags = getDirSyncFlags(response);
     cookie = getDirSyncCookie(response);
   } while (flags != 0);
   response.getResult().addEntries(result.getEntries());
   response.getResult().addReferences(result.getReferences());
   return response;
 }