/**
   * @param dn to search on.
   * @param filter to search with.
   * @throws Exception On test failure.
   */
  @Parameters({"dsmlSearchDn", "dsmlSearchFilter"})
  @Test(groups = {"dsml"})
  public void searchAndCompareDsmlv1(final String dn, final String filter) throws Exception {
    final Connection conn = TestUtils.createConnection();
    try {
      conn.open();
      final SearchOperation search = new SearchOperation(conn);

      final SearchRequest request = new SearchRequest(dn, new SearchFilter(filter));
      if (TestControl.isActiveDirectory()) {
        request.setBinaryAttributes("objectSid", "objectGUID", "jpegPhoto");
      } else {
        request.setBinaryAttributes("jpegPhoto");
      }
      final SearchResult result1 = search.execute(request).getResult();

      final StringWriter writer = new StringWriter();
      final Dsmlv1Writer dsmlWriter = new Dsmlv1Writer(writer);
      dsmlWriter.write(result1);

      final StringReader reader = new StringReader(writer.toString());
      final Dsmlv1Reader dsmlReader = new Dsmlv1Reader(reader);
      final SearchResult result2 = dsmlReader.read();

      TestUtils.assertEquals(result2, result1);
    } finally {
      conn.close();
    }
  }
  /**
   * 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>The cookie is extracted from the supplied response and replayed in the request.
   *
   * @param request search request to execute
   * @param response of a previous dir sync operation
   * @return search operation response
   * @throws LdapException if the search fails
   */
  public Response<SearchResult> execute(
      final SearchRequest request, final Response<SearchResult> response) throws LdapException {
    final byte[] cookie = getDirSyncCookie(response);
    if (cookie == null) {
      throw new IllegalArgumentException("Response does not contain a dir sync cookie");
    }

    final SearchOperation search = new SearchOperation(connection);
    request.setControls(createRequestControls(null));
    return search.execute(request);
  }
  /**
   * Recursively gets the attribute(s) {@link #mergeAttributes} for the supplied dn and adds the
   * values to the supplied attributes.
   *
   * @param conn to perform search operation on
   * @param dn to get attribute(s) for
   * @param entry to merge with
   * @param searchedDns list of DNs that have been searched for
   * @throws LdapException if a search error occurs
   */
  private void recursiveSearch(
      final Connection conn, final String dn, final LdapEntry entry, final List<String> searchedDns)
      throws LdapException {
    if (!searchedDns.contains(dn)) {

      LdapEntry newEntry = null;
      try {
        final SearchOperation search = new SearchOperation(conn);
        final SearchRequest sr = SearchRequest.newObjectScopeSearchRequest(dn, retAttrs);
        final SearchResult result = search.execute(sr).getResult();
        newEntry = result.getEntry(dn);
      } catch (LdapException e) {
        logger.warn("Error retrieving attribute(s): {}", Arrays.toString(retAttrs), e);
      }
      searchedDns.add(dn);

      if (newEntry != null) {
        // recursively search new attributes
        readSearchAttribute(conn, newEntry, searchedDns);

        // merge new attribute values
        for (String s : mergeAttributes) {
          final LdapAttribute newAttr = newEntry.getAttribute(s);
          if (newAttr != null) {
            final LdapAttribute oldAttr = entry.getAttribute(s);
            if (oldAttr == null) {
              entry.addAttribute(newAttr);
            } else {
              if (newAttr.isBinary()) {
                for (byte[] value : newAttr.getBinaryValues()) {
                  oldAttr.addBinaryValue(value);
                }
              } else {
                for (String value : newAttr.getStringValues()) {
                  oldAttr.addStringValue(value);
                }
              }
            }
          }
        }
      }
    }
  }
 /**
  * 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;
 }
  /** {@inheritDoc} */
  @Override
  protected void processAttributes(
      final Connection conn, final SearchRequest request, final LdapEntry entry)
      throws LdapException {
    final Map<LdapAttribute, Matcher> matchingAttrs = new HashMap<LdapAttribute, Matcher>();
    for (LdapAttribute la : entry.getAttributes()) {
      // Match attribute ID against the pattern
      final Matcher matcher = RANGE_PATTERN.matcher(la.getName());

      // If the attribute ID matches the pattern
      if (matcher.find()) {
        matchingAttrs.put(la, matcher);
      }
    }

    for (Map.Entry<LdapAttribute, Matcher> mEntry : matchingAttrs.entrySet()) {
      final LdapAttribute la = mEntry.getKey();
      final Matcher matcher = mEntry.getValue();
      final String msg = String.format("attribute '%s' entry '%s'", la.getName(), entry.getDn());

      // Determine the attribute name without the range syntax
      final String attrTypeName = matcher.group(1);
      logger.debug("Found Range option {}", msg);
      if (attrTypeName == null || attrTypeName.isEmpty()) {
        logger.error("Unable to determine the attribute type name for {}", msg);
        throw new IllegalArgumentException(
            "Unable to determine the attribute type name for " + msg);
      }

      // Create or update the attribute whose ID has the range syntax removed
      LdapAttribute newAttr = entry.getAttribute(attrTypeName);
      if (newAttr == null) {
        newAttr = new LdapAttribute(la.getSortBehavior(), la.isBinary());
        newAttr.setName(attrTypeName);
        entry.addAttribute(newAttr);
      }

      // Copy values
      if (la.isBinary()) {
        newAttr.addBinaryValues(la.getBinaryValues());
      } else {
        newAttr.addStringValues(la.getStringValues());
      }

      // Remove original attribute with range syntax from returned attributes
      entry.removeAttribute(la);

      // If the attribute ID ends with * we're done, otherwise increment
      if (!la.getName().endsWith(END_OF_RANGE)) {

        // Determine next attribute ID
        // CheckStyle:MagicNumber OFF
        final int start = Integer.parseInt(matcher.group(2));
        final int end = Integer.parseInt(matcher.group(3));
        // CheckStyle:MagicNumber ON
        final int diff = end - start;
        final String nextAttrID =
            String.format(RANGE_FORMAT, attrTypeName, end + 1, end + diff + 1);

        // Search for next increment of values
        logger.debug("Searching for '{}' to increment {}", nextAttrID, msg);

        final SearchOperation search = new SearchOperation(conn);
        final SearchRequest sr =
            SearchRequest.newObjectScopeSearchRequest(entry.getDn(), new String[] {nextAttrID});
        final SearchResult result = search.execute(sr).getResult();

        // Add all attributes to the search result
        entry.addAttributes(result.getEntry().getAttributes());

        // Iterate
        processAttributes(conn, request, entry);
      }
    }
  }
 /**
  * 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>
  *
  * @param request search request to execute
  * @return search operation response
  * @throws LdapException if the search fails
  */
 public Response<SearchResult> execute(final SearchRequest request) throws LdapException {
   final SearchOperation search = new SearchOperation(connection);
   request.setControls(createRequestControls(null));
   return search.execute(request);
 }