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

Gaetan Boismal
06.43.2015 b7b340fb143d4d58411d16166cf4e73ee5d0f523
OPENDJ-1993 Code cleanup

* org.opends.quicksetup.util.Utils
** Autorefactor'ed file
** Reformat
** Use straight return
** Use List instead of ArrayList as declarative type
1 files modified
928 ■■■■ changed files
opendj-server-legacy/src/main/java/org/opends/quicksetup/util/Utils.java 928 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/util/Utils.java
@@ -79,20 +79,17 @@
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
  private Utils() {}
  private static final int BUFFER_SIZE = 1024;
  private static final int MAX_LINE_WIDTH = 80;
  private Utils()
  {
  }
  /** Chars that require special treatment when passing them to command-line. */
  private static final char[] CHARS_TO_ESCAPE =
    { ' ', '\t', '\n', '|', ';', '<', '>', '(', ')', '$', '`', '\\', '"', '\'' };
  /**
   * The class name that contains the control panel customizations for
   * products.
   */
  private static final String CUSTOMIZATION_CLASS_NAME =
    "org.opends.server.util.ReleaseDefinition";
  /** The class name that contains the control panel customizations for products. */
  private static final String CUSTOMIZATION_CLASS_NAME = "org.opends.server.util.ReleaseDefinition";
  /** The service name required by the JNLP downloader. */
  public static final String JNLP_SERVICE_NAME = "javax.jnlp.DownloadService";
@@ -100,9 +97,11 @@
  /**
   * Returns <CODE>true</CODE> if the provided port is free and we can use it,
   * <CODE>false</CODE> otherwise.
   * @param port the port we are analyzing.
   *
   * @param port
   *          the port we are analyzing.
   * @return <CODE>true</CODE> if the provided port is free and we can use it,
   * <CODE>false</CODE> otherwise.
   *         <CODE>false</CODE> otherwise.
   */
  public static boolean canUseAsPort(int port)
  {
@@ -112,47 +111,46 @@
  /**
   * Returns <CODE>true</CODE> if the provided port is a privileged port,
   * <CODE>false</CODE> otherwise.
   * @param port the port we are analyzing.
   *
   * @param port
   *          the port we are analyzing.
   * @return <CODE>true</CODE> if the provided port is a privileged port,
   * <CODE>false</CODE> otherwise.
   *         <CODE>false</CODE> otherwise.
   */
  public static boolean isPrivilegedPort(int port)
  {
    return SetupUtils.isPrivilegedPort(port);
  }
  /**
   * Tells whether the provided java installation supports a given option or
   * not.
   * @param javaHome the java installation path.
   * @param option the java option that we want to check.
   * @param installPath the install path of the server.
   *
   * @param javaHome
   *          the java installation path.
   * @param option
   *          the java option that we want to check.
   * @param installPath
   *          the install path of the server.
   * @return <CODE>true</CODE> if the provided java installation supports a
   * given option and <CODE>false</CODE> otherwise.
   *         given option and <CODE>false</CODE> otherwise.
   */
  public static boolean supportsOption(String option, String javaHome,
      String installPath)
  public static boolean supportsOption(String option, String javaHome, String installPath)
  {
    boolean supported = false;
    logger.info(LocalizableMessage.raw("Checking if options "+option+
        " are supported with java home: "+javaHome));
    logger.info(LocalizableMessage.raw("Checking if options " + option + " are supported with java home: " + javaHome));
    try
    {
      List<String> args = new ArrayList<String>();
      List<String> args = new ArrayList<>();
      String script;
      String libPath = Utils.getPath(installPath,
          Installation.LIBRARIES_PATH_RELATIVE);
      String libPath = Utils.getPath(installPath, Installation.LIBRARIES_PATH_RELATIVE);
      if (isWindows())
      {
        script = Utils.getScriptPath(Utils.getPath(libPath,
            Installation.SCRIPT_UTIL_FILE_WINDOWS));
        script = Utils.getScriptPath(Utils.getPath(libPath, Installation.SCRIPT_UTIL_FILE_WINDOWS));
      }
      else
      {
        script = Utils.getScriptPath(Utils.getPath(libPath,
            Installation.SCRIPT_UTIL_FILE_UNIX));
        script = Utils.getScriptPath(Utils.getPath(libPath, Installation.SCRIPT_UTIL_FILE_UNIX));
      }
      args.add(script);
      ProcessBuilder pb = new ProcessBuilder(args);
@@ -168,13 +166,14 @@
        env.put("DO_NOT_PAUSE", "true");
      }
      final Process process = pb.start();
      logger.info(LocalizableMessage.raw("launching "+args+ " with env: "+env));
      logger.info(LocalizableMessage.raw("launching " + args + " with env: " + env));
      InputStream is = process.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String line;
      boolean errorDetected = false;
      while (null != (line = reader.readLine())) {
        logger.info(LocalizableMessage.raw("The output: "+line));
      while (null != (line = reader.readLine()))
      {
        logger.info(LocalizableMessage.raw("The output: " + line));
        if (line.contains("ERROR:  The detected Java version"))
        {
          if (isWindows())
@@ -207,29 +206,35 @@
      }
      process.waitFor();
      int returnCode = process.exitValue();
      logger.info(LocalizableMessage.raw("returnCode: "+returnCode));
      logger.info(LocalizableMessage.raw("returnCode: " + returnCode));
      supported = returnCode == 0 && !errorDetected;
      logger.info(LocalizableMessage.raw("supported: "+supported));
      logger.info(LocalizableMessage.raw("supported: " + supported));
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error testing option "+option+" on "+javaHome, t));
      logger.warn(LocalizableMessage.raw("Error testing option " + option + " on " + javaHome, t));
    }
    return supported;
  }
  /**
   * Creates a new file attempting to create the parent directories
   * if necessary.
   * @param f File to create
   * Creates a new file attempting to create the parent directories if
   * necessary.
   *
   * @param f
   *          File to create
   * @return boolean indicating whether the file was created; false otherwise
   * @throws IOException if something goes wrong
   * @throws IOException
   *           if something goes wrong
   */
  public static boolean createFile(File f) throws IOException {
  public static boolean createFile(File f) throws IOException
  {
    boolean success = false;
    if (f != null) {
    if (f != null)
    {
      File parent = f.getParentFile();
      if (!parent.exists()) {
      if (!parent.exists())
      {
        parent.mkdirs();
      }
      success = f.createNewFile();
@@ -239,8 +244,11 @@
  /**
   * Returns the absolute path for the given parentPath and relativePath.
   * @param parentPath the parent path.
   * @param relativePath the relative path.
   *
   * @param parentPath
   *          the parent path.
   * @param relativePath
   *          the relative path.
   * @return the absolute path for the given parentPath and relativePath.
   */
  public static String getPath(String parentPath, String relativePath)
@@ -250,9 +258,11 @@
  /**
   * Returns the String that can be used to launch an script using Runtime.exec.
   * This method is required because in Windows the script that contain a "="
   * in their path must be quoted.
   * @param script the script name
   * This method is required because in Windows the script that contain a "=" in
   * their path must be quoted.
   *
   * @param script
   *          the script name
   * @return the absolute path for the given parentPath and relativePath.
   */
  public static String getScriptPath(String script)
@@ -261,15 +271,18 @@
  }
  /**
   * Returns the absolute path for the given file.  It tries to get the
   * canonical file path.  If it fails it returns the string representation.
   * @param f File to get the path
   * Returns the absolute path for the given file. It tries to get the canonical
   * file path. If it fails it returns the string representation.
   *
   * @param f
   *          File to get the path
   * @return the absolute path for the given file.
   */
  public static String getPath(File f)
  {
    String path = null;
    if (f != null) {
    if (f != null)
    {
      try
      {
        /*
@@ -280,7 +293,8 @@
      }
      catch (IOException ioe)
      {
        /* This is a best effort to get the best possible representation of the
        /*
         * This is a best effort to get the best possible representation of the
         * file: reporting the error is not necessary.
         */
      }
@@ -292,19 +306,26 @@
  /**
   * Returns <CODE>true</CODE> if the first provided path is under the second
   * path in the file system.
   * @param descendant the descendant candidate path.
   * @param path the path.
   *
   * @param descendant
   *          the descendant candidate path.
   * @param path
   *          the path.
   * @return <CODE>true</CODE> if the first provided path is under the second
   * path in the file system; <code>false</code> otherwise or if
   * either of the files are null
   *         path in the file system; <code>false</code> otherwise or if either
   *         of the files are null
   */
  public static boolean isDescendant(File descendant, File path) {
  public static boolean isDescendant(File descendant, File path)
  {
    boolean isDescendant = false;
    if (descendant != null && path != null) {
    if (descendant != null && path != null)
    {
      File parent = descendant.getParentFile();
      while (parent != null && !isDescendant) {
      while (parent != null && !isDescendant)
      {
        isDescendant = path.equals(parent);
        if (!isDescendant) {
        if (!isDescendant)
        {
          parent = parent.getParentFile();
        }
      }
@@ -315,9 +336,11 @@
  /**
   * Returns <CODE>true</CODE> if the parent directory for the provided path
   * exists and <CODE>false</CODE> otherwise.
   * @param path the path that we are analyzing.
   *
   * @param path
   *          the path that we are analyzing.
   * @return <CODE>true</CODE> if the parent directory for the provided path
   * exists and <CODE>false</CODE> otherwise.
   *         exists and <CODE>false</CODE> otherwise.
   */
  public static boolean parentDirectoryExists(String path)
  {
@@ -334,9 +357,11 @@
  /**
   * Returns <CODE>true</CODE> if the the provided path is a file and exists and
   * <CODE>false</CODE> otherwise.
   * @param path the path that we are analyzing.
   *
   * @param path
   *          the path that we are analyzing.
   * @return <CODE>true</CODE> if the the provided path is a file and exists and
   * <CODE>false</CODE> otherwise.
   *         <CODE>false</CODE> otherwise.
   */
  public static boolean fileExists(String path)
  {
@@ -347,9 +372,11 @@
  /**
   * Returns <CODE>true</CODE> if the the provided path is a directory, exists
   * and is not empty <CODE>false</CODE> otherwise.
   * @param path the path that we are analyzing.
   *
   * @param path
   *          the path that we are analyzing.
   * @return <CODE>true</CODE> if the the provided path is a directory, exists
   * and is not empty <CODE>false</CODE> otherwise.
   *         and is not empty <CODE>false</CODE> otherwise.
   */
  public static boolean directoryExistsAndIsNotEmpty(String path)
  {
@@ -365,15 +392,16 @@
  /**
   * Returns <CODE>true</CODE> if the the provided string is a configuration DN
   * and <CODE>false</CODE> otherwise.
   * @param dn the String we are analyzing.
   *
   * @param dn
   *          the String we are analyzing.
   * @return <CODE>true</CODE> if the the provided string is a configuration DN
   * and <CODE>false</CODE> otherwise.
   *         and <CODE>false</CODE> otherwise.
   */
  public static boolean isConfigurationDn(String dn)
  {
    boolean isConfigurationDn = false;
    String[] configDns =
      { "cn=config", Constants.SCHEMA_DN };
    String[] configDns = { "cn=config", Constants.SCHEMA_DN };
    for (int i = 0; i < configDns.length && !isConfigurationDn; i++)
    {
      isConfigurationDn = areDnsEqual(dn, configDns[i]);
@@ -382,12 +410,15 @@
  }
  /**
   * Returns <CODE>true</CODE> if the the provided strings represent the same
   * DN and <CODE>false</CODE> otherwise.
   * @param dn1 the first dn to compare.
   * @param dn2 the second dn to compare.
   * @return <CODE>true</CODE> if the the provided strings represent the same
   * DN and <CODE>false</CODE> otherwise.
   * Returns <CODE>true</CODE> if the the provided strings represent the same DN
   * and <CODE>false</CODE> otherwise.
   *
   * @param dn1
   *          the first dn to compare.
   * @param dn2
   *          the second dn to compare.
   * @return <CODE>true</CODE> if the the provided strings represent the same DN
   *         and <CODE>false</CODE> otherwise.
   */
  public static boolean areDnsEqual(String dn1, String dn2)
  {
@@ -397,7 +428,9 @@
      LdapName name1 = new LdapName(dn1);
      LdapName name2 = new LdapName(dn2);
      areDnsEqual = name1.equals(name2);
    } catch (Exception ex) {
    }
    catch (Exception ex)
    {
      // do nothing
    }
@@ -406,14 +439,18 @@
  /**
   * Creates the parent directory if it does not already exist.
   * @param f File for which parentage will be insured
   * @return boolean indicating whether or not the input <code>f</code>
   * has a parent after this method is invoked.
   *
   * @param f
   *          File for which parentage will be insured
   * @return boolean indicating whether or not the input <code>f</code> has a
   *         parent after this method is invoked.
   */
  public static boolean insureParentsExist(File f) {
  public static boolean insureParentsExist(File f)
  {
    final File parent = f.getParentFile();
    final boolean b = parent.exists();
    if (!b) {
    if (!b)
    {
      return parent.mkdirs();
    }
    return b;
@@ -421,21 +458,28 @@
  /**
   * Creates the a directory in the provided path.
   * @param path the path.
   *
   * @param path
   *          the path.
   * @return <CODE>true</CODE> if the path was created or already existed (and
   * was a directory) and <CODE>false</CODE> otherwise.
   * @throws IOException if something goes wrong.
   *         was a directory) and <CODE>false</CODE> otherwise.
   * @throws IOException
   *           if something goes wrong.
   */
  public static boolean createDirectory(String path) throws IOException {
  public static boolean createDirectory(String path) throws IOException
  {
    return createDirectory(new File(path));
  }
  /**
   * Creates the a directory in the provided path.
   * @param f the path.
   *
   * @param f
   *          the path.
   * @return <CODE>true</CODE> if the path was created or already existed (and
   * was a directory) and <CODE>false</CODE> otherwise.
   * @throws IOException if something goes wrong.
   *         was a directory) and <CODE>false</CODE> otherwise.
   * @throws IOException
   *           if something goes wrong.
   */
  public static boolean createDirectory(File f) throws IOException
  {
@@ -443,7 +487,8 @@
    if (!f.exists())
    {
      directoryCreated = f.mkdirs();
    } else
    }
    else
    {
      directoryCreated = f.isDirectory();
    }
@@ -453,9 +498,13 @@
  /**
   * Creates a file on the specified path with the contents of the provided
   * stream.
   * @param path the path where the file will be created.
   * @param is the InputStream with the contents of the file.
   * @throws IOException if something goes wrong.
   *
   * @param path
   *          the path where the file will be created.
   * @param is
   *          the InputStream with the contents of the file.
   * @throws IOException
   *           if something goes wrong.
   */
  public static void createFile(File path, InputStream is) throws IOException
  {
@@ -478,15 +527,18 @@
  /**
   * Creates a file on the specified path with the contents of the provided
   * String.  The file is protected, so that 'others' have no access to it.
   * @param path the path where the file will be created.
   * @param content the String with the contents of the file.
   * @throws IOException if something goes wrong.
   * @throws InterruptedException if there is a problem changing the permissions
   * of the file.
   * String. The file is protected, so that 'others' have no access to it.
   *
   * @param path
   *          the path where the file will be created.
   * @param content
   *          the String with the contents of the file.
   * @throws IOException
   *           if something goes wrong.
   * @throws InterruptedException
   *           if there is a problem changing the permissions of the file.
   */
  public static void createProtectedFile(String path, String content)
  throws IOException, InterruptedException
  public static void createProtectedFile(String path, String content) throws IOException, InterruptedException
  {
    FileWriter file = new FileWriter(path);
    PrintWriter out = new PrintWriter(file);
@@ -503,22 +555,24 @@
  }
  /**
   * This is a helper method that gets a LocalizableMessage representation of the elements
   * in the Collection of Messages. The LocalizableMessage will display the different
   * elements separated by the separator String.
   * This is a helper method that gets a LocalizableMessage representation of
   * the elements in the Collection of Messages. The LocalizableMessage will
   * display the different elements separated by the separator String.
   *
   * @param col
   *          the collection containing the messages.
   * @param separator
   *          the separator String to be used.
   * @return the message representation for the collection;
   *          null if <code>col</code> is null
   * @return the message representation for the collection; null if
   *         <code>col</code> is null
   */
  public static LocalizableMessage getMessageFromCollection(Collection<LocalizableMessage> col,
                                                 String separator) {
    if (col != null) {
  public static LocalizableMessage getMessageFromCollection(Collection<LocalizableMessage> col, String separator)
  {
    if (col != null)
    {
      final LocalizableMessageBuilder mb = new LocalizableMessageBuilder();
      for (LocalizableMessage m : col) {
      for (LocalizableMessage m : col)
      {
        mb.append(separator).append(m);
      }
      return mb.toMessage();
@@ -527,20 +581,19 @@
  }
  /**
   * Returns the default server location that will be proposed to the user
   * in the installation.
   * @return the default server location that will be proposed to the user
   * in the installation.
   * Returns the default server location that will be proposed to the user in
   * the installation.
   *
   * @return the default server location that will be proposed to the user in
   *         the installation.
   */
  public static String getDefaultServerLocation()
  {
    String userDir = System.getProperty("user.home");
    String firstLocation = userDir + File.separator
        + SHORT_NAME.toLowerCase(Locale.ENGLISH);
    String firstLocation = userDir + File.separator + SHORT_NAME.toLowerCase(Locale.ENGLISH);
    String serverLocation = firstLocation;
    int i = 1;
    while (fileExists(serverLocation)
        || directoryExistsAndIsNotEmpty(serverLocation))
    while (fileExists(serverLocation) || directoryExistsAndIsNotEmpty(serverLocation))
    {
      serverLocation = firstLocation + "-" + i;
      i++;
@@ -551,13 +604,15 @@
  /**
   * Returns <CODE>true</CODE> if there is more disk space in the provided path
   * than what is specified with the bytes parameter.
   * @param directoryPath the path.
   * @param bytes the disk space.
   *
   * @param directoryPath
   *          the path.
   * @param bytes
   *          the disk space.
   * @return <CODE>true</CODE> if there is more disk space in the provided path
   * than what is specified with the bytes parameter.
   *         than what is specified with the bytes parameter.
   */
  public static synchronized boolean hasEnoughSpace(String directoryPath,
      long bytes)
  public static synchronized boolean hasEnoughSpace(String directoryPath, long bytes)
  {
    // TODO This does not work with quotas etc. but at least it seems that
    // we do not write all data on disk if it fails.
@@ -570,15 +625,18 @@
    {
      deleteDirectory = directory.mkdir();
    }
    try
    {
      file = File.createTempFile("temp" + System.nanoTime(), ".tmp", directory);
      raf = new RandomAccessFile(file, "rw");
      raf.setLength(bytes);
      hasEnoughSpace = true;
    } catch (IOException ex)
    }
    catch (IOException ex)
    { /* do nothing */
    } finally
    }
    finally
    {
      StaticUtils.close(raf);
      if (file != null)
@@ -586,16 +644,20 @@
        file.delete();
      }
    }
    if (deleteDirectory)
    {
      directory.delete();
    }
    return hasEnoughSpace;
  }
  /**
   * Gets a localized representation of the provide TopologyCacheException.
   * @param te the exception.
   *
   * @param te
   *          the exception.
   * @return a localized representation of the provide TopologyCacheException.
   */
  public static LocalizableMessage getMessage(TopologyCacheException te)
@@ -615,12 +677,11 @@
    }
    else if (te.getCause() instanceof NamingException)
    {
      buf.append(getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(),
          te.getCause()));
      buf.append(getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(), te.getCause()));
    }
    else
    {
      logger.warn(LocalizableMessage.raw("Unexpected error: "+te, te));
      logger.warn(LocalizableMessage.raw("Unexpected error: " + te, te));
      // This is unexpected.
      if (te.getCause() != null)
      {
@@ -637,15 +698,20 @@
  /**
   * Sets the permissions of the provided paths with the provided permission
   * String.
   * @param paths the paths to set permissions on.
   * @param permissions the UNIX-mode file system permission representation
   * (for example "644" or "755")
   *
   * @param paths
   *          the paths to set permissions on.
   * @param permissions
   *          the UNIX-mode file system permission representation (for example
   *          "644" or "755")
   * @return the return code of the chmod command.
   * @throws IOException if something goes wrong.
   * @throws InterruptedException if the Runtime.exec method is interrupted.
   * @throws IOException
   *           if something goes wrong.
   * @throws InterruptedException
   *           if the Runtime.exec method is interrupted.
   */
  public static int setPermissionsUnix(ArrayList<String> paths,
      String permissions) throws IOException, InterruptedException
  public static int setPermissionsUnix(ArrayList<String> paths, String permissions) throws IOException,
      InterruptedException
  {
    String[] args = new String[paths.size() + 2];
    args[0] = "chmod";
@@ -661,15 +727,19 @@
  /**
   * Sets the permissions of the provided paths with the provided permission
   * String.
   * @param path to set permissions on.
   * @param permissions the UNIX-mode file system permission representation
   * (for example "644" or "755")
   *
   * @param path
   *          to set permissions on.
   * @param permissions
   *          the UNIX-mode file system permission representation (for example
   *          "644" or "755")
   * @return the return code of the chmod command.
   * @throws IOException if something goes wrong.
   * @throws InterruptedException if the Runtime.exec method is interrupted.
   * @throws IOException
   *           if something goes wrong.
   * @throws InterruptedException
   *           if the Runtime.exec method is interrupted.
   */
  public static int setPermissionsUnix(String path,
      String permissions) throws IOException, InterruptedException
  public static int setPermissionsUnix(String path, String permissions) throws IOException, InterruptedException
  {
    String[] args = new String[3];
    args[0] = "chmod";
@@ -693,8 +763,9 @@
  /**
   * Returns <CODE>true</CODE> if this is executed from command line and
   * <CODE>false</CODE> otherwise.
   *
   * @return <CODE>true</CODE> if this is executed from command line and
   * <CODE>false</CODE> otherwise.
   *         <CODE>false</CODE> otherwise.
   */
  public static boolean isCli()
  {
@@ -703,30 +774,30 @@
  /**
   * Creates an LDAP+StartTLS connection and returns the corresponding
   * LdapContext.
   * This method first creates an LdapContext with anonymous bind. Then it
   * requests a StartTlsRequest extended operation. The StartTlsResponse is
   * setup with the specified hostname verifier. Negotiation is done using a
   * LdapContext. This method first creates an LdapContext with anonymous bind.
   * Then it requests a StartTlsRequest extended operation. The StartTlsResponse
   * is setup with the specified hostname verifier. Negotiation is done using a
   * TrustSocketFactory so that the specified TrustManager gets called during
   * the SSL handshake.
   * If trust manager is null, certificates are not checked during SSL
   * handshake.
   * the SSL handshake. If trust manager is null, certificates are not checked
   * during SSL handshake.
   *
   * @param ldapsURL      the target *LDAPS* URL.
   * @param dn            passed as Context.SECURITY_PRINCIPAL if not null.
   * @param pwd           passed as Context.SECURITY_CREDENTIALS if not null.
   * @param timeout       passed as com.sun.jndi.ldap.connect.timeout if > 0.
   * @param env           null or additional environment properties.
   * @param trustManager  null or the trust manager to be invoked during SSL.
   * negociation.
   * @param verifier      null or the hostname verifier to be setup in the
   * StartTlsResponse.
   *
   * @param ldapsURL
   *          the target *LDAPS* URL.
   * @param dn
   *          passed as Context.SECURITY_PRINCIPAL if not null.
   * @param pwd
   *          passed as Context.SECURITY_CREDENTIALS if not null.
   * @param timeout
   *          passed as com.sun.jndi.ldap.connect.timeout if > 0.
   * @param env
   *          null or additional environment properties.
   * @param trustManager
   *          null or the trust manager to be invoked during SSL. negociation.
   * @param verifier
   *          null or the hostname verifier to be setup in the StartTlsResponse.
   * @return the established connection with the given parameters.
   *
   * @throws NamingException the exception thrown when instantiating
   * InitialLdapContext.
   *
   * @throws NamingException
   *           the exception thrown when instantiating InitialLdapContext.
   * @see javax.naming.Context
   * @see javax.naming.ldap.InitialLdapContext
   * @see javax.naming.ldap.StartTlsRequest
@@ -734,55 +805,53 @@
   * @see org.opends.admin.ads.util.TrustedSocketFactory
   */
  public static InitialLdapContext createStartTLSContext(String ldapsURL,
      String dn, String pwd, int timeout, Hashtable<String, String> env,
      TrustManager trustManager, HostnameVerifier verifier)
  throws NamingException
  public static InitialLdapContext createStartTLSContext(String ldapsURL, String dn, String pwd, int timeout,
      Hashtable<String, String> env, TrustManager trustManager, HostnameVerifier verifier) throws NamingException
  {
    return ConnectionUtils.createStartTLSContext(ldapsURL, dn, pwd, timeout,
        env, trustManager, null, verifier);
    return ConnectionUtils.createStartTLSContext(ldapsURL, dn, pwd, timeout, env, trustManager, null, verifier);
  }
  /**
   * Returns a message object for the given NamingException.  The code assume
   * Returns a message object for the given NamingException. The code assume
   * that we are trying to connect to the local server.
   * @param ne the NamingException.
   *
   * @param ne
   *          the NamingException.
   * @return a message object for the given NamingException.
   */
  public static LocalizableMessage getMessageForException(NamingException ne)
  {
    LocalizableMessage msg;
    final String detailedException = ne.toString(true);
    if (isCertificateException(ne))
    {
      msg = INFO_ERROR_READING_CONFIG_LDAP_CERTIFICATE.get(ne.toString(true));
      return INFO_ERROR_READING_CONFIG_LDAP_CERTIFICATE.get(detailedException);
    }
    else if (ne instanceof AuthenticationException)
    {
      msg = ERR_CANNOT_CONNECT_TO_LOCAL_AUTHENTICATION.get(ne.toString(true));
      return ERR_CANNOT_CONNECT_TO_LOCAL_AUTHENTICATION.get(detailedException);
    }
    else if (ne instanceof NoPermissionException)
    {
      msg = ERR_CANNOT_CONNECT_TO_LOCAL_PERMISSIONS.get(ne.toString(true));
      return ERR_CANNOT_CONNECT_TO_LOCAL_PERMISSIONS.get(detailedException);
    }
    else if (ne instanceof NamingSecurityException)
    {
      msg = ERR_CANNOT_CONNECT_TO_LOCAL_PERMISSIONS.get(ne.toString(true));
      return ERR_CANNOT_CONNECT_TO_LOCAL_PERMISSIONS.get(detailedException);
    }
    else if (ne instanceof CommunicationException)
    {
      msg = ERR_CANNOT_CONNECT_TO_LOCAL_COMMUNICATION.get(ne.toString(true));
      return ERR_CANNOT_CONNECT_TO_LOCAL_COMMUNICATION.get(detailedException);
    }
    else
    {
       msg = ERR_CANNOT_CONNECT_TO_LOCAL_GENERIC.get(ne.toString(true));
      return ERR_CANNOT_CONNECT_TO_LOCAL_GENERIC.get(detailedException);
    }
    return msg;
  }
  /**
   * Returns the path of the installation of the directory server.  Note that
   * Returns the path of the installation of the directory server. Note that
   * this method assumes that this code is being run locally.
   *
   * @return the path of the installation of the directory server.
   */
  public static String getInstallPathFromClasspath()
@@ -797,7 +866,8 @@
    String sep = System.getProperty("path.separator");
    String[] classPaths = System.getProperty("java.class.path").split(sep);
    String path = getInstallPath(classPaths);
    if (path != null) {
    if (path != null)
    {
      File f = new File(path).getAbsoluteFile();
      File librariesDir = f.getParentFile();
@@ -833,26 +903,28 @@
  }
  /**
   * Returns the path of the installation of the directory server.  Note that
   * Returns the path of the installation of the directory server. Note that
   * this method assumes that this code is being run locally.
   * @param installPath The installation path
   *
   * @param installPath
   *          The installation path
   * @return the path of the installation of the directory server.
   */
  public static String getInstancePathFromInstallPath(String installPath)
  {
    String instancePathFileName = Installation.INSTANCE_LOCATION_PATH;
    File _svcScriptPathName = new File(installPath + File.separator +
      Installation.LIBRARIES_PATH_RELATIVE + File.separator +
      "_svc-opendj.sh");
    File _svcScriptPathName = new File(
        installPath + File.separator + Installation.LIBRARIES_PATH_RELATIVE + File.separator + "_svc-opendj.sh");
    // look for /etc/opt/opendj/instance.loc
    File f = new File(instancePathFileName);
    if (!_svcScriptPathName.exists() || !f.exists()) {
    if (!_svcScriptPathName.exists() || !f.exists())
    {
      // look for <installPath>/instance.loc
      instancePathFileName = installPath + File.separator +
              Installation.INSTANCE_LOCATION_PATH_RELATIVE;
      instancePathFileName = installPath + File.separator + Installation.INSTANCE_LOCATION_PATH_RELATIVE;
      f = new File(instancePathFileName);
      if (!f.exists()) {
      if (!f.exists())
      {
        return installPath;
      }
    }
@@ -867,21 +939,19 @@
      return installPath;
    }
    // Read the first line and close the file.
    String line;
    try
    {
      line = reader.readLine();
      File instanceLoc =  new File (line.trim());
      File instanceLoc = new File(line.trim());
      if (instanceLoc.isAbsolute())
      {
        return instanceLoc.getAbsolutePath();
      }
      else
      {
        return new File(installPath + File.separator + instanceLoc.getPath())
            .getAbsolutePath();
        return new File(installPath + File.separator + instanceLoc.getPath()).getAbsolutePath();
      }
    }
    catch (Exception e)
@@ -895,11 +965,11 @@
  }
  /**
   * Returns the max size in character of a line to be displayed in the command
   * line.
   *
   * @return the max size in character of a line to be displayed in the command
   * line.
   *         line.
   */
  public static int getCommandLineMaxLineWidth()
  {
@@ -908,21 +978,22 @@
  /**
   * Puts Swing menus in the Mac OS menu bar, if using the Aqua look and feel,
   * and sets the application name that is displayed in the application menu
   * and in the dock.
   * and sets the application name that is displayed in the application menu and
   * in the dock.
   *
   * @param appName
   *          application name to display in the menu bar and the dock.
   */
  public static void setMacOSXMenuBar(LocalizableMessage appName)
  {
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name",
                       String.valueOf(appName));
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", String.valueOf(appName));
  }
  /**
   * Returns the number of entries contained in the zip file.  This is used to
   * Returns the number of entries contained in the zip file. This is used to
   * update properly the progress bar ratio.
   *
   * @return the number of entries contained in the zip file.
   */
  public static int getNumberZipEntries()
@@ -932,28 +1003,37 @@
  }
  /**
   * Creates a string consisting of the string representation of the
   * elements in the <code>list</code> separated by <code>separator</code>.
   * @param list the list to print
   * @param separator to use in separating elements
   * @param prefix prepended to each individual element in the list before
   *        adding to the returned string.
   * @param suffix appended to each individual element in the list before
   *        adding to the returned string.
   * Creates a string consisting of the string representation of the elements in
   * the <code>list</code> separated by <code>separator</code>.
   *
   * @param list
   *          the list to print
   * @param separator
   *          to use in separating elements
   * @param prefix
   *          prepended to each individual element in the list before adding to
   *          the returned string.
   * @param suffix
   *          appended to each individual element in the list before adding to
   *          the returned string.
   * @return String representing the list
   */
  public static String listToString(List<?> list, String separator,
                                    String prefix, String suffix) {
  public static String listToString(List<?> list, String separator, String prefix, String suffix)
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < list.size(); i++) {
      if (prefix != null) {
    for (int i = 0; i < list.size(); i++)
    {
      if (prefix != null)
      {
        sb.append(prefix);
      }
      sb.append(list.get(i));
      if (suffix != null) {
      if (suffix != null)
      {
        sb.append(suffix);
      }
      if (i < list.size() - 1) {
      if (i < list.size() - 1)
      {
        sb.append(separator);
      }
    }
@@ -962,69 +1042,69 @@
  /**
   * Returns the file system permissions for a file.
   * @param file the file for which we want the file permissions.
   *
   * @param file
   *          the file for which we want the file permissions.
   * @return the file system permissions for the file.
   */
  public static String getFileSystemPermissions(File file)
  {
    String name = file.getName();
    if (file.getParent().endsWith(
        File.separator + Installation.WINDOWS_BINARIES_PATH_RELATIVE) ||
        file.getParent().endsWith(
        File.separator + Installation.UNIX_BINARIES_PATH_RELATIVE)) {
      if (name.endsWith(".bat")) {
        return "644";
      }
      else {
        return "755";
      }
    } else if (name.endsWith(".sh")) {
    if (file.getParent().endsWith(File.separator + Installation.WINDOWS_BINARIES_PATH_RELATIVE)
        || file.getParent().endsWith(File.separator + Installation.UNIX_BINARIES_PATH_RELATIVE))
    {
      return name.endsWith(".bat") ? "644" : "755";
    }
    else if (name.endsWith(".sh")
          || name.endsWith(Installation.UNIX_SETUP_FILE_NAME)
          || name.endsWith(Installation.UNIX_UNINSTALL_FILE_NAME)
          || name.endsWith(Installation.UNIX_UPGRADE_FILE_NAME)
          || name.endsWith(Installation.MAC_JAVA_APP_STUB_NAME))
    {
      return "755";
    } else if (name.endsWith(Installation.UNIX_SETUP_FILE_NAME) ||
            name.endsWith(Installation.UNIX_UNINSTALL_FILE_NAME) ||
            name.endsWith(Installation.UNIX_UPGRADE_FILE_NAME)) {
      return "755";
    } else if (name.endsWith(Installation.MAC_JAVA_APP_STUB_NAME)) {
      return "755";
    } else {
    }
    else
    {
      return "644";
    }
  }
  /**
   * Inserts HTML break tags into <code>d</code> breaking it up
   * so that ideally no line is longer than <code>maxll</code>
   * assuming no single word is longer then <code>maxll</code>.
   * If the string already contains HTML tags that cause a line
   * break (e.g break and closing list item tags) they are
   * respected by this method when calculating where to place
   * new breaks to control the maximum line length.
   * Inserts HTML break tags into <code>d</code> breaking it up so that ideally
   * no line is longer than <code>maxll</code> assuming no single word is longer
   * then <code>maxll</code>. If the string already contains HTML tags that
   * cause a line break (e.g break and closing list item tags) they are
   * respected by this method when calculating where to place new breaks to
   * control the maximum line length.
   *
   * @param cs String to break
   * @param maxll int maximum line length
   * @return String representing <code>d</code> with HTML break
   *         tags inserted
   * @param cs
   *          String to break
   * @param maxll
   *          int maximum line length
   * @return String representing <code>d</code> with HTML break tags inserted
   */
  public static String breakHtmlString(CharSequence cs, int maxll) {
    if (cs != null) {
  public static String breakHtmlString(CharSequence cs, int maxll)
  {
    if (cs != null)
    {
      String d = cs.toString();
      int len = d.length();
      if (len <= 0)
      {
        return d;
      }
      if (len > maxll) {
      if (len > maxll)
      {
        // First see if there are any tags that would cause a
        // natural break in the line.  If so start line break
        // point evaluation from that point.
        for (String tag : Constants.BREAKING_TAGS) {
        for (String tag : Constants.BREAKING_TAGS)
        {
          int p = d.lastIndexOf(tag, maxll);
          if (p > 0 && p < len) {
            return d.substring(0, p + tag.length()) +
                   breakHtmlString(
                           d.substring(p + tag.length()),
                           maxll);
          if (p > 0 && p < len)
          {
            return d.substring(0, p + tag.length()) + breakHtmlString(d.substring(p + tag.length()), maxll);
          }
        }
@@ -1034,57 +1114,73 @@
        // use the first space encountered after the max line
        // length.
        int p = d.lastIndexOf(' ', maxll);
        if (p <= 0) {
        if (p <= 0)
        {
          p = d.indexOf(' ', maxll);
        }
        if (p > 0 && p < len) {
          return d.substring(0, p) +
                  Constants.HTML_LINE_BREAK +
                 breakHtmlString(d.substring(p + 1), maxll);
        } else {
        if (p > 0 && p < len)
        {
          return d.substring(0, p) + Constants.HTML_LINE_BREAK + breakHtmlString(d.substring(p + 1), maxll);
        }
        else
        {
          return d;
        }
      } else {
      }
      else
      {
        return d;
      }
    } else {
    }
    else
    {
      return null;
    }
  }
  /**
   * Converts existing HTML break tags to native line separators.
   * @param s string to convert
   *
   * @param s
   *          string to convert
   * @return converted string
   */
  public static String convertHtmlBreakToLineSeparator(String s) {
  public static String convertHtmlBreakToLineSeparator(String s)
  {
    return s.replaceAll("<br>", Constants.LINE_SEPARATOR);
  }
  /**
   * Strips any potential HTML markup from a given string.
   * @param s string to strip
   *
   * @param s
   *          string to strip
   * @return resulting string
   */
  public static String stripHtml(String s) {
    if (s != null) {
  public static String stripHtml(String s)
  {
    if (s != null)
    {
      // This is not a comprehensive solution but addresses the few tags
      // that we have in Resources.properties at the moment.
      // Note that the following might strip out more than is intended for non-tags
      // like '<your name here>' or for funky tags like '<tag attr="1 > 0">'.
      // See test class for cases that might cause problems.
      return s.replaceAll("<.*?>","");
      return s.replaceAll("<.*?>", "");
    }
    return null;
  }
  /**
   * Tests a text string to see if it contains HTML.
   * @param text String to test
   *
   * @param text
   *          String to test
   * @return true if the string contains HTML
   */
  public static boolean containsHtml(String text) {
  public static boolean containsHtml(String text)
  {
    return text != null && text.indexOf('<') != -1 && text.indexOf('>') != -1;
  }
@@ -1092,6 +1188,7 @@
  /**
   * Returns a printstream that does not write anything to standard output.
   *
   * @return a printstream that does not write anything to standard output.
   */
  public static EmptyPrintStream getEmptyPrintStream()
@@ -1105,7 +1202,9 @@
  /**
   * Returns the current time of a server in milliseconds.
   * @param ctx the connection to the server.
   *
   * @param ctx
   *          the connection to the server.
   * @return the current time of a server in milliseconds.
   */
  public static long getServerClock(InitialLdapContext ctx)
@@ -1113,10 +1212,7 @@
    long time = -1;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
    ctls.setReturningAttributes(
        new String[] {
            "currentTime"
        });
    ctls.setReturningAttributes(new String[] { "currentTime" });
    String filter = "(objectclass=*)";
    try
@@ -1128,14 +1224,13 @@
      {
        while (listeners.hasMore())
        {
          SearchResult sr = (SearchResult)listeners.next();
          SearchResult sr = (SearchResult) listeners.next();
          String v = getFirstValue(sr, "currentTime");
          TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
          SimpleDateFormat formatter =
            new SimpleDateFormat("yyyyMMddHHmmss'Z'");
          SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
          formatter.setTimeZone(utcTimeZone);
          time = formatter.parse(v).getTime();
@@ -1148,15 +1243,16 @@
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error retrieving server current time: "+t, t));
      logger.warn(LocalizableMessage.raw("Error retrieving server current time: " + t, t));
    }
    return time;
  }
  /**
   * Checks that the java version we are running is compatible with OpenDS.
   * @throws IncompatibleVersionException if the java version we are running
   * is not compatible with OpenDS.
   *
   * @throws IncompatibleVersionException
   *           if the java version we are running is not compatible with OpenDS.
   */
  public static void checkJavaVersion() throws IncompatibleVersionException
  {
@@ -1167,15 +1263,11 @@
      if (i.getVendor().equalsIgnoreCase(vendor))
      {
        // Compare versions.
        boolean versionCompatible =
          i.getVersion().compareToIgnoreCase(version) <= 0;
        boolean versionCompatible = i.getVersion().compareToIgnoreCase(version) <= 0;
        if (!versionCompatible)
        {
          String javaBin = System.getProperty("java.home")+File.separator+
          "bin"+File.separator+"java";
          throw new IncompatibleVersionException(
              ERR_INCOMPATIBLE_VERSION.get(i.getVersion(), version, javaBin),
              null);
          String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
          throw new IncompatibleVersionException(ERR_INCOMPATIBLE_VERSION.get(i.getVersion(), version, javaBin), null);
        }
      }
    }
@@ -1189,19 +1281,19 @@
      catch (Throwable t)
      {
        throw new IncompatibleVersionException(
            INFO_DOWNLOADING_ERROR_NO_SERVICE_FOUND.get(
                JNLP_SERVICE_NAME, getSetupFilename()),
            t);
            INFO_DOWNLOADING_ERROR_NO_SERVICE_FOUND.get(JNLP_SERVICE_NAME, getSetupFilename()), t);
      }
    }
  }
  /**
   * Basic method to know if the host is local or not.  This is only used to
   * know if we can perform a port check or not.
   * @param host the host to analyze.
   * Basic method to know if the host is local or not. This is only used to know
   * if we can perform a port check or not.
   *
   * @param host
   *          the host to analyze.
   * @return <CODE>true</CODE> if it is the local host and <CODE>false</CODE>
   * otherwise.
   *         otherwise.
   */
  public static boolean isLocalHost(String host)
  {
@@ -1214,8 +1306,10 @@
    {
      InetAddress localAddress = InetAddress.getLocalHost();
      InetAddress[] addresses = InetAddress.getAllByName(host);
      for (InetAddress address : addresses) {
        if (localAddress.equals(address)) {
      for (InetAddress address : addresses)
      {
        if (localAddress.equals(address))
        {
          return true;
        }
      }
@@ -1281,7 +1375,8 @@
  public static String getHtml(String text)
  {
    StringBuilder buffer = new StringBuilder();
    if (text != null) {
    if (text != null)
    {
      text = text.replaceAll("\r\n", "\n");
      String[] lines = text.split("[\n\r\u0085\u2028\u2029]");
      for (int i = 0; i < lines.length; i++)
@@ -1297,18 +1392,22 @@
  }
  /**
   * Tries to find a customized object in the customization class.  If the
   * customization class does not exist or it does not contain the field
   * as the specified type of the object, returns the default value.
   * @param <T> the type of the customized object.
   * @param fieldName the name of the field representing an object in the
   * customization class.
   * @param defaultValue the default value.
   * @param valueClass the class of the parametrized value.
   * Tries to find a customized object in the customization class. If the
   * customization class does not exist or it does not contain the field as the
   * specified type of the object, returns the default value.
   *
   * @param <T>
   *          the type of the customized object.
   * @param fieldName
   *          the name of the field representing an object in the customization
   *          class.
   * @param defaultValue
   *          the default value.
   * @param valueClass
   *          the class of the parametrized value.
   * @return the customized object.
   */
  public static <T> T getCustomizedObject(String fieldName,
      T defaultValue, Class<T> valueClass)
  public static <T> T getCustomizedObject(String fieldName, T defaultValue, Class<T> valueClass)
  {
    T value = defaultValue;
    if (!isWebStart())
@@ -1330,9 +1429,13 @@
  /**
   * Adds word break tags to the provided html string.
   * @param htmlString the string.
   * @param from the first index to start the spacing from.
   * @param spacing the minimal spacing between word breaks.
   *
   * @param htmlString
   *          the string.
   * @param from
   *          the first index to start the spacing from.
   * @param spacing
   *          the minimal spacing between word breaks.
   * @return a string containing word breaks.
   */
  public static String addWordBreaks(String htmlString, int from, int spacing)
@@ -1341,7 +1444,7 @@
    boolean insideTag = false;
    int totalAddedChars = 0;
    int addedChars = 0;
    for (int i = 0 ; i<htmlString.length(); i++)
    for (int i = 0; i < htmlString.length(); i++)
    {
      char c = htmlString.charAt(i);
      sb.append(c);
@@ -1355,10 +1458,10 @@
      }
      if (!insideTag && c != '>')
      {
        addedChars ++;
        totalAddedChars ++;
        addedChars++;
        totalAddedChars++;
      }
      if ((addedChars > spacing) && (totalAddedChars > from) && !insideTag)
      if (addedChars > spacing && totalAddedChars > from && !insideTag)
      {
        sb.append("<wbr>");
        addedChars = 0;
@@ -1367,8 +1470,6 @@
    return sb.toString();
  }
  /**
   * Returns the localized string describing the DataOptions chosen by the user.
   *
@@ -1384,9 +1485,10 @@
    final SuffixesToReplicateOptions suf = userInstallData.getSuffixesToReplicateOptions();
    final String backendType = userInstallData.getBackendType().getUserFriendlyName().toString();
    boolean createSuffix = repl.getType() == DataReplicationOptions.Type.FIRST_IN_TOPOLOGY
        || repl.getType() == DataReplicationOptions.Type.STANDALONE
        || suf.getType() == SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
    boolean createSuffix =
        repl.getType() == DataReplicationOptions.Type.FIRST_IN_TOPOLOGY
            || repl.getType() == DataReplicationOptions.Type.STANDALONE
            || suf.getType() == SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
    if (createSuffix)
    {
@@ -1421,8 +1523,9 @@
      }
      else if (options.getBaseDns().size() > 1)
      {
        msg = INFO_REVIEW_CREATE_SUFFIX.get(
            backendType, joinAsString(Constants.LINE_SEPARATOR, options.getBaseDns()), arg2);
        msg =
            INFO_REVIEW_CREATE_SUFFIX.get(backendType, joinAsString(Constants.LINE_SEPARATOR, options.getBaseDns()),
                arg2);
      }
      else
      {
@@ -1446,24 +1549,23 @@
    return msg.toString();
  }
  /**
   * Returns a localized String representation of the provided SecurityOptions
   * object.
   * @param ops the SecurityOptions object from which we want to obtain the
   * String representation.
   * @param html whether the resulting String must be in HTML or not.
   *
   * @param ops
   *          the SecurityOptions object from which we want to obtain the String
   *          representation.
   * @param html
   *          whether the resulting String must be in HTML or not.
   * @return a localized String representation of the provided SecurityOptions
   * object.
   *         object.
   */
  public static String getSecurityOptionsString(SecurityOptions ops,
      boolean html)
  public static String getSecurityOptionsString(SecurityOptions ops, boolean html)
  {
    StringBuilder buf = new StringBuilder();
    if (ops.getCertificateType() ==
      SecurityOptions.CertificateType.NO_CERTIFICATE)
    if (ops.getCertificateType() == SecurityOptions.CertificateType.NO_CERTIFICATE)
    {
      buf.append(INFO_NO_SECURITY.get());
    }
@@ -1520,16 +1622,14 @@
        break;
      default:
        throw new IllegalStateException("Unknown certificate options type: "+
            ops.getCertificateType());
        throw new IllegalStateException("Unknown certificate options type: " + ops.getCertificateType());
      }
      buf.append(certMsg);
    }
    if (html)
    {
      return "<html>"+UIFactory.applyFontToHtml(buf.toString(),
          UIFactory.SECONDARY_FIELD_VALID_FONT);
      return "<html>" + UIFactory.applyFontToHtml(buf.toString(), UIFactory.SECONDARY_FIELD_VALID_FONT);
    }
    else
    {
@@ -1557,14 +1657,14 @@
    {
      sbSeparator.append("\\");
      sbSeparator.append(formatter.getLineBreak());
      for (int i=0 ; i < 10 ; i++)
      for (int i = 0; i < 10; i++)
      {
        sbSeparator.append(formatter.getSpace());
      }
    }
    String lineSeparator = sbSeparator.toString();
    for (int i=initialIndex ; i<cmd.size(); i++)
    for (int i = initialIndex; i < cmd.size(); i++)
    {
      String s = cmd.get(i);
      if (s.startsWith("-"))
@@ -1575,21 +1675,18 @@
      else
      {
        builder.append(formatter.getSpace());
        builder.append(formatter.getFormattedProgress(LocalizableMessage.raw(
            escapeCommandLineValue(s))));
        builder.append(formatter.getFormattedProgress(LocalizableMessage.raw(escapeCommandLineValue(s))));
      }
    }
    return builder.toString();
  }
  /** Chars that require special treatment when passing them to command-line. */
  private static final char[] charsToEscape = {' ', '\t', '\n', '|', ';', '<',
    '>', '(', ')', '$', '`', '\\', '"', '\''};
  /**
   * This method simply takes a value and tries to transform it (with escape or
   * '"') characters so that it can be used in a command line.
   * @param value the String to be treated.
   *
   * @param value
   *          the String to be treated.
   * @return the transformed value.
   */
  public static String escapeCommandLineValue(String value)
@@ -1597,13 +1694,13 @@
    StringBuilder b = new StringBuilder();
    if (isUnix())
    {
      for (int i=0 ; i<value.length(); i++)
      for (int i = 0; i < value.length(); i++)
      {
        char c = value.charAt(i);
        boolean charToEscapeFound = false;
        for (int j=0; j<charsToEscape.length && !charToEscapeFound; j++)
        for (int j = 0; j < CHARS_TO_ESCAPE.length && !charToEscapeFound; j++)
        {
          charToEscapeFound = c == charsToEscape[j];
          charToEscapeFound = c == CHARS_TO_ESCAPE[j];
        }
        if (charToEscapeFound)
        {
@@ -1632,7 +1729,7 @@
   */
  public static List<String> getSetupEquivalentCommandLine(final UserData userData)
  {
    List<String> cmdLine = new ArrayList<String>();
    List<String> cmdLine = new ArrayList<>();
    cmdLine.add(getInstallDir(userData) + getSetupFilename());
    cmdLine.add("--cli");
@@ -1740,7 +1837,7 @@
  private static List<String> getSecurityOptionSetupEquivalentCmdLine(final UserData userData)
  {
    final List<String> cmdLine = new ArrayList<String>();
    final List<String> cmdLine = new ArrayList<>();
    switch (userData.getSecurityOptions().getCertificateType())
    {
@@ -1824,19 +1921,19 @@
  }
  /**
   * Returns the list of equivalent command-lines that must be executed to enable or initialize
   * replication as the setup does.
   * Returns the list of equivalent command-lines that must be executed to
   * enable or initialize replication as the setup does.
   *
   * @param subcommand
   *          either {@code "enable"} or {@code "initialize"}
   * @param userData
   *          the user data.
   * @return the list of equivalent command-lines that must be executed to enable or initialize
   *         replication as the setup does.
   * @return the list of equivalent command-lines that must be executed to
   *         enable or initialize replication as the setup does.
   */
  public static List<List<String>> getDsReplicationEquivalentCommandLines(String subcommand, UserData userData)
  {
    final List<List<String>> cmdLines = new ArrayList<List<String>>();
    final List<List<String>> cmdLines = new ArrayList<>();
    final Map<ServerDescriptor, Set<String>> hmServerBaseDNs = getServerDescriptorBaseDNMap(userData);
    for (ServerDescriptor server : hmServerBaseDNs.keySet())
    {
@@ -1845,7 +1942,7 @@
    return cmdLines;
  }
  private static void addEnableCommandOptions(UserData userData, ServerDescriptor server, ArrayList<String> cmdLine)
  private static void addEnableCommandOptions(UserData userData, ServerDescriptor server, List<String> cmdLine)
  {
    DataReplicationOptions replOptions = userData.getReplicationOptions();
    cmdLine.add("--host1");
@@ -1853,23 +1950,19 @@
    cmdLine.add("--port1");
    cmdLine.add(String.valueOf(server.getEnabledAdministrationPorts().get(0)));
    AuthenticationData authData =
      userData.getReplicationOptions().getAuthenticationData();
    if (!Utils.areDnsEqual(authData.getDn(),
        ADSContext.getAdministratorDN(userData.getGlobalAdministratorUID())))
    AuthenticationData authData = userData.getReplicationOptions().getAuthenticationData();
    if (!Utils.areDnsEqual(authData.getDn(), ADSContext.getAdministratorDN(userData.getGlobalAdministratorUID())))
    {
      cmdLine.add("--bindDN1");
      cmdLine.add(authData.getDn());
      cmdLine.add("--bindPassword1");
      cmdLine.add(OBFUSCATED_VALUE);
    }
    for (ServerDescriptor s :
      userData.getRemoteWithNoReplicationPort().keySet())
    for (ServerDescriptor s : userData.getRemoteWithNoReplicationPort().keySet())
    {
      if (s.getAdminConnectorURL().equals(server.getAdminConnectorURL()))
      {
        AuthenticationData remoteRepl =
          userData.getRemoteWithNoReplicationPort().get(server);
        AuthenticationData remoteRepl = userData.getRemoteWithNoReplicationPort().get(server);
        int remoteReplicationPort = remoteRepl.getPort();
        cmdLine.add("--replicationPort1");
@@ -1901,34 +1994,35 @@
  /**
   * Returns the full path of the command-line for a given script name.
   * @param userData  the user data.
   * @param scriptBasicName the script basic name (with no extension).
   *
   * @param userData
   *          the user data.
   * @param scriptBasicName
   *          the script basic name (with no extension).
   * @return the full path of the command-line for a given script name.
   */
  private static String getCommandLinePath(UserData userData,
                                           String scriptBasicName)
  private static String getCommandLinePath(UserData userData, String scriptBasicName)
  {
    String cmdLineName;
    if (isWindows())
    {
      cmdLineName = getInstallDir(userData)
          + Installation.WINDOWS_BINARIES_PATH_RELATIVE
          + File.separatorChar
          + scriptBasicName + ".bat";
      cmdLineName =
          getInstallDir(userData) + Installation.WINDOWS_BINARIES_PATH_RELATIVE + File.separatorChar + scriptBasicName
              + ".bat";
    }
    else
    {
      cmdLineName = getInstallDir(userData)
          + Installation.UNIX_BINARIES_PATH_RELATIVE
          + File.separatorChar
          + scriptBasicName;
      cmdLineName =
          getInstallDir(userData) + Installation.UNIX_BINARIES_PATH_RELATIVE + File.separatorChar + scriptBasicName;
    }
    return cmdLineName;
  }
  private static String installDir;
  /**
   * Returns the installation directory.
   *
   * @return the installation directory.
   */
  private static String getInstallDir(UserData userData)
@@ -1961,10 +2055,10 @@
    return installDir;
  }
  private static ArrayList<String> getDsReplicationEquivalentCommandLine(
      String subcommand, UserData userData, Set<String> baseDNs, ServerDescriptor server)
  private static List<String> getDsReplicationEquivalentCommandLine(String subcommand, UserData userData,
      Set<String> baseDNs, ServerDescriptor server)
  {
    ArrayList<String> cmdLine = new ArrayList<String>();
    List<String> cmdLine = new ArrayList<>();
    String cmdName = getCommandLinePath(userData, "dsreplication");
    cmdLine.add(cmdName);
    cmdLine.add(subcommand);
@@ -1986,7 +2080,7 @@
    return cmdLine;
  }
  private static void addInitializeCommandOptions(UserData userData, ServerDescriptor server, ArrayList<String> cmdLine)
  private static void addInitializeCommandOptions(UserData userData, ServerDescriptor server, List<String> cmdLine)
  {
    cmdLine.add("--hostSource");
    cmdLine.add(server.getHostName());
@@ -1999,7 +2093,7 @@
    cmdLine.add(String.valueOf(userData.getAdminConnectorPort()));
  }
  private static void addCommonOptions(UserData userData, Set<String> baseDNs, ArrayList<String> cmdLine)
  private static void addCommonOptions(UserData userData, Set<String> baseDNs, List<String> cmdLine)
  {
    for (String baseDN : baseDNs)
    {
@@ -2017,17 +2111,17 @@
    cmdLine.add("--noPropertiesFile");
  }
  private static ArrayList<String> getBaseDNs(UserData userData)
  private static List<String> getBaseDNs(UserData userData)
  {
    ArrayList<String> baseDNs = new ArrayList<String>();
    List<String> baseDNs = new ArrayList<>();
    DataReplicationOptions repl = userData.getReplicationOptions();
    SuffixesToReplicateOptions suf = userData.getSuffixesToReplicateOptions();
    boolean createSuffix =
      repl.getType() == DataReplicationOptions.Type.FIRST_IN_TOPOLOGY ||
      repl.getType() == DataReplicationOptions.Type.STANDALONE ||
      suf.getType() == SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
        repl.getType() == DataReplicationOptions.Type.FIRST_IN_TOPOLOGY
            || repl.getType() == DataReplicationOptions.Type.STANDALONE
            || suf.getType() == SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
    if (createSuffix)
    {
@@ -2045,32 +2139,27 @@
    return baseDNs;
  }
  private static Map<ServerDescriptor, Set<String>>
  getServerDescriptorBaseDNMap(UserData userData)
  private static Map<ServerDescriptor, Set<String>> getServerDescriptorBaseDNMap(UserData userData)
  {
    Map<ServerDescriptor, Set<String>> hm =
      new HashMap<ServerDescriptor, Set<String>>();
    Map<ServerDescriptor, Set<String>> hm = new HashMap<>();
    Set<SuffixDescriptor> suffixes =
      userData.getSuffixesToReplicateOptions().getSuffixes();
    AuthenticationData authData =
      userData.getReplicationOptions().getAuthenticationData();
    String ldapURL = ConnectionUtils.getLDAPUrl(authData.getHostName(),
        authData.getPort(), authData.useSecureConnection());
    Set<SuffixDescriptor> suffixes = userData.getSuffixesToReplicateOptions().getSuffixes();
    AuthenticationData authData = userData.getReplicationOptions().getAuthenticationData();
    String ldapURL =
        ConnectionUtils.getLDAPUrl(authData.getHostName(), authData.getPort(), authData.useSecureConnection());
    for (SuffixDescriptor suffix : suffixes)
    {
      boolean found = false;
      for (ReplicaDescriptor replica : suffix.getReplicas())
      {
        if (ldapURL.equalsIgnoreCase(
            replica.getServer().getAdminConnectorURL()))
        if (ldapURL.equalsIgnoreCase(replica.getServer().getAdminConnectorURL()))
        {
          // This is the server we're configuring
          found = true;
          Set<String> baseDNs = hm.get(replica.getServer());
          if (baseDNs == null)
          {
            baseDNs = new LinkedHashSet<String>();
            baseDNs = new LinkedHashSet<>();
            hm.put(replica.getServer(), baseDNs);
          }
          baseDNs.add(suffix.getDN());
@@ -2095,7 +2184,7 @@
        ReplicaDescriptor replica = suffix.getReplicas().iterator().next();
        if (replica != null)
        {
          Set<String> baseDNs = new LinkedHashSet<String>();
          Set<String> baseDNs = new LinkedHashSet<>();
          hm.put(replica.getServer(), baseDNs);
          baseDNs.add(suffix.getDN());
        }
@@ -2115,10 +2204,10 @@
   */
  public static List<List<String>> getDsConfigReplicationEnableEquivalentCommandLines(UserData userData)
  {
    final List<List<String>> cmdLines = new ArrayList<List<String>>();
    final List<List<String>> cmdLines = new ArrayList<>();
    final String cmdName = getCommandLinePath(userData, "dsconfig");
    ArrayList<String> connectionArgs = new ArrayList<String>();
    List<String> connectionArgs = new ArrayList<>();
    connectionArgs.add("--hostName");
    connectionArgs.add(userData.getHostName());
    connectionArgs.add("--port");
@@ -2131,14 +2220,13 @@
    connectionArgs.add("--no-prompt");
    connectionArgs.add("--noPropertiesFile");
    ArrayList<String> cmdReplicationServer = new ArrayList<String>();
    List<String> cmdReplicationServer = new ArrayList<>();
    cmdReplicationServer.add(cmdName);
    cmdReplicationServer.add("create-replication-server");
    cmdReplicationServer.add("--provider-name");
    cmdReplicationServer.add("Multimaster Synchronization");
    cmdReplicationServer.add("--set");
    cmdReplicationServer.add("replication-port:"+
        userData.getReplicationOptions().getReplicationPort());
    cmdReplicationServer.add("replication-port:" + userData.getReplicationOptions().getReplicationPort());
    cmdReplicationServer.add("--set");
    cmdReplicationServer.add("replication-server-id:1");
    cmdReplicationServer.add("--type");
@@ -2149,16 +2237,16 @@
    for (String baseDN : getBaseDNs(userData))
    {
      ArrayList<String> cmdDomain = new ArrayList<String>();
      List<String> cmdDomain = new ArrayList<>();
      cmdDomain.add(cmdName);
      cmdDomain.add("create-replication-domain");
      cmdDomain.add("--provider-name");
      cmdDomain.add("Multimaster Synchronization");
      cmdDomain.add("--set");
      cmdDomain.add("base-dn:"+baseDN);
      cmdDomain.add("base-dn:" + baseDN);
      cmdDomain.add("--set");
      cmdDomain.add("replication-server:"+userData.getHostName()+":"+
          userData.getReplicationOptions().getReplicationPort());
      cmdDomain.add("replication-server:" + userData.getHostName() + ":"
          + userData.getReplicationOptions().getReplicationPort());
      cmdDomain.add("--set");
      cmdDomain.add("server-id:1");
      cmdDomain.add("--type");
@@ -2176,24 +2264,20 @@
/**
 * This class is used to avoid displaying the error message related to display
 * problems that we might have when trying to display the SplashWindow.
 *
 */
class EmptyPrintStream extends PrintStream {
class EmptyPrintStream extends PrintStream
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
  /**
   * Default constructor.
   *
   */
  /** Default constructor. */
  public EmptyPrintStream()
  {
    super(new ByteArrayOutputStream(), true);
  }
  /** {@inheritDoc} */
  @Override
  public void println(String msg)
  {
    logger.info(LocalizableMessage.raw("EmptyStream msg: "+msg));
    logger.info(LocalizableMessage.raw("EmptyStream msg: " + msg));
  }
}