mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Nicolas Capponi
05.58.2016 ed0ae491be5928897b1e8bd5b41d0426dbd08081
OPENDJ-2413 Add test class for EmbeddedDirectoryServer class
2 files added
12 files modified
575 ■■■■ changed files
opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java 3 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/LocalPurgeHistorical.java 5 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java 2 ●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConfigParameters.java 20 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConnectionParameters.java 20 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServer.java 70 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ImportParameters.java 20 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/RebuildIndexParameters.java 36 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ReplicationParameters.java 20 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/SetupParameters.java 20 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/UpgradeParameters.java 20 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java 37 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/util/EmbeddedDirectoryServerTestCase.java 284 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/tests/unit-tests-testng/resource/test-import-file.ldif 18 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
@@ -1223,6 +1223,9 @@
      directoryServer.disabledPrivileges = new LinkedHashSet<>(0);
      directoryServer.returnBindErrorMessages = false;
      directoryServer.idleTimeLimit = 0L;
      // make sure the timer thread is started in case it was stopped before
      TimeThread.start();
    }
  }
opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/LocalPurgeHistorical.java
@@ -16,7 +16,8 @@
 */
package org.opends.server.tools.dsreplication;
import static org.opends.server.util.embedded.ConfigParameters.Builder.configParams;
import static org.opends.server.util.embedded.ConfigParameters.configParams;
import static org.opends.server.util.embedded.EmbeddedDirectoryServer.defineServerForStartStopOperations;
import static org.opends.messages.AdminToolMessages.*;
import org.forgerock.i18n.LocalizableMessage;
@@ -88,7 +89,7 @@
    try
    {
      EmbeddedDirectoryServer server = EmbeddedDirectoryServer.defineServerForStartStopOperations(
      EmbeddedDirectoryServer server = defineServerForStartStopOperations(
          configParams()
            .configurationFile(configFile)
            .disableConnectionHandlers(true)
opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java
@@ -2507,7 +2507,7 @@
        if (fileEntry.isDirectory())
        {
          targetFile.mkdir();
          targetFile.mkdirs();
          continue;
        }
        extractFileFromZip(zipStream, targetFile);
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConfigParameters.java
@@ -30,6 +30,16 @@
    // private constructor to force usage of the associated Builder
  }
  /**
   * Creates a builder for the configuration parameters.
   *
   * @return a builder
   */
  public static Builder configParams()
  {
    return new Builder();
  }
  String getServerRootDirectory()
  {
    return serverRootDirectory;
@@ -64,16 +74,6 @@
    }
    /**
     * Creates a builder for the configuration parameters.
     *
     * @return a builder
     */
    public static Builder configParams()
    {
      return new Builder();
    }
    /**
     * Generates the parameters from this builder.
     * <p>
     * After this call, the builder is reset and can be used to generate other parameters.
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConnectionParameters.java
@@ -33,6 +33,16 @@
    // private constructor to force usage of the associated Builder
  }
  /**
   * Creates a builder for the connection parameters.
   *
   * @return a builder
   */
  public static Builder connectionParams()
  {
    return new Builder();
  }
  String getAdminPassword()
  {
    return adminPassword;
@@ -81,16 +91,6 @@
    }
    /**
     * Creates a builder for the connection parameters.
     *
     * @return a builder
     */
    public static Builder connectionParams()
    {
      return new Builder();
    }
    /**
     * Generates the parameters from this builder.
     * <p>
     * After this call, the builder is reset and can be used to generate other parameters.
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServer.java
@@ -31,8 +31,12 @@
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.requests.Requests;
import org.forgerock.opendj.ldap.requests.SimpleBindRequest;
import org.forgerock.opendj.server.config.client.RootCfgClient;
import org.forgerock.util.Options;
import org.forgerock.util.Pair;
import org.forgerock.util.Reject;
import org.opends.quicksetup.TempLogFile;
import org.opends.server.core.DirectoryServer;
import org.opends.server.protocols.internal.InternalClientConnection;
@@ -44,6 +48,7 @@
import org.opends.server.types.DirectoryEnvironmentConfig;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.InitializationException;
import org.opends.server.util.ServerConstants;
import org.opends.server.util.StaticUtils;
/**
@@ -54,6 +59,9 @@
{
  private static final String EMBEDDED_OPEN_DJ_PREFIX = "embeddedOpenDJ";
  private static final String QUICKSETUP_ROOT_PROPERTY = "org.opends.quicksetup.Root";
  private static final String QUICKSETUP_INSTANCE_PROPERTY = "org.opends.quicksetup.Root";
  /** The parameters for install and instance directories, and configuration file of the server. */
  private final ConfigParameters configParams;
@@ -89,15 +97,19 @@
    this.connectionParams = connParams;
    this.outStream = out;
    this.errStream = err;
    this.ldapConnectionFactory = connectionParams != null ?
        new LDAPConnectionFactory(connectionParams.getHostname(), connectionParams.getLdapPort())
        : null;
    //System.setProperty("org.opends.quicksetup.Root", configParams.getServerRootDirectory());
    //System.setProperty(ServerConstants.PROPERTY_SERVER_ROOT, configParams.getServerRootDirectory());
    //System.setProperty(ServerConstants.PROPERTY_INSTANCE_ROOT, configParams.getServerInstanceDirectory());
    // from LicenseFile.java - provided by AM OpenDJUpgrader.java
    //System.setProperty("INSTALL_ROOT", configParams.getServerInstanceDirectory());
    if (connectionParams != null)
    {
      SimpleBindRequest authRequest = Requests.newSimpleBindRequest(
          connectionParams.getBindDn(), connectionParams.getBindPassword().toCharArray());
      ldapConnectionFactory = new LDAPConnectionFactory(
          connectionParams.getHostname(),
          connectionParams.getLdapPort(),
          Options.defaultOptions().set(LDAPConnectionFactory.AUTHN_BIND_REQUEST, authRequest));
    }
    else
    {
      ldapConnectionFactory = null;
    }
  }
  /**
@@ -244,6 +256,8 @@
  /**
   * Imports LDIF data to the directory server, overwriting existing data.
   * <p>
   * The import is implemented only for online use.
   *
   * @param parameters
   *            The import parameters.
@@ -252,6 +266,7 @@
   */
  public void importData(ImportParameters parameters) throws EmbeddedDirectoryServerException
  {
    checkServerIsRunning();
    checkConnectionParameters();
    int returnCode = ImportLDIF.mainImportLDIF(
        parameters.toCommandLineArguments(configParams.getConfigurationFile(), connectionParams),
@@ -351,6 +366,8 @@
  public void setup(SetupParameters parameters) throws EmbeddedDirectoryServerException
  {
    checkConnectionParameters();
    System.setProperty(QUICKSETUP_ROOT_PROPERTY, configParams.getServerRootDirectory());
    System.setProperty(QUICKSETUP_INSTANCE_PROPERTY, configParams.getServerInstanceDirectory());
    int returnCode = InstallDS.mainCLI(parameters.toCommandLineArguments(connectionParams), outStream, errStream,
        TempLogFile.newTempLogFile(EMBEDDED_OPEN_DJ_PREFIX));
@@ -363,6 +380,9 @@
  /**
   * Setups this server from the provided archive.
   * <p>
   * As the DJ archive includes the "opendj" directory, it is mandatory to have
   * the root directory named "opendj".
   *
   * @param openDJZipFile
   *            The OpenDJ server archive.
@@ -376,7 +396,14 @@
    checkConnectionParameters();
    try
    {
      StaticUtils.extractZipArchive(openDJZipFile, new File(configParams.getServerRootDirectory()));
      File serverRoot = new File(configParams.getServerRootDirectory());
      if (!serverRoot.getName().equals("opendj"))
      {
        throw new EmbeddedDirectoryServerException(LocalizableMessage.raw("Wrong server root directory" + serverRoot));
      }
      // the directory where the zip file is extracted should be one level up from the server root.
      File deployDirectory = serverRoot.getParentFile();
      StaticUtils.extractZipArchive(openDJZipFile, deployDirectory);
    }
    catch (IOException e)
    {
@@ -388,6 +415,8 @@
  /**
   * Rebuilds all the indexes of this server.
   * <p>
   * This operation is done offline, hence the server must be stopped when calling this method.
   *
   * @param parameters
   *            The parameters for rebuilding the indexes.
@@ -396,8 +425,9 @@
   */
  public void rebuildIndex(RebuildIndexParameters parameters) throws EmbeddedDirectoryServerException
  {
    checkServerIsNotRunning();
    int returnCode = RebuildIndex.mainRebuildIndex(
        parameters.toCommandLineArguments(), !isRunning(), outStream, errStream);
        parameters.toCommandLineArguments(configParams.getConfigurationFile()), !isRunning(), outStream, errStream);
    if (returnCode != 0)
    {
@@ -590,6 +620,24 @@
    }
  }
  private void checkServerIsRunning() throws EmbeddedDirectoryServerException
  {
    if (!isRunning())
    {
      throw new EmbeddedDirectoryServerException(LocalizableMessage.raw(
          "This operation is only available when server is online"));
    }
  }
  private void checkServerIsNotRunning() throws EmbeddedDirectoryServerException
  {
    if (isRunning())
    {
      throw new EmbeddedDirectoryServerException(LocalizableMessage.raw(
          "This operation is only available when server is offline"));
    }
  }
  /**
   * Retrieves the management context, and optionally a connection if the server is running, in order to
   * give access to the configuration of the server.
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ImportParameters.java
@@ -29,6 +29,16 @@
  }
  /**
   * Creates a builder for the import parameters.
   *
   * @return a builder
   */
  public static Builder importParams()
  {
    return new Builder();
  }
  /**
   * Generates command-line arguments from the parameters.
   *
   * @return command-line arguments
@@ -64,16 +74,6 @@
    }
    /**
     * Creates a builder for the import parameters.
     *
     * @return a builder
     */
    public static Builder importParams()
    {
      return new Builder();
    }
    /**
     * Generates the parameters from this builder.
     * <p>
     * After this call, the builder is reset and can be used to generate other parameters.
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/RebuildIndexParameters.java
@@ -20,7 +20,6 @@
 */
public final class RebuildIndexParameters
{
  private String configurationFile;
  private String baseDN;
  private RebuildIndexParameters()
@@ -29,11 +28,21 @@
  }
  /**
   * Creates a builder for the rebuild index parameters.
   *
   * @return a builder
   */
  public static Builder rebuildIndexParams()
  {
    return new Builder();
  }
  /**
   * Generates command-line arguments from the parameters.
   *
   * @return command-line arguments
   */
  String[] toCommandLineArguments()
  String[] toCommandLineArguments(String configurationFile)
  {
    return new String[] {
      "--configFile", configurationFile,
@@ -56,16 +65,6 @@
    }
    /**
     * Creates a builder for the rebuild index parameters.
     *
     * @return a builder
     */
    public static Builder rebuildIndexParams()
    {
      return new Builder();
    }
    /**
     * Generates the parameters from this builder.
     * <p>
     * After this call, the builder is reset and can be used to generate other parameters.
@@ -80,19 +79,6 @@
    }
    /**
     * Sets the configuration file of the server.
     *
     * @param file
     *          the configuration file
     * @return this builder
     */
    public Builder configurationFile(String file)
    {
      params.configurationFile = file;
      return this;
    }
    /**
     * Sets the base Dn for user information in the directory server.
     *
     * @param baseDN
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ReplicationParameters.java
@@ -31,6 +31,16 @@
  }
  /**
   * Creates a builder for the replication parameters.
   *
   * @return a builder
   */
  public static Builder replicationParams()
  {
    return new Builder();
  }
  /**
   * Generates the command-line arguments for enabling replication, from the parameters.
   *
   * @return command-line arguments
@@ -138,16 +148,6 @@
    }
    /**
     * Creates a builder for the replication parameters.
     *
     * @return a builder
     */
    public static Builder replicationParams()
    {
      return new Builder();
    }
    /**
     * Generates the parameters from this builder.
     * <p>
     * After this call, the builder is reset and can be used to generate other parameters.
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/SetupParameters.java
@@ -30,6 +30,16 @@
  }
  /**
   * Creates a builder for the setup parameters.
   *
   * @return a builder
   */
  public static Builder setupParams()
  {
    return new Builder();
  }
  /**
   * Generates command-line arguments from the parameters.
   *
   * @return command-line arguments
@@ -82,16 +92,6 @@
    }
    /**
     * Creates a builder for the setup parameters.
     *
     * @return a builder
     */
    public static Builder setupParams()
    {
      return new Builder();
    }
    /**
     * Generates the parameters from this builder.
     * <p>
     * After this call, the builder is reset and can be used to generate other parameters.
opendj-server-legacy/src/main/java/org/opends/server/util/embedded/UpgradeParameters.java
@@ -31,6 +31,16 @@
  }
  /**
   * Starts construction of the upgrade parameters.
   *
   * @return this builder
   */
  public static Builder upgradeParams()
  {
    return new Builder();
  }
  /**
   * Generates command-line arguments from the parameters.
   *
   * @return command-line arguments
@@ -62,16 +72,6 @@
    }
    /**
     * Starts construction of the upgrade parameters.
     *
     * @return this builder
     */
    public static Builder upgradeParams()
    {
      return new Builder();
    }
    /**
     * Returns the fully initialized parameters.
     *
     * @return the parameters
opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java
@@ -17,7 +17,9 @@
 */
package org.opends.server;
import static org.opends.server.util.embedded.ConfigParameters.Builder.configParams;
import static org.opends.server.util.embedded.EmbeddedDirectoryServer.defineServer;
import static org.opends.server.util.embedded.ConnectionParameters.connectionParams;
import static org.opends.server.util.embedded.ConfigParameters.configParams;
import static org.opends.server.loggers.TextAccessLogPublisher.getStartupTextAccessPublisher;
import static org.opends.server.loggers.TextErrorLogPublisher.getToolStartupTextErrorPublisher;
import static org.opends.server.loggers.TextHTTPAccessLogPublisher.getStartupTextHTTPAccessPublisher;
@@ -104,6 +106,7 @@
import org.opends.server.types.LDIFImportConfig;
import org.forgerock.opendj.ldap.schema.Schema;
import org.opends.server.util.BuildVersion;
import org.opends.server.util.DynamicConstants;
import org.opends.server.util.LDIFReader;
import org.opends.server.util.embedded.EmbeddedDirectoryServer;
import org.testng.Assert;
@@ -112,7 +115,6 @@
import static org.mockito.Mockito.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.util.embedded.ConnectionParameters.Builder.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
import static org.testng.Assert.*;
@@ -218,7 +220,7 @@
  private static int serverRestarts;
  /** The paths to directories and files used in the tests. */
  private static TestPaths paths;
  private static TestPaths paths = new TestPaths();
  /** The ports used in the tests. */
  private static TestPorts ports;
@@ -308,7 +310,7 @@
      }
      InvocationCounterPlugin.resetStartupCalled();
      initializePathsPortsAndServer();
      initializePortsAndServer();
      deployDirectoryDirsAndFiles();
@@ -334,12 +336,11 @@
    }
  }
  private static void initializePathsPortsAndServer() throws Exception
  private static void initializePortsAndServer() throws Exception
  {
    paths = new TestPaths();
    ports = new TestPorts();
    hostname = InetAddress.getLocalHost().getHostName();
    server = EmbeddedDirectoryServer.defineServer(
    server = defineServer(
        configParams()
          .serverRootDirectory(paths.testInstallRoot.getPath())
          .serverInstanceDirectory(paths.testInstanceRoot.getPath())
@@ -1129,19 +1130,25 @@
   */
  public static File getTestResource(String filename)
  {
    String buildRoot = System.getProperty(PROPERTY_BUILD_ROOT);
    File   testResourceDir = new File(buildRoot + File.separator + "tests" +
                                      File.separator + "unit-tests-testng" +
                                      File.separator + "resource");
    File testResourceDir = new File(paths.testSrcRoot, "resource");
    return new File(testResourceDir, filename);
  }
  public static File getUnitTestRootPath()
  {
    final String buildRoot = System.getProperty(PROPERTY_BUILD_ROOT);
    final String path = System.getProperty(PROPERTY_BUILD_DIR, buildRoot + File.separator + "target");
    return new File(path, "unit-tests");
    return paths.unitRoot;
  }
  /** Get the complete path to the OpenDJ archive. */
  public static File getOpenDJArchivePath()
  {
    String qualifier = DynamicConstants.VERSION_QUALIFIER;
    String openDJArchiveName =
        DynamicConstants.SHORT_NAME.toLowerCase()
        + "-"
        + DynamicConstants.VERSION_NUMBER_STRING
        + (qualifier != null && !qualifier.isEmpty() ? "-" + qualifier : "");
    return getBuildRoot().toPath().resolve("target/package").resolve(openDJArchiveName + ".zip").toFile();
  }
  /** Prevent instantiation. */
opendj-server-legacy/src/test/java/org/opends/server/util/EmbeddedDirectoryServerTestCase.java
New file
@@ -0,0 +1,284 @@
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2016 ForgeRock AS.
 */
package org.opends.server.util;
import static org.opends.server.util.embedded.ConfigParameters.configParams;
import static org.opends.server.util.embedded.ConnectionParameters.connectionParams;
import static org.opends.server.util.embedded.EmbeddedDirectoryServer.defineServer;
import static org.opends.server.util.embedded.ImportParameters.importParams;
import static org.opends.server.util.embedded.UpgradeParameters.upgradeParams;
import static org.opends.server.util.embedded.RebuildIndexParameters.rebuildIndexParams;
import static org.assertj.core.api.Assertions.assertThat;
import static org.opends.server.TestCaseUtils.getServer;
import static org.testng.Assert.*;
import java.io.File;
import java.util.SortedSet;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.server.config.client.BackendCfgClient;
import org.forgerock.opendj.server.config.client.RootCfgClient;
import org.opends.server.TestCaseUtils;
import org.opends.server.core.DirectoryServer;
import org.opends.server.types.DirectoryEnvironmentConfig;
import org.opends.server.util.embedded.EmbeddedDirectoryServer;
import org.opends.server.util.embedded.EmbeddedDirectoryServer.DirectoryConfigReader;
import org.opends.server.util.embedded.EmbeddedDirectoryServer.DirectoryConfigUpdater;
import org.opends.server.util.embedded.EmbeddedDirectoryServerException;
import org.opends.server.util.embedded.SetupParameters;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
 * Tests for an embedded directory server.
 */
@Test(groups = "slow", sequential=true)
@SuppressWarnings("javadoc")
public class EmbeddedDirectoryServerTestCase extends UtilTestCase
{
  private static final String USER_ROOT = "userRoot";
  @BeforeClass
  public void setUp() throws Exception
  {
    TestCaseUtils.startServer();
    TestCaseUtils.clearBackend(USER_ROOT, "dc=example,dc=com");
    assertTrue(getServer().isRunning());
  }
  /**
   * Make sure that the server gets restarted by the {@code TestCaseUtils.restartServer} method
   * because it does a few things to the server that aren't covered in the out-of-the-box
   * configuration.
   */
  @AfterClass
  public void cleanUp() throws Exception
  {
    TestCaseUtils.restartServer();
  }
  @Test
  public void testRestartServer() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    assertTrue(server.isRunning());
    DirectoryEnvironmentConfig environmentConfig = DirectoryServer.getEnvironmentConfig();
    assertNotNull(environmentConfig);
    server.restart(getClass().getName(), LocalizableMessage.raw("testRestartServer"));
    assertTrue(server.isRunning());
  }
  @Test
  public void testStopAndStartServer() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    assertTrue(server.isRunning());
    DirectoryEnvironmentConfig environmentConfig = DirectoryServer.getEnvironmentConfig();
    assertNotNull(environmentConfig);
    server.stop(getClass().getName(), LocalizableMessage.raw("testStopAndStartServer"));
    assertFalse(server.isRunning());
    server.start();
    assertTrue(server.isRunning());
  }
  public void testReadConfigurationOffline() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    server.stop(getClass().getSimpleName(), LocalizableMessage.raw("stopping for read config test"));
    try
    {
      readConfiguration(server);
    }
    finally
    {
      server.start();
    }
  }
  private void readConfiguration(EmbeddedDirectoryServer server) throws EmbeddedDirectoryServerException
  {
    SortedSet<DN> dns = server.readConfiguration(new DirectoryConfigReader<SortedSet<DN>>() {
          @Override
          public SortedSet<DN> read(RootCfgClient rootConfig) throws Exception
          {
            return rootConfig.getBackend(USER_ROOT).getBaseDN();
          }
        });
    assertThat(dns).containsExactly(DN.valueOf("dc=example,dc=com"));
  }
  public void testReadConfigurationOnline() throws Exception
  {
    readConfiguration(getServer());
  }
  public void testUpdateConfiguration() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    assertTrue(DirectoryServer.hasBackend(USER_ROOT));
    toggleBackendActivation(server, false);
    assertFalse(DirectoryServer.hasBackend(USER_ROOT));
    // revert to initial configuration
    toggleBackendActivation(server, true);
    assertTrue(DirectoryServer.hasBackend(USER_ROOT));
  }
  private void toggleBackendActivation(EmbeddedDirectoryServer server, final boolean enabled) throws Exception
  {
    server.updateConfiguration(new DirectoryConfigUpdater()
    {
      @Override
      public void update(RootCfgClient rootConfig) throws Exception
      {
        BackendCfgClient backend = rootConfig.getBackend(USER_ROOT);
        backend.setEnabled(enabled);
        backend.commit();
      }
    });
  }
  /**
   * This test only ensures that the rebuild index process is correctly launched and does not fail.
   * There is no assertions.
   */
  public void testRebuildIndexOffline() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    server.stop(getClass().getSimpleName(), LocalizableMessage.raw("stopping for rebuild index test"));
    try
    {
      server.rebuildIndex(rebuildIndexParams().baseDN("dc=example,dc=com").build());
    }
    finally
    {
      server.start();
    }
  }
  /** Rebuild index is not available online. */
  @Test(expectedExceptions = EmbeddedDirectoryServerException.class)
  public void testRebuildIndexOnline() throws Exception
  {
    getServer().rebuildIndex(rebuildIndexParams().baseDN("dc=example,dc=com").build());
  }
  /**
   * This test only ensures that the upgrade index is correctly launched and does not fail.
   * There is no assertions.
   */
  public void testUpgradeOffline() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    server.stop(getClass().getSimpleName(), LocalizableMessage.raw("stopping for upgrade test"));
    try
    {
      server.upgrade(upgradeParams().isIgnoreErrors(false).build());
    }
    finally
    {
      server.start();
    }
  }
  /**
   * This test only ensures that the upgrade index is correctly launched and does not fail.
   * There is no assertions.
   */
  public void testUpgradeOnline() throws Exception
  {
    getServer().upgrade(upgradeParams().isIgnoreErrors(false).build());
  }
  public void testImportDataOnline() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    server.importData(importParams()
        .backendId("userRoot")
        .ldifFile(TestCaseUtils.getTestResource("test-import-file.ldif").getPath())
        .build());
  }
  /** Import data is not implemented for offline use in EmbeddedDirectoryServer.*/
  @Test(expectedExceptions= EmbeddedDirectoryServerException.class)
  public void testImportDataOffline() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    server.stop(getClass().getSimpleName(), LocalizableMessage.raw("stopping for import data test"));
    try
    {
      server.importData(importParams()
          .backendId("userRoot")
          .ldifFile(TestCaseUtils.getTestResource("test-import-file.ldif").getPath())
          .build());
    }
    finally
    {
      server.start();
    }
  }
  public void testSetupFromArchive() throws Exception
  {
    EmbeddedDirectoryServer server = getServer();
    server.stop(getClass().getSimpleName(), LocalizableMessage.raw("stopping for setup from archive test"));
    try
    {
      File rootDir = TestCaseUtils.getUnitTestRootPath().toPath().resolve("embedded-setup").resolve("opendj").toFile();
      // ensure the test starts from a clean directory
      StaticUtils.recursiveDelete(rootDir);
      final int[] ports = TestCaseUtils.findFreePorts(3);
      EmbeddedDirectoryServer tempServer = defineServer(
        configParams()
          .serverRootDirectory(rootDir.getPath())
          .configurationFile(rootDir.toPath().resolve("config").resolve("config.ldif").toString())
          .build(),
        connectionParams()
          .bindDn("cn=Directory Manager")
          .bindPassword("password")
          .hostName("localhost")
          .ldapPort(ports[0])
          .adminPort(ports[1])
          .build(),
         System.out,
         System.err);
      tempServer.setupFromArchive(TestCaseUtils.getOpenDJArchivePath(),
          SetupParameters.setupParams()
            .backendType("pdb")
            .baseDn("dc=example,dc=com")
            .jmxPort(ports[2])
            .build());
      tempServer.start();
      tempServer.stop(getClass().getSimpleName(), LocalizableMessage.raw("stopping temp server for setup test"));
    }
    finally
    {
      server.start();
    }
  }
}
opendj-server-legacy/tests/unit-tests-testng/resource/test-import-file.ldif
New file
@@ -0,0 +1,18 @@
# The contents of this file are subject to the terms of the Common Development and
# Distribution License (the License). You may not use this file except in compliance with the
# License.
#
# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
# specific language governing permission and limitations under the License.
#
# When distributing Covered Software, include this CDDL Header Notice in each file and include
# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
# Header, with the fields enclosed by brackets [] replaced by your own identifying
# information: "Portions Copyright [year] [name of copyright owner]".
#
# Copyright 2016 ForgeRock AS.
dn: dc=example,dc=com
objectClass: top
objectClass: domain
dc: example