/**
   * Write a modify request.
   *
   * @throws Exception
   */
  @Test
  public void testWriteModifyRequest() throws Exception {
    final List<String> actual = new ArrayList<>();
    final LDIFChangeRecordWriter writer = new LDIFChangeRecordWriter(actual);

    // @formatter:off
    final ModifyRequest changeRequest =
        Requests.newModifyRequest(
            "version: 1",
            "dn: cn=scarter,dc=example,dc=com",
            "changetype: modify",
            "add: work-phone",
            "work-phone: 650/506-7000");

    // @formatter:on
    writer.writeChangeRecord(changeRequest);
    writer.close();

    // version number is skipped.
    assertThat(actual.get(0)).isEqualTo("dn: cn=scarter,dc=example,dc=com");
    assertThat(actual.get(1)).isEqualTo("changetype: modify");
    assertThat(actual.get(2)).isEqualTo("add: work-phone");
    assertThat(actual.get(3)).isEqualTo("work-phone: 650/506-7000");
    assertThat(actual.get(4)).isEqualTo("-");
  }
  /**
   * Write an ModifyRequest LDIF.
   *
   * @throws Exception
   */
  @Test
  public void testWriteModifyRequestNoModifications() throws Exception {
    final List<String> actual = new ArrayList<>();
    final LDIFChangeRecordWriter writer = new LDIFChangeRecordWriter(actual);

    // @formatter:off
    final ModifyRequest changeRequest =
        Requests.newModifyRequest(
            "version: 1", "", "dn: cn=scarter,dc=example,dc=com", "changetype: modify");
    // @formatter:on
    writer.writeChangeRecord(changeRequest);
    writer.close();

    // No changes, nothing to do, the record is not written.
    assertThat(actual.size()).isEqualTo(0);
  }
  /**
   * Write a modify request containing a control.
   *
   * @throws Exception
   */
  @Test
  public void testWriteModifyRequestUsingControl() throws Exception {
    final List<String> actual = new ArrayList<>();
    final LDIFChangeRecordWriter writer = new LDIFChangeRecordWriter(actual);

    // @formatter:off
    final ModifyRequest changeRequest =
        Requests.newModifyRequest("cn=scarter,dc=example,dc=com")
            .addControl(PreReadRequestControl.newControl(true, "mail"))
            .addModification(ModificationType.REPLACE, "mail", "*****@*****.**");
    // @formatter:on

    writer.writeChangeRecord(changeRequest);
    writer.close();

    assertThat(actual.size()).isEqualTo(7);
    assertThat(actual.get(0)).isEqualTo("dn: cn=scarter,dc=example,dc=com");
    assertThat(actual.get(1)).contains("control: 1.3.6.1.1.13.1 true:");
    assertThat(actual.get(2)).isEqualTo("changetype: modify");
    assertThat(actual.get(3)).isEqualTo("replace: mail");
    assertThat(actual.get(4)).isEqualTo("mail: [email protected]");
    assertThat(actual.get(5)).isEqualTo("-");
  }
Ejemplo n.º 4
0
  /**
   * Updates the config file during the upgrade process.
   *
   * @param configPath The original path to the file.
   * @param filter The filter to select entries. Only useful for modify change type.
   * @param changeType The change type which must be applied to ldif lines.
   * @param ldifLines The change record ldif lines. For ADD change type, the first line must be the
   *     dn. For DELETE change type, the first and only line must be the dn.
   * @throws IOException If an Exception occurs during the input output methods.
   * @return The changes number that have occurred.
   */
  static int updateConfigFile(
      final String configPath,
      final Filter filter,
      final ChangeOperationType changeType,
      final String... ldifLines)
      throws IOException {
    final File original = new File(configPath);
    final File copyConfig = File.createTempFile("copyConfig", ".tmp", original.getParentFile());

    int changeCount = 0;
    LDIFEntryReader entryReader = null;
    LDIFEntryWriter writer = null;
    try {
      final Schema schema = getUpgradeSchema();
      entryReader = new LDIFEntryReader(new FileInputStream(configPath)).setSchema(schema);

      writer = new LDIFEntryWriter(new FileOutputStream(copyConfig));
      writer.setWrapColumn(80);

      // Writes the header on the new file.
      writer.writeComment(INFO_CONFIG_FILE_HEADER.get());
      writer.setWrapColumn(0);

      boolean entryAlreadyExist = false;
      DN ldifDN = null;
      if (filter == null && (changeType == ADD || changeType == DELETE)) {
        // The first line should start with dn:
        ldifDN = DN.valueOf(ldifLines[0].replaceFirst("dn: ", ""));
      }
      final Filter f = filter != null ? filter : Filter.alwaysFalse();
      final Matcher matcher = f.matcher(schema);
      while (entryReader.hasNext()) {
        Entry entry = entryReader.readEntry();
        final DN entryDN = entry.getName();
        // Searching for the related entries
        if (changeType == MODIFY && matcher.matches(entry) == ConditionResult.TRUE) {
          try {
            final ModifyRequest mr =
                Requests.newModifyRequest(readLDIFLines(entryDN, changeType, ldifLines));
            entry = Entries.modifyEntryPermissive(entry, mr.getModifications());
            changeCount++;
            logger.debug(
                LocalizableMessage.raw("The following entry has been modified : %s", entryDN));
          } catch (Exception ex) {
            logger.error(LocalizableMessage.raw(ex.getMessage()));
          }
        }

        if (entryDN.equals(ldifDN)) {
          logger.debug(LocalizableMessage.raw("Entry %s found", entryDN));
          entryAlreadyExist = true;

          if (changeType == DELETE) {
            entry = null;
            changeCount++;
            logger.debug(
                LocalizableMessage.raw("The following entry has been deleted : %s", entryDN));
          }
        }

        if (entry != null) {
          writer.writeEntry(entry);
        }
      }

      if (changeType == ADD && !entryAlreadyExist) {
        final AddRequest ar = Requests.newAddRequest(ldifLines);
        writer.writeEntry(ar);
        logger.debug(
            LocalizableMessage.raw(
                "Entry successfully added %s in %s", ldifDN, original.getAbsolutePath()));
        changeCount++;
      }
    } catch (Exception ex) {
      throw new IOException(ex.getMessage());
    } finally {
      // The reader and writer must be close before renaming files.
      // Otherwise it causes exceptions under windows OS.
      StaticUtils.close(entryReader, writer);
    }

    try {
      // Renaming the file, overwriting previous one.
      rename(copyConfig, new File(configPath));
    } catch (IOException e) {
      logger.error(LocalizableMessage.raw(e.getMessage()));
      deleteRecursively(original);
      throw e;
    }

    return changeCount;
  }
  /**
   * Write a full example containing multiple change records.
   *
   * @throws Exception
   */
  @Test
  public void testWriteMultipleChangeRecords() throws Exception {
    final List<String> actual = new ArrayList<>();
    final LDIFChangeRecordWriter writer = new LDIFChangeRecordWriter(actual);
    final ChangeRecord changeRequest = Requests.newAddRequest(getAddLDIFChangeRecord());

    // @formatter:off
    final ModifyDNRequest changeRequest2 =
        Requests.newModifyDNRequest("cn=scarter,dc=example,dc=com", "cn=Susan Jacobs")
            .setDeleteOldRDN(false);
    // @formatter:on

    // @formatter:off
    final ModifyRequest changeRequest3 =
        Requests.newModifyRequest(
            "version: 1",
            "",
            "dn: cn=scarter,dc=example,dc=com",
            "changetype: modify",
            "replace: work-phone",
            "work-phone: 555-555-1155");
    // @formatter:on

    // @formatter:off
    final AddRequest changeRequest4 =
        Requests.newAddRequest(
            "version: 1",
            "dn: uid=scarter,ou=People,dc=example,dc=com",
            "changetype: add",
            "sn: Carter");
    // @formatter:on

    final File file = File.createTempFile("sdk", null);
    final String url = file.toURI().toURL().toString();

    // @formatter:off
    final AddRequest changeRequest5 =
        Requests.newAddRequest(
            "version: 1",
            "# Add a new record",
            "dn: cn=Fiona Jensen, ou=Marketing, dc=airius, dc=com",
            "changetype: add",
            "objectclass: top",
            "objectclass: person",
            "objectclass: organizationalPerson",
            "cn: Fiona Jensen",
            "sn: Jensen",
            "uid: fiona",
            "telephonenumber: +1 408 555 1212",
            "jpegphoto:< " + url);
    // @formatter:on

    writer.writeChangeRecord(changeRequest);
    writer.writeChangeRecord(changeRequest2);
    writer.writeChangeRecord(changeRequest3);
    writer.writeChangeRecord(changeRequest4);
    writer.writeComment("A comment...");
    writer.writeChangeRecord(changeRequest5);
    writer.close();

    assertThat(actual.size()).isGreaterThan(10);
    assertThat(actual.get(0)).isEqualTo("dn: uid=scarter,ou=People,dc=example,dc=com");
    assertThat(actual.get(actual.size() - 1)).isEqualTo("");

    file.delete();
  }