From 256c2bcdd00b78a349feef7e2258364cea0e832f Mon Sep 17 00:00:00 2001
From: Nicolas Capponi <nicolas.capponi@forgerock.com>
Date: Wed, 21 Sep 2016 15:15:44 +0000
Subject: [PATCH] OPENDJ-2413 Create new EmbeddedDirectoryServer class as API entry point

---
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServerException.java |   53 +
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServer.java          |  591 +++++++++++++++++++
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ImportParameters.java                 |  116 +++
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConnectionParameters.java             |  198 ++++++
 opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java                               |   65 ++
 opendj-server-legacy/src/main/java/org/opends/server/util/EmbeddedUtils.java                             |    4 
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/package-info.java                     |   19 
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConfigParameters.java                 |  127 ++++
 opendj-server-legacy/pom.xml                                                                             |    7 
 opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java                    |    3 
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/SetupParameters.java                  |  147 ++++
 opendj-server-legacy/src/messages/org/opends/messages/utility.properties                                 |   35 +
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/RebuildIndexParameters.java           |  108 +++
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/UpgradeParameters.java                |  102 +++
 opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ReplicationParameters.java            |  219 +++++++
 15 files changed, 1,782 insertions(+), 12 deletions(-)

diff --git a/opendj-server-legacy/pom.xml b/opendj-server-legacy/pom.xml
index a4d766e..3a1c1f7 100644
--- a/opendj-server-legacy/pom.xml
+++ b/opendj-server-legacy/pom.xml
@@ -199,13 +199,6 @@
     </dependency>
 
     <dependency>
-      <groupId>org.forgerock.opendj</groupId>
-      <artifactId>opendj-core</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>
-
-    <dependency>
       <groupId>org.freemarker</groupId>
       <artifactId>freemarker</artifactId>
       <version>${freemarker.version}</version>
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java b/opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java
index c4c1a52..2644cad 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java
@@ -183,8 +183,9 @@
     {
       if (!configFramework.isInitialized())
       {
-        configFramework.initialize();
+        configFramework.initialize(serverContext.getServerRoot(), serverContext.getInstanceRoot());
       }
+      configFramework.setIsClient(false);
     }
     catch (ConfigException e)
     {
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/EmbeddedUtils.java b/opendj-server-legacy/src/main/java/org/opends/server/util/EmbeddedUtils.java
index aeb61c7..0b642a4 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/util/EmbeddedUtils.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/EmbeddedUtils.java
@@ -12,7 +12,7 @@
  * information: "Portions Copyright [year] [name of copyright owner]".
  *
  * Copyright 2008 Sun Microsystems, Inc.
- * Portions Copyright 2014 ForgeRock AS.
+ * Portions Copyright 2014-2016 ForgeRock AS.
  */
 package org.opends.server.util;
 
@@ -69,7 +69,7 @@
     if (DirectoryServer.isRunning())
     {
       throw new InitializationException(
-              ERR_EMBEDUTILS_SERVER_ALREADY_RUNNING.get());
+              ERR_EMBEDUTILS_SERVER_ALREADY_RUNNING.get(config.getServerRootAsString()));
     }
 
     DirectoryServer directoryServer = DirectoryServer.reinitialize(config);
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java b/opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java
index 9b1af2b..82e04b8 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java
@@ -19,6 +19,7 @@
 import static org.opends.messages.UtilityMessages.*;
 import static org.opends.server.util.ServerConstants.*;
 
+import java.io.BufferedOutputStream;
 import java.io.Closeable;
 import java.io.File;
 import java.io.FileInputStream;
@@ -43,6 +44,8 @@
 import java.util.List;
 import java.util.Map;
 import java.util.TimeZone;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
 
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.LocalizableMessageBuilder;
@@ -89,6 +92,9 @@
   /** The number of bytes of a Java long. A Java int is 64 bits, i.e. 8 bytes. */
   public static final int LONG_SIZE = 8;
 
+  /** Size of buffer used to copy/move/extract files. */
+  public static final int BUFFER_SIZE = 8192;
+
   /**
    * Number of bytes in a Kibibyte.
    * <p>
@@ -2477,5 +2483,64 @@
       return false;
     }
   }
+
+  /**
+   * Extracts the provided zip archive to the provided target directory.
+   * <p>
+   * Archive files ending by "sh" or beginning by "bin" are set as executable files.
+   *
+   * @param zipFile
+   *            The zip file to extract.
+   * @param targetDirectory
+   *            The target directory for the content of the archive.
+   * @throws IOException
+   *            If zip archive can't be read or target files can be written.
+   */
+  public static void extractZipArchive(File zipFile, File targetDirectory) throws IOException
+  {
+    try (ZipInputStream zipStream = new ZipInputStream(new FileInputStream(zipFile)))
+    {
+      ZipEntry fileEntry;
+      while ((fileEntry = zipStream.getNextEntry()) != null)
+      {
+        File targetFile = new File(targetDirectory.getPath() + File.separator +  fileEntry.getName());
+
+        if (fileEntry.isDirectory())
+        {
+          targetFile.mkdir();
+          continue;
+        }
+        extractFileFromZip(zipStream, targetFile);
+
+        if (fileEntry.getName().endsWith("sh") || fileEntry.getName().startsWith("bin"))
+        {
+          targetFile.setExecutable(true);
+        }
+      }
+    }
+  }
+
+  /**
+   * Extracts a file from a zip input stream.
+   *
+   * @param zipInput
+   *          The input stream of a zip file.
+   * @param targetFile
+   *          The destination of the extracted file.
+   * @throws IOException
+   *           If the zip file can't be read or the target file can't be written
+   */
+  private static void extractFileFromZip(ZipInputStream zipInput, File targetFile) throws IOException
+  {
+    try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
+    {
+      int bytesRead = 0;
+      byte[] bytes = new byte[BUFFER_SIZE];
+      while ((bytesRead = zipInput.read(bytes)) != -1)
+      {
+        outputStream.write(bytes, 0, bytesRead);
+      }
+    }
+  }
 }
 
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConfigParameters.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConfigParameters.java
new file mode 100644
index 0000000..443ce4b
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConfigParameters.java
@@ -0,0 +1,127 @@
+/*
+ * 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.embedded;
+
+/**
+ * Parameters to configure a directory server.
+ */
+public final class ConfigParameters
+{
+  private String serverRootDirectory;
+  private String serverInstanceDirectory;
+  private String configurationFile;
+
+  private ConfigParameters()
+  {
+    // private constructor to force usage of the associated Builder
+  }
+
+  String getServerRootDirectory()
+  {
+    return serverRootDirectory;
+  }
+
+  String getServerInstanceDirectory()
+  {
+    // provides the expected default value if not set
+    return serverInstanceDirectory != null ? serverInstanceDirectory : serverRootDirectory;
+  }
+
+  String getConfigurationFile()
+  {
+    return configurationFile;
+  }
+
+  /**
+   * Builder for this class.
+   */
+  public static final class Builder
+  {
+    private ConfigParameters params;
+
+    private Builder()
+    {
+      params = new ConfigParameters();
+    }
+
+    /**
+     * 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.
+     *
+     * @return the replication parameters
+     */
+    public ConfigParameters toParams()
+    {
+      ConfigParameters p = params;
+      this.params = new ConfigParameters();
+      return p;
+    }
+
+    /**
+     * Sets the server root directory of the directory server.
+     * <p>
+     * The server root is the location where the binaries and default configuration is stored.
+     *
+     * @param dir
+     *          the server root directory
+     * @return this builder
+     */
+    public Builder serverRootDirectory(String dir)
+    {
+      params.serverRootDirectory = dir;
+      return this;
+    }
+
+    /**
+     * Sets the install root directory of the directory server.
+     * <p>
+     * The install root is the location where the data and live configuration is stored.
+     *
+     * @param dir
+     *          the install root directory
+     * @return this builder
+     */
+    public Builder serverInstanceDirectory(String dir)
+    {
+      params.serverInstanceDirectory = dir;
+      return this;
+    }
+
+    /**
+     * Sets the path of the configuration file of the directory server.
+     *
+     * @param file
+     *          the configuration file
+     * @return this builder
+     */
+    public Builder configurationFile(String file)
+    {
+      params.configurationFile = file;
+      return this;
+    }
+  }
+}
\ No newline at end of file
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConnectionParameters.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConnectionParameters.java
new file mode 100644
index 0000000..212f0d5
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ConnectionParameters.java
@@ -0,0 +1,198 @@
+/*
+ * 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.embedded;
+
+/**
+ * Parameters to establish connections to a directory server.
+ */
+public final class ConnectionParameters
+{
+  private String adminPassword;
+  private Integer adminPort;
+  private String adminUid;
+  private String bindDn;
+  private String bindPassword;
+  private String hostname;
+  private Integer ldapPort;
+
+  private ConnectionParameters()
+  {
+    // private constructor to force usage of the associated Builder
+  }
+
+  String getAdminPassword()
+  {
+    return adminPassword;
+  }
+
+  Integer getAdminPort()
+  {
+    return adminPort;
+  }
+
+  String getAdminUid()
+  {
+    return adminUid;
+  }
+
+  String getBindDn()
+  {
+    return bindDn;
+  }
+
+  String getBindPassword()
+  {
+    return bindPassword;
+  }
+
+  String getHostname()
+  {
+    return hostname;
+  }
+
+  Integer getLdapPort()
+  {
+    return ldapPort;
+  }
+
+  /**
+   * Builder for the ConnectionParameters class.
+   */
+  public static final class Builder
+  {
+    private ConnectionParameters params;
+
+    private Builder()
+    {
+      params = new ConnectionParameters();
+    }
+
+    /**
+     * 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.
+     *
+     * @return the replication parameters
+     */
+    public ConnectionParameters toParams()
+    {
+      ConnectionParameters p = params;
+      this.params = new ConnectionParameters();
+      return p;
+    }
+
+    /**
+     * Sets the password of the Global Administrator to use to bind to the server.
+     *
+     * @param password
+     *          the password
+     * @return this builder
+     */
+    public Builder adminPassword(String password)
+    {
+      params.adminPassword = password;
+      return this;
+    }
+
+    /**
+     * Sets the port for directory server administration.
+     *
+     *  @param port
+     *          the admin port
+     * @return this builder
+     */
+    public Builder adminPort(int port)
+    {
+      params.adminPort = port;
+      return this;
+    }
+
+    /**
+     * Sets the user id of the Global Administrator to use to bind to the server.
+     *
+     * @param uid
+     *          the user id
+     * @return this builder
+     */
+    public Builder adminUid(String uid)
+    {
+      params.adminUid = uid;
+      return this;
+    }
+
+    /**
+     * Sets the Dn to use to bind to the directory server.
+     *
+     * @param dn
+     *          the bind Dn
+     * @return this builder
+     */
+    public Builder bindDn(String dn)
+    {
+      params.bindDn = dn;
+      return this;
+    }
+
+    /**
+     * Sets the password to use to bind to the directory server.
+     *
+     * @param password
+     *          the bind password
+     * @return this builder
+     */
+    public Builder bindPassword(String password)
+    {
+      params.bindPassword = password;
+      return this;
+    }
+
+    /**
+     * Sets the the fully-qualified directory server host name.
+     *
+     * @param hostname
+     *          the hostname of the server
+     * @return this builder
+     */
+    public Builder hostname(String hostname)
+    {
+      params.hostname = hostname;
+      return this;
+    }
+
+    /**
+     * Sets the port on which the directory server listen for LDAP communication.
+     *
+     * @param port
+     *          the LDAP port
+     * @return this builder
+     */
+    public Builder ldapPort(int port)
+    {
+      params.ldapPort = port;
+      return this;
+    }
+  }
+}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServer.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServer.java
new file mode 100644
index 0000000..355d7f4
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServer.java
@@ -0,0 +1,591 @@
+/*
+ * 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.embedded;
+
+import static org.forgerock.opendj.config.client.ldap.LDAPManagementContext.newManagementContext;
+import static org.forgerock.opendj.config.client.ldap.LDAPManagementContext.newLDIFManagementContext;
+import static org.opends.messages.UtilityMessages.*;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.adapter.server3x.Adapters;
+import org.forgerock.opendj.config.LDAPProfile;
+import org.forgerock.opendj.config.client.ManagementContext;
+import org.forgerock.opendj.config.server.ConfigException;
+import org.forgerock.opendj.ldap.Connection;
+import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LDAPConnectionFactory;
+import org.forgerock.opendj.server.config.client.RootCfgClient;
+import org.forgerock.util.Pair;
+import org.opends.quicksetup.TempLogFile;
+import org.opends.server.core.DirectoryServer;
+import org.opends.server.protocols.internal.InternalClientConnection;
+import org.opends.server.tools.ImportLDIF;
+import org.opends.server.tools.InstallDS;
+import org.opends.server.tools.RebuildIndex;
+import org.opends.server.tools.dsreplication.ReplicationCliMain;
+import org.opends.server.tools.upgrade.UpgradeCli;
+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;
+
+/**
+ * Represents an embedded directory server on which high-level operations
+ * are available (setup, upgrade, start, stop, ...).
+ */
+public class EmbeddedDirectoryServer
+{
+  private static final String EMBEDDED_OPEN_DJ_PREFIX = "embeddedOpenDJ";
+
+  /** The parameters for install and instance directories, and configuration file of the server. */
+  private final ConfigParameters configParams;
+
+  /** The connection parameters for the server. */
+  private final ConnectionParameters connectionParams;
+
+  /** The connection factory to get connections to the server. */
+  private final LDAPConnectionFactory ldapConnectionFactory;
+
+  /** The output stream used for feedback during operations on server. */
+  private final OutputStream outStream;
+
+  /** The error stream used for feedback during operations on server. */
+  private final OutputStream errStream;
+
+  /**
+   * Defines an embedded directory server, providing the output and error streams used for
+   * giving feedback during operations on the server.
+   *
+   * @param configParams
+   *          The basic configuration parameters for the server.
+   * @param connParams
+   *          The connection parameters for the server.
+   * @param out
+   *          Output stream used for feedback during operations on server
+   * @param err
+   *          Error stream used for feedback during operations on server
+   */
+  private EmbeddedDirectoryServer(ConfigParameters configParams, ConnectionParameters connParams,
+      OutputStream out, OutputStream err)
+  {
+    this.configParams = configParams;
+    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());
+  }
+
+  /**
+   * Defines an embedded directory server.
+   * <p>
+   * Output/error streams used for giving feedback during operations are default system ones.
+   *
+   * @param configParams
+   *          The basic configuration parameters for the server.
+   * @param connParams
+   *          The connection parameters for the server.
+   */
+  private EmbeddedDirectoryServer(ConfigParameters configParams, ConnectionParameters connParams)
+  {
+    this(configParams, connParams, System.out, System.err);
+  }
+
+  /**
+   * Defines an embedded directory server for any operation.
+   *
+   * @param configParams
+   *          The basic configuration parameters for the server.
+   * @param connParams
+   *          The connection parameters for the server.
+   * @param out
+   *          Output stream used for feedback during operations on server
+   * @param err
+   *          Error stream used for feedback during operations on server
+   * @return the directory server
+   */
+  public static EmbeddedDirectoryServer defineServer(ConfigParameters configParams,
+      ConnectionParameters connParams, OutputStream out, OutputStream err)
+  {
+    return new EmbeddedDirectoryServer(configParams, connParams, out, err);
+  }
+
+  /**
+   * Defines an embedded directory server for start/stop operation.
+   * <p>
+   * To be able to perform any operation on the server, use the alternative {@code defineServer()}
+   * method.
+   *
+   * @param configParams
+   *          The basic configuration parameters for the server.
+   * @param out
+   *          Output stream used for feedback during operations on server
+   * @param err
+   *          Error stream used for feedback during operations on server
+   * @return the directory server
+   */
+  public static EmbeddedDirectoryServer defineServerForStartStopOperations(ConfigParameters configParams,
+      OutputStream out, OutputStream err)
+  {
+    return new EmbeddedDirectoryServer(configParams, null, out, err);
+  }
+
+  /**
+   * Displays the replication status on the output stream defined for this server.
+   * <p>
+   * Displays a list with the basic replication configuration of all base DNs of
+   * the servers defined in the registration information.
+   *
+   * @param parameters
+   *            The parameters for the replication.
+   * @throws EmbeddedDirectoryServerException
+   *            If a problem occurs.
+   */
+  public void displayReplicationStatus(ReplicationParameters parameters) throws EmbeddedDirectoryServerException
+  {
+    checkConnectionParameters();
+    int returnCode = ReplicationCliMain.mainCLI(
+        parameters.toCommandLineArgumentsStatus(configParams.getConfigurationFile(), connectionParams),
+        !isRunning(), outStream, errStream);
+
+    if (returnCode != 0)
+    {
+      throw new EmbeddedDirectoryServerException(
+          ERR_EMBEDDED_SERVER_DISPLAY_REPLICATION_STATUS.get(configParams.getServerRootDirectory(), returnCode));
+    }
+  }
+
+  /**
+   * Enables replication between this directory server (first server) and another server
+   * (second server).
+   * <p>
+   * Updates the configuration of the servers to replicate the data under the
+   * base DN specified in the parameters.
+   *
+   * @param parameters
+   *            The parameters for the replication.
+   * @throws EmbeddedDirectoryServerException
+   *            If a problem occurs.
+   */
+  public void enableReplication(ReplicationParameters parameters) throws EmbeddedDirectoryServerException
+  {
+    checkConnectionParameters();
+    int returnCode = ReplicationCliMain.mainCLI(
+        parameters.toCommandLineArgumentsEnable(configParams.getConfigurationFile(), connectionParams),
+        !isRunning(), outStream, errStream);
+
+    if (returnCode != 0)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_ENABLE_REPLICATION.get(
+          configParams.getServerRootDirectory(), parameters.getReplicationPort1(), parameters.getHostname2(),
+          parameters.getReplicationPort2(), returnCode));
+    }
+  }
+
+  /**
+   * Returns an internal connection to the server that will be authenticated as the specified user.
+   *
+   * @param userDn
+   *            The user to be used for authentication to the server
+   * @return the connection
+   * @throws EmbeddedDirectoryServerException
+   *            If the connection can't be returned
+   */
+  public Connection getInternalConnection(DN userDn) throws EmbeddedDirectoryServerException
+  {
+    try
+    {
+      return Adapters.newConnection(new InternalClientConnection(userDn));
+    }
+    catch (DirectoryException e)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_INTERNAL_CONNECTION.get(userDn));
+    }
+  }
+
+  /**
+   * Imports LDIF data to the directory server, overwriting existing data.
+   *
+   * @param parameters
+   *            The import parameters.
+   * @throws EmbeddedDirectoryServerException
+   *            If the import fails
+   */
+  public void importData(ImportParameters parameters) throws EmbeddedDirectoryServerException
+  {
+    checkConnectionParameters();
+    int returnCode = ImportLDIF.mainImportLDIF(
+        parameters.toCommandLineArguments(configParams.getConfigurationFile(), connectionParams),
+        !isRunning(), outStream, errStream);
+
+    if (returnCode != 0)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_IMPORT_DATA.get(
+          parameters.getLdifFile(), configParams.getServerRootDirectory(), returnCode));
+    }
+  }
+
+  /**
+   * Initializes replication between this server and another server.
+   *
+   * @param parameters
+   *            The parameters for the replication.
+   * @throws EmbeddedDirectoryServerException
+   *            If a problem occurs.
+   */
+  public void initializeReplication(ReplicationParameters parameters) throws EmbeddedDirectoryServerException
+  {
+    checkConnectionParameters();
+    int returnCode = ReplicationCliMain.mainCLI(
+        parameters.toCommandLineArgumentsInitialize(configParams.getConfigurationFile(), connectionParams),
+        !isRunning(), outStream, errStream);
+
+    if (returnCode != 0)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_INITIALIZE_REPLICATION.get(
+          configParams.getServerRootDirectory(), connectionParams.getAdminPort(), parameters.getHostname2(),
+          parameters.getAdminPort2(), returnCode));
+    }
+  }
+
+  /**
+   * Indicates whether this server is currently running.
+   *
+   * @return {@code true} if the server is currently running, or {@code false} if not.
+   */
+  public boolean isRunning()
+  {
+    return DirectoryServer.isRunning();
+  }
+
+  /**
+   * Reads the configuration of this server with the provided configuration reader.
+   * <p>
+   * The configuration reader provides access to the root configuration of the directory,
+   * which can then be used to read any configuration object and return the result as an
+   * arbitrary object.
+   * <p>
+   * Example:
+   * <pre>
+   * server.readConfiguration(new DirectoryConfigReader<List<String>>() {
+   *   public List<String> read(RootCfgClient rootConfig) {
+   *    return Arrays.asList(rootConfig.listSynchronizationProviders());
+   *   }
+   * });
+   * </pre>
+   * @param <R>
+   *          the type of the returned result
+   * @param configReader
+   *          the reader of the configuration
+   * @return the result of the read
+   * @throws EmbeddedDirectoryServerException
+   *            If the read fails
+   */
+  public <R> R readConfiguration(DirectoryConfigReader<R> configReader) throws EmbeddedDirectoryServerException
+  {
+    checkConnectionParameters();
+    Pair<ManagementContext, Connection> contextAndConnection = getManagementContext();
+    try
+    {
+      RootCfgClient rootConfig = contextAndConnection.getFirst().getRootConfiguration();
+      return configReader.read(rootConfig);
+    }
+    catch (Exception e)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_READ_CONFIG.get(
+          configParams.getServerRootDirectory(), StaticUtils.stackTraceToSingleLineString(e)));
+    }
+    finally
+    {
+      StaticUtils.close(contextAndConnection.getFirst(), contextAndConnection.getSecond());
+    }
+  }
+
+  /**
+   * Setups this server from the root directory.
+   *
+   * @param parameters
+   *            The setup parameters.
+   * @throws EmbeddedDirectoryServerException
+   *            If the setup fails for any reason.
+   */
+  public void setup(SetupParameters parameters) throws EmbeddedDirectoryServerException
+  {
+    checkConnectionParameters();
+    int returnCode = InstallDS.mainCLI(parameters.toCommandLineArguments(connectionParams), outStream, errStream,
+        TempLogFile.newTempLogFile(EMBEDDED_OPEN_DJ_PREFIX));
+
+    if (returnCode != 0)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_SETUP.get(
+          configParams.getServerRootDirectory(),  parameters.getBaseDn(), parameters.getBackendType(), returnCode));
+    }
+  }
+
+  /**
+   * Setups this server from the provided archive.
+   *
+   * @param openDJZipFile
+   *            The OpenDJ server archive.
+   * @param parameters
+   *            The installation parameters.
+   * @throws EmbeddedDirectoryServerException
+   *            If the setup fails for any reason.
+   */
+  public void setupFromArchive(File openDJZipFile, SetupParameters parameters) throws EmbeddedDirectoryServerException
+  {
+    checkConnectionParameters();
+    try
+    {
+      StaticUtils.extractZipArchive(openDJZipFile, new File(configParams.getServerRootDirectory()));
+    }
+    catch (IOException e)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_SETUP_EXTRACT_ARCHIVE.get(
+          openDJZipFile, configParams.getServerRootDirectory(), StaticUtils.stackTraceToSingleLineString(e)));
+    }
+    setup(parameters);
+  }
+
+  /**
+   * Rebuilds all the indexes of this server.
+   *
+   * @param parameters
+   *            The parameters for rebuilding the indexes.
+   * @throws EmbeddedDirectoryServerException
+   *            If an error occurs.
+   */
+  public void rebuildIndex(RebuildIndexParameters parameters) throws EmbeddedDirectoryServerException
+  {
+    int returnCode = RebuildIndex.mainRebuildIndex(
+        parameters.toCommandLineArguments(), !isRunning(), outStream, errStream);
+
+    if (returnCode != 0)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_REBUILD_INDEX.get(
+          configParams.getServerRootDirectory(), returnCode));
+    }
+  }
+
+  /**
+   * Restarts the directory server.
+   * <p>
+   * This will perform an in-core restart in which the existing server instance will be shut down, a
+   * new instance will be created, and it will be reinitialized and restarted.
+   *
+   * @param className
+   *          The name of the class that initiated the restart.
+   * @param reason
+   *          A message explaining the reason for the restart.
+   */
+  public void restartServer(String className, LocalizableMessage reason)
+  {
+    DirectoryServer.restart(className, reason, DirectoryServer.getEnvironmentConfig());
+  }
+
+  /**
+   * Starts this server.
+   *
+   * @throws EmbeddedDirectoryServerException
+   *           If the server is already running, or if an error occurs during server initialization
+   *           or startup.
+   */
+  public void start() throws EmbeddedDirectoryServerException
+  {
+    if (DirectoryServer.isRunning())
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDUTILS_SERVER_ALREADY_RUNNING.get(
+          configParams.getServerRootDirectory()));
+    }
+
+    try
+    {
+      DirectoryEnvironmentConfig env = new DirectoryEnvironmentConfig();
+      env.setServerRoot(new File(configParams.getServerRootDirectory()));
+      env.setInstanceRoot(new File(configParams.getServerInstanceDirectory()));
+      env.setForceDaemonThreads(true);
+      env.setConfigFile(new File(configParams.getConfigurationFile()));
+
+      DirectoryServer directoryServer = DirectoryServer.reinitialize(env);
+      directoryServer.startServer();
+    }
+    catch (InitializationException | ConfigException e)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_START.get(
+          configParams.getServerRootDirectory(), StaticUtils.stackTraceToSingleLineString(e)));
+    }
+  }
+
+  /**
+   * Stops this server.
+   *
+   * @param className
+   *          The name of the class that initiated the shutdown.
+   * @param reason
+   *          A message explaining the reason for the shutdown.
+   */
+  public void stop(String className, LocalizableMessage reason)
+  {
+    DirectoryServer.shutDown(className, reason);
+  }
+
+  /**
+   * Configures this server with the provided configuration updater.
+   * <p>
+   * The configuration updater provides access to the root configuration of the directory server,
+   * which can then be used to perform one or more modifications on any configuration object.
+   * <p>
+   * Example:
+   * <pre>
+   * server.configure(new DirectoryConfigUpdater() {
+   *
+   *   public void update(RootCfgClient rootConfig) {
+   *     JEBackendCfgClient userRoot = (JEBackendCfgClient) rootConfig.getBackend("userRoot");
+   *     userRoot.setBaseDN(Arrays.asList(DN.valueOf("dc=example,dc=com")));
+   *     userRoot.setDBCachePercent(70);
+   *     userRoot.commit();
+   *   }
+   * });
+   * </pre>
+   *
+   * @param configUpdater
+   *            updates the configuration
+   * @throws EmbeddedDirectoryServerException
+   *            If an error occurs.
+   */
+  public void updateConfiguration(DirectoryConfigUpdater configUpdater) throws EmbeddedDirectoryServerException
+  {
+    checkConnectionParameters();
+    Pair<ManagementContext, Connection> contextAndConnection = getManagementContext();
+    try {
+      RootCfgClient rootConfig = contextAndConnection.getFirst().getRootConfiguration();
+      configUpdater.update(rootConfig);
+    } catch (Exception e) {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_UPDATE_CONFIG.get(
+          configParams.getServerRootDirectory(), StaticUtils.stackTraceToSingleLineString(e)));
+    }
+    finally
+    {
+      StaticUtils.close(contextAndConnection.getFirst(), contextAndConnection.getSecond());
+    }
+  }
+
+  /**
+   * Upgrades this server.
+   * <p>
+   * Upgrades the server configuration and application data so that it is compatible
+   * with the installed binaries.
+   *
+   * @param parameters
+   *          The upgrade parameters.
+   * @throws EmbeddedDirectoryServerException
+   *            If the upgrade fails
+   */
+  public void upgrade(UpgradeParameters parameters) throws EmbeddedDirectoryServerException
+  {
+    int returnCode = UpgradeCli.main(parameters.toCommandLineArguments(
+            configParams.getConfigurationFile()), !isRunning(), outStream, errStream);
+
+    if (returnCode != 0)
+    {
+      throw new EmbeddedDirectoryServerException(ERR_EMBEDDED_SERVER_UPGRADE.get(
+          configParams.getServerRootDirectory(), returnCode));
+    }
+  }
+
+  /**
+   * Interface to update the configuration of the directory server.
+   */
+  public interface DirectoryConfigUpdater
+  {
+    /**
+     * Updates the configuration, provided the root configuration object of the directory server.
+     *
+     * @param rootConfig
+     *          The root configuration of the server.
+     * @throws Exception
+     *          If an error occurs.
+     */
+    public void update(RootCfgClient rootConfig) throws Exception;
+  }
+
+  /**
+   * Interface to read the configuration of the directory server.
+   *
+   * @param <R>
+   *            The type of the result returned by the read operation.
+   */
+  public interface DirectoryConfigReader<R>
+  {
+    /**
+     * Reads the configuration, provided the root configuration object of the directory server.
+     *
+     * @param rootConfig
+     *          The root configuration of the server.
+     * @return the result of the read operation
+     * @throws Exception
+     *          If an error occurs.
+     */
+    public R read(RootCfgClient rootConfig) throws Exception;
+  }
+
+  private void checkConnectionParameters() throws EmbeddedDirectoryServerException
+  {
+    if (connectionParams == null)
+    {
+      throw new EmbeddedDirectoryServerException(LocalizableMessage.raw("Operation is not permitted"));
+    }
+  }
+
+  /**
+   * Retrieves the management context, and optionally a connection if the server is running, in order to
+   * give access to the configuration of the server.
+   */
+  private Pair<ManagementContext, Connection> getManagementContext() throws EmbeddedDirectoryServerException
+  {
+    Connection ldapConnection = null;
+    ManagementContext ctx = null;
+    try
+    {
+      if (isRunning())
+      {
+        ldapConnection = ldapConnectionFactory.getConnection();
+        ctx = newManagementContext(ldapConnection, LDAPProfile.getInstance());
+      }
+      else
+      {
+        ctx = newLDIFManagementContext(new File(configParams.getConfigurationFile()));
+      }
+      return Pair.of(ctx, ldapConnection);
+    }
+    catch (IOException e)
+    {
+      throw new EmbeddedDirectoryServerException(LocalizableMessage.raw("Error when initialising LDIF mgt ctx"));
+    }
+  }
+}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServerException.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServerException.java
new file mode 100644
index 0000000..aa1b871
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/EmbeddedDirectoryServerException.java
@@ -0,0 +1,53 @@
+/*
+ * 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.embedded;
+
+import org.forgerock.i18n.LocalizableMessage;
+import org.opends.server.types.OpenDsException;
+
+/**
+ * Exception that may be thrown by an embedded directory server if a problem occurs while
+ * performing an operation on the server.
+ */
+public final class EmbeddedDirectoryServerException extends OpenDsException
+{
+
+  private static final long serialVersionUID = 1L;
+
+  /**
+   * Creates a new exception with the provided message.
+   *
+   * @param message
+   *          The message that explains the problem that occurred.
+   */
+  public EmbeddedDirectoryServerException(LocalizableMessage message)
+  {
+    super(message);
+  }
+
+  /**
+   * Creates a new exception with the provided message and root cause.
+   *
+   * @param message
+   *          The message that explains the problem that occurred.
+   * @param cause
+   *          The exception that was caught to trigger this exception.
+   */
+  public EmbeddedDirectoryServerException(LocalizableMessage message, Throwable cause)
+  {
+    super(message, cause);
+  }
+}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ImportParameters.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ImportParameters.java
new file mode 100644
index 0000000..f024577
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ImportParameters.java
@@ -0,0 +1,116 @@
+/*
+ * 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.embedded;
+
+/**
+ * Parameters to import LDIF data to a directory server.
+ */
+public final class ImportParameters
+{
+  private String backendID;
+  private String ldifFile;
+
+  private ImportParameters()
+  {
+    // private constructor to force usage of the associated Builder
+  }
+
+  /**
+   * Generates command-line arguments from the parameters.
+   *
+   * @return command-line arguments
+   */
+  String[] toCommandLineArguments(String configurationFile, ConnectionParameters connParams)
+  {
+    return new String[] {
+      "--configFile", configurationFile,
+      "--backendID", backendID,
+      "--bindDN", connParams.getBindDn(),
+      "--bindPassword", connParams.getBindPassword(),
+      "--ldifFile", ldifFile,
+      "--noPropertiesFile",
+      "--trustAll"
+    };
+  }
+
+  String getLdifFile()
+  {
+    return ldifFile;
+  }
+
+  /**
+   * Builder for this class.
+   */
+  public static final class Builder
+  {
+    private ImportParameters params;
+
+    private Builder()
+    {
+      params = new ImportParameters();
+    }
+
+    /**
+     * 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.
+     *
+     * @return the replication parameters
+     */
+    public ImportParameters toParams()
+    {
+      ImportParameters p = params;
+      this.params = new ImportParameters();
+      return p;
+    }
+
+    /**
+     * Sets the backend id of the backend to import.
+     *
+     * @param id
+     *          the backend id
+     * @return this builder
+     */
+    public Builder backendId(String id)
+    {
+      params.backendID = id;
+      return this;
+    }
+
+    /**
+     * Sets the path to the LDIF file to be imported.
+     *
+     * @param ldifFile
+     *          The path to the LDIF file
+     * @return this builder
+     */
+    public Builder ldifFile(String ldifFile)
+    {
+      params.ldifFile = ldifFile;
+      return this;
+    }
+  }
+}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/RebuildIndexParameters.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/RebuildIndexParameters.java
new file mode 100644
index 0000000..818639b
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/RebuildIndexParameters.java
@@ -0,0 +1,108 @@
+/*
+ * 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.embedded;
+
+/**
+ * Parameters to rebuild the indexes of a directory server.
+ */
+public final class RebuildIndexParameters
+{
+  private String configurationFile;
+  private String baseDN;
+
+  private RebuildIndexParameters()
+  {
+    // private constructor to force usage of the associated Builder
+  }
+
+  /**
+   * Generates command-line arguments from the parameters.
+   *
+   * @return command-line arguments
+   */
+  String[] toCommandLineArguments()
+  {
+    return new String[] {
+      "--configFile", configurationFile,
+      "--baseDN", baseDN,
+      "--rebuildAll",
+      "--noPropertiesFile"
+    };
+  }
+
+  /**
+   * Builder for this class.
+   */
+  public static final class Builder
+  {
+    private RebuildIndexParameters params;
+
+    private Builder()
+    {
+      params = new RebuildIndexParameters();
+    }
+
+    /**
+     * 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.
+     *
+     * @return the rebuild index parameters
+     */
+    public RebuildIndexParameters toParams()
+    {
+      RebuildIndexParameters p = params;
+      this.params = new RebuildIndexParameters();
+      return p;
+    }
+
+    /**
+     * 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
+     *          the baseDN
+     * @return this builder
+     */
+    public Builder baseDN(String baseDN)
+    {
+      params.baseDN = baseDN;
+      return this;
+    }
+  }
+}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ReplicationParameters.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ReplicationParameters.java
new file mode 100644
index 0000000..9ddba17
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/ReplicationParameters.java
@@ -0,0 +1,219 @@
+/*
+ * 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.embedded;
+
+/**
+ * Parameters for replication operations on a directory server.
+ */
+public final class ReplicationParameters
+{
+  private String baseDn;
+  private Integer replicationPort1;
+  private Integer replicationPort2;
+  private ConnectionParameters connParamsForHost2;
+
+  private ReplicationParameters()
+  {
+    // private constructor to force usage of the associated Builder
+  }
+
+  /**
+   * Generates the command-line arguments for enabling replication, from the parameters.
+   *
+   * @return command-line arguments
+   */
+  String[] toCommandLineArgumentsEnable(String configurationFile, ConnectionParameters connParams)
+  {
+    return new String[] {
+      "enable",
+      "--no-prompt",
+      "--configFile", configurationFile,
+      "--host1", connParams.getHostname(),
+      "--port1", s(connParams.getAdminPort()),
+      "--bindDN1", connParams.getBindDn(),
+      "--bindPassword1", connParams.getBindPassword(),
+      "--replicationPort1", s(replicationPort1),
+      "--host2", connParamsForHost2.getHostname(),
+      "--port2", s(connParamsForHost2.getAdminPort()),
+      "--bindDN2", connParamsForHost2.getBindDn(),
+      "--bindPassword2", connParamsForHost2.getBindPassword(),
+      "--replicationPort2", s(replicationPort2),
+      "--adminUID", connParams.getAdminUid(),
+      "--adminPassword", connParams.getAdminPassword(),
+      "--baseDN", baseDn,
+      "--trustAll",
+      "--noPropertiesFile" };
+  }
+
+  /**
+   * Generates the command-line arguments for initializing replication, from the parameters.
+   *
+   * @return command-line arguments
+   */
+  String[] toCommandLineArgumentsInitialize(String configurationFile, ConnectionParameters connParams)
+  {
+    return new String[] {
+      "initialize",
+      "--no-prompt",
+      "--configFile", configurationFile,
+      "--hostSource", connParams.getHostname(),
+      "--portSource", s(connParams.getAdminPort()),
+      "--hostDestination", connParamsForHost2.getHostname(),
+      "--portDestination", s(connParamsForHost2.getAdminPort()),
+      "--adminUID", connParams.getAdminUid(),
+      "--adminPassword", connParams.getAdminPassword(),
+      "--baseDN", baseDn,
+      "--trustAll",
+      "--noPropertiesFile" };
+  }
+
+  /**
+   * Generates the command-line arguments for output of the replication status, from the parameters.
+   *
+   * @return command-line arguments
+   */
+  String[] toCommandLineArgumentsStatus(String configurationFile, ConnectionParameters connParams)
+  {
+    return new String[] {
+      "status",
+      "--no-prompt",
+      "--configFile", configurationFile,
+      "--hostname", connParams.getHostname(),
+      "--port", s(connParams.getAdminPort()),
+      "--adminUID", connParams.getAdminUid(),
+      "--adminPassword", connParams.getAdminPassword(),
+      "--script-friendly",
+      "--noPropertiesFile" };
+  }
+
+  int getReplicationPort1()
+  {
+    return replicationPort1;
+  }
+
+  int getReplicationPort2()
+  {
+    return replicationPort2;
+  }
+
+  String getHostname2()
+  {
+    return connParamsForHost2.getHostname();
+  }
+
+  int getAdminPort2()
+  {
+    return connParamsForHost2.getAdminPort();
+  }
+
+  /** Convert an integer to a String. */
+  private String s(Integer val)
+  {
+    return String.valueOf(val);
+  }
+
+  /**
+   * Builder for this class.
+   */
+  public static final class Builder
+  {
+    private ReplicationParameters params;
+
+    private Builder()
+    {
+      params = new ReplicationParameters();
+    }
+
+    /**
+     * 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.
+     *
+     * @return the replication parameters
+     */
+    public ReplicationParameters toParams()
+    {
+      ReplicationParameters p = params;
+      this.params = new ReplicationParameters();
+      return p;
+    }
+
+    /**
+     * Sets the base Dn of the data to be replicated.
+     *
+     * @param baseDn
+     *          the base Dn
+     * @return this builder
+     */
+    public Builder baseDn(String baseDn)
+    {
+      params.baseDn = baseDn;
+      return this;
+    }
+
+    /**
+     * Sets the replication port of the first server whose contents will be replicated.
+     * <p>
+     * The first server should correspond to the embedded server on which the replication
+     * operation is applied.
+     *
+     * @param port
+     *          the replication port
+     * @return this builder
+     */
+    public Builder replicationPort1(int port)
+    {
+      params.replicationPort1 = port;
+      return this;
+    }
+
+    /**
+     * Sets the replication port of the second server whose contents will be replicated.
+     *
+     * @param port
+     *          the replication port
+     * @return this builder
+     */
+    public Builder replicationPort2(int port)
+    {
+      params.replicationPort2 = port;
+      return this;
+    }
+
+    /**
+     * Sets the connection parameters of the second server whose contents will be replicated.
+     *
+     * @param host2Params
+     *          The connection parameters
+     * @return this builder
+     */
+    public Builder connectionParamsForHost2(ConnectionParameters.Builder host2Params)
+    {
+      params.connParamsForHost2 = host2Params.toParams();
+      return this;
+    }
+  }
+}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/SetupParameters.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/SetupParameters.java
new file mode 100644
index 0000000..86c4df1
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/SetupParameters.java
@@ -0,0 +1,147 @@
+/*
+ * 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.embedded;
+
+/**
+ * Parameters to setup a directory server.
+ */
+public final class SetupParameters
+{
+  private String baseDn;
+  private int jmxPort;
+  private String backendType;
+
+  private SetupParameters()
+  {
+    // private constructor to force usage of the associated Builder
+  }
+
+  /**
+   * Generates command-line arguments from the parameters.
+   *
+   * @return command-line arguments
+   */
+  String[] toCommandLineArguments(ConnectionParameters connParams)
+  {
+    return new String[] {
+      "--cli",
+      "--noPropertiesFile",
+      "--no-prompt",
+      "--doNotStart",
+      "--skipPortCheck",
+      "--baseDN", baseDn,
+      "--hostname", connParams.getHostname(),
+      "--rootUserDN", connParams.getBindDn(),
+      "--rootUserPassword", connParams.getBindPassword(),
+      "--ldapPort", s(connParams.getLdapPort()),
+      "--adminConnectorPort", s(connParams.getAdminPort()),
+      "--jmxPort", s(jmxPort),
+      "--backendType", backendType
+    };
+  }
+
+  String getBaseDn()
+  {
+    return baseDn;
+  }
+
+  String getBackendType()
+  {
+    return backendType;
+  }
+
+  /** Convert an integer to a String. */
+  private String s(Integer val)
+  {
+    return String.valueOf(val);
+  }
+
+  /**
+   * Builder for this class.
+   */
+  public static final class Builder
+  {
+    private SetupParameters params;
+
+    private Builder()
+    {
+      params = new SetupParameters();
+    }
+
+    /**
+     * 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.
+     *
+     * @return the replication parameters
+     */
+    public SetupParameters toParams()
+    {
+      SetupParameters p = params;
+      this.params = new SetupParameters();
+      return p;
+    }
+
+    /**
+     * Sets the base Dn for user information in the directory server.
+     *
+     * @param baseDn
+     *          the base Dn
+     * @return this builder
+     */
+    public Builder baseDn(String baseDn)
+    {
+      params.baseDn = baseDn;
+      return this;
+    }
+
+    /**
+     * Sets the port on which the directory server should listen for JMX communication.
+     *
+     * @param jmxPort
+     *          the JMX port
+     * @return this builder
+     */
+    public Builder jmxPort(int jmxPort)
+    {
+      params.jmxPort = jmxPort;
+      return this;
+    }
+
+    /**
+     * Sets the type of the backend containing user information.
+     *
+     * @param backendType
+     *          the backend type (e.g. je, pdb)
+     * @return this builder
+     */
+    public Builder backendType(String backendType)
+    {
+      params.backendType = backendType;
+      return this;
+    }
+  }
+}
\ No newline at end of file
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/UpgradeParameters.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/UpgradeParameters.java
new file mode 100644
index 0000000..2d235d3
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/UpgradeParameters.java
@@ -0,0 +1,102 @@
+/*
+ * 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.embedded;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Parameters to upgrade a Directory Server.
+ */
+public final class UpgradeParameters
+{
+  private boolean ignoreErrors;
+
+  private UpgradeParameters()
+  {
+    // private constructor to force usage of the associated Builder
+  }
+
+  /**
+   * Generates command-line arguments from the parameters.
+   *
+   * @return command-line arguments
+   */
+  String[] toCommandLineArguments(String configurationFile)
+  {
+    List<String> args = new ArrayList<>(6);
+    args.add("--acceptLicense");
+    args.add("--no-prompt");
+    args.add("--force");
+    args.add("--configFile");
+    args.add(configurationFile);
+    if (ignoreErrors) {
+      args.add("--ignoreErrors");
+    }
+    return args.toArray(new String[args.size()]);
+  }
+
+  /**
+   * Builder for the UpgradeParameters class.
+   */
+  public static final class Builder
+  {
+    private UpgradeParameters params;
+
+    private Builder()
+    {
+      params = new UpgradeParameters();
+    }
+
+    /**
+     * Starts construction of the upgrade parameters.
+     *
+     * @return this builder
+     */
+    public static Builder upgradeParams()
+    {
+      return new Builder();
+    }
+
+    /**
+     * Returns the fully initialized parameters.
+     *
+     * @return the parameters
+     */
+    public UpgradeParameters toParams()
+    {
+      UpgradeParameters p = params;
+      this.params = new UpgradeParameters();
+      return p;
+    }
+
+    /**
+     * Indicates whether errors should be ignored during the upgrade.
+     * <p>
+     * This option should be used with caution and may be useful in automated deployments where
+     * potential errors are known in advance and resolved after the upgrade has completed
+     *
+     * @param ignore
+     *          indicates whether errors should be ignored
+     * @return this builder
+     */
+    public Builder isIgnoreErrors(boolean ignore)
+    {
+      params.ignoreErrors = ignore;
+      return this;
+    }
+  }
+}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/package-info.java b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/package-info.java
new file mode 100644
index 0000000..67c491c
--- /dev/null
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/embedded/package-info.java
@@ -0,0 +1,19 @@
+/*
+ * 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.
+ */
+/**
+ * Provides support for an embedded directory server.
+ */
+package org.opends.server.util.embedded;
\ No newline at end of file
diff --git a/opendj-server-legacy/src/messages/org/opends/messages/utility.properties b/opendj-server-legacy/src/messages/org/opends/messages/utility.properties
index 003b7f8..9cf169c 100644
--- a/opendj-server-legacy/src/messages/org/opends/messages/utility.properties
+++ b/opendj-server-legacy/src/messages/org/opends/messages/utility.properties
@@ -210,8 +210,8 @@
  to or replace the file
 ERR_LDIF_SKIP_165=Skipping entry %s because the DN is not one that \
  should be included based on the include and exclude branches/filters
-ERR_EMBEDUTILS_SERVER_ALREADY_RUNNING_167=The Directory Server cannot \
- be started because it is already running
+ERR_EMBEDUTILS_SERVER_ALREADY_RUNNING_167=The embedded server with server \
+ root '%s' cannot be started because it is already running.
 INFO_EMAIL_TOOL_DESCRIPTION_171=Send an e-mail message via SMTP
 INFO_EMAIL_HOST_DESCRIPTION_172=The address of the SMTP server to use to send \
  the message
@@ -406,3 +406,34 @@
 ERR_BACKUP_CANNOT_CREATE_SAVE_DIRECTORY_326=An error occurred while \
  attempting to create a save directory with base path %s before restore of \
  backup of %s: %s
+ERR_EMBEDDED_SERVER_DISPLAY_REPLICATION_STATUS_327=An error occurred while attempting \
+ to display replication status of embedded server with server root '%s'. Error code \
+ is: %s
+ERR_EMBEDDED_SERVER_ENABLE_REPLICATION_328=An error occurred while attempting \
+ to enable replication between embedded server with server root '%s' and replication \
+ port1 '%s' and second server with hostname '%s' and replication port2 '%s'. Error code \
+ is: %s
+ERR_EMBEDDED_SERVER_IMPORT_DATA_329=An error occurred while attempting \
+ to import LDIF file '%s' into embedded server with server root '%s'. Error code \
+ is: %s
+ERR_EMBEDDED_SERVER_INITIALIZE_REPLICATION_330=An error occurred while attempting \
+ to initialize replication between embedded server with server root '%s' and admin \
+ port1 '%s' and second server with hostname '%s' and admin port2 '%s'. Error code \
+ is: %s
+ERR_EMBEDDED_SERVER_READ_CONFIG_331=An error occurred while attempting \
+ to read configuration of embedded server with server root '%s' : %s
+ERR_EMBEDDED_SERVER_SETUP_332=An error occurred while attempting \
+ to setup the embedded server with server root '%s', base DN '%s' and backend type '%s'. \
+ Error code is: %s
+ERR_EMBEDDED_SERVER_SETUP_EXTRACT_ARCHIVE_333=An error occurred while attempting \
+ to extract server archive '%s' before setup of embedded server with server root '%s': %s
+ERR_EMBEDDED_SERVER_REBUILD_INDEX_334=An error occurred while attempting \
+ to rebuild index of embedded server with server root '%s'. Error code is: %s
+ERR_EMBEDDED_SERVER_UPDATE_CONFIG_335=An error occurred while attempting \
+ to update configuration of embedded server with server root '%s' : %s
+ERR_EMBEDDED_SERVER_START_336=An error occurred while attempting \
+ to start the embedded server with server root '%s' : %s
+ERR_EMBEDDED_SERVER_UPGRADE_337=An error occurred while attempting \
+ to upgrade the embedded server with server root '%s' : %s
+ERR_EMBEDDED_SERVER_INTERNAL_CONNECTION=An error occurred while attempting to retrieve \
+ an internal connection to the server with the user DN '%s'
\ No newline at end of file

--
Gitblit v1.10.0