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

Jean-Noel Rouvignac
24.47.2014 f298aaee8802d3eaad4ff712ed088546586388d8
More code cleanup of ReplicationCliMain
Removed utility methods that are just forwarding to other utility methods.
Removed methods that have been ported to com.forgerock.opendj.cli.Utils.


ReplicationCliMain.java:
Replaced all protected / private.
Used static imports for utility methods.
Extracted methods addBaseDNs(), createTopologyCache().

ServerLoader.java:
Extracted methods isLdapEnabled(), isLdapsEnabled(), isStartTlsEnabled()

Installer.java:
Extracted method createInitialLdapContext().
13 files modified
1400 ■■■■■ changed files
opendj3-server-dev/src/ads/org/opends/admin/ads/ServerDescriptor.java 143 ●●●● patch | view | raw | blame | history
opendj3-server-dev/src/ads/org/opends/admin/ads/util/ConnectionUtils.java 44 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/ads/org/opends/admin/ads/util/ServerLoader.java 114 ●●●● patch | view | raw | blame | history
opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java 44 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java 5 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/util/Utilities.java 113 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/guitools/org/opends/guitools/uninstaller/UninstallCliHelper.java 7 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/quicksetup/org/opends/quicksetup/installer/Installer.java 89 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/quicksetup/org/opends/quicksetup/util/ServerController.java 33 ●●●● patch | view | raw | blame | history
opendj3-server-dev/src/quicksetup/org/opends/quicksetup/util/Utils.java 76 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/server/org/opends/server/admin/client/ldap/JNDIDirContextAdaptor.java 93 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java 626 ●●●●● patch | view | raw | blame | history
opendj3-server-dev/src/server/org/opends/server/tools/status/StatusCli.java 13 ●●●● patch | view | raw | blame | history
opendj3-server-dev/src/ads/org/opends/admin/ads/ServerDescriptor.java
@@ -24,7 +24,6 @@
 *      Copyright 2007-2010 Sun Microsystems, Inc.
 *      Portion Copyright 2013-2014 ForgeRock AS.
 */
package org.opends.admin.ads;
import java.util.ArrayList;
@@ -35,28 +34,32 @@
import java.util.Map;
import java.util.Set;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NameAlreadyBoundException;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.quicksetup.Constants;
import org.opends.quicksetup.util.Utils;
import org.opends.server.schema.SchemaConstants;
import static org.opends.admin.ads.util.ConnectionUtils.*;
/**
 * The object of this class represent an OpenDS server.
 */
public class ServerDescriptor
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
  private static final String TRUSTSTORE_DN = "cn=ads-truststore";
  private final Map<ADSContext.ServerProperty, Object> adsProperties =
    new HashMap<ADSContext.ServerProperty, Object>();
  private final Set<ReplicaDescriptor> replicas =
@@ -65,103 +68,61 @@
    new HashMap<ServerProperty, Object>();
  private TopologyCacheException lastException;
  private static final String TRUSTSTORE_DN = "cn=ads-truststore";
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
  /**
   * Enumeration containing the different server properties that we can keep in
   * the ServerProperty object.
   */
  public enum ServerProperty
  {
    /**
     * The associated value is a String.
     */
    /** The associated value is a String. */
    HOST_NAME,
    /**
     * The associated value is an ArrayList of Integer.
     */
    /** The associated value is an ArrayList of Integer. */
    LDAP_PORT,
    /**
     * The associated value is an ArrayList of Integer.
     */
    /** The associated value is an ArrayList of Integer. */
    LDAPS_PORT,
    /**
     * The associated value is an Integer.
     */
    /** The associated value is an Integer. */
    ADMIN_PORT,
    /**
     * The associated value is an ArrayList of Boolean.
     */
    /** The associated value is an ArrayList of Boolean. */
    LDAP_ENABLED,
    /**
     * The associated value is an ArrayList of Boolean.
     */
    /** The associated value is an ArrayList of Boolean. */
    LDAPS_ENABLED,
    /**
     * The associated value is an ArrayList of Boolean.
     */
    /** The associated value is an ArrayList of Boolean. */
    ADMIN_ENABLED,
    /**
     * The associated value is an ArrayList of Boolean.
     */
    /** The associated value is an ArrayList of Boolean. */
    STARTTLS_ENABLED,
    /**
     * The associated value is an ArrayList of Integer.
     */
    /** The associated value is an ArrayList of Integer. */
    JMX_PORT,
    /**
     * The associated value is an ArrayList of Integer.
     */
    /** The associated value is an ArrayList of Integer. */
    JMXS_PORT,
    /**
     * The associated value is an ArrayList of Boolean.
     */
    /** The associated value is an ArrayList of Boolean. */
    JMX_ENABLED,
    /**
     * The associated value is an ArrayList of Boolean.
     */
    /** The associated value is an ArrayList of Boolean. */
    JMXS_ENABLED,
    /**
     * The associated value is an Integer.
     */
    /** The associated value is an Integer. */
    REPLICATION_SERVER_PORT,
    /**
     * The associated value is a Boolean.
     */
    /** The associated value is a Boolean. */
    IS_REPLICATION_SERVER,
    /**
     * The associated value is a Boolean.
     */
    /** The associated value is a Boolean. */
    IS_REPLICATION_ENABLED,
    /**
     * The associated value is a Boolean.
     */
    /** The associated value is a Boolean. */
    IS_REPLICATION_SECURE,
    /**
     * List of servers specified in the Replication Server configuration.
     * This is a Set of String.
     */
    EXTERNAL_REPLICATION_SERVERS,
    /**
     * The associated value is an Integer.
     */
    /** The associated value is an Integer. */
    REPLICATION_SERVER_ID,
    /**
     * The instance key-pair public-key certificate. The associated value is a
     * byte[] (ds-cfg-public-key-certificate;binary).
     */
    INSTANCE_PUBLIC_KEY_CERTIFICATE,
    /**
     * The schema generation ID.
     */
    /** The schema generation ID. */
    SCHEMA_GENERATION_ID
  }
  /**
   * Default constructor.
   */
  /** Default constructor. */
  protected ServerDescriptor()
  {
  }
@@ -366,7 +327,7 @@
    }
    if (port != -1)
    {
      ldapUrl = ConnectionUtils.getLDAPUrl(host, port, false);
      ldapUrl = getLDAPUrl(host, port, false);
    }
    return ldapUrl;
  }
@@ -403,7 +364,7 @@
    }
    if (port != -1)
    {
      ldapsUrl = ConnectionUtils.getLDAPUrl(host, port, true);
      ldapsUrl = getLDAPUrl(host, port, true);
    }
    return ldapsUrl;
  }
@@ -440,7 +401,7 @@
    }
    if (port != -1)
    {
      adminConnectorUrl = ConnectionUtils.getLDAPUrl(host, port, true);
      adminConnectorUrl = getLDAPUrl(host, port, true);
    }
    return adminConnectorUrl;
  }
@@ -782,14 +743,13 @@
  {
    ServerDescriptor desc = new ServerDescriptor();
    updateLdapConfiguration(desc, ctx, filter);
    updateAdminConnectorConfiguration(desc, ctx, filter);
    updateJmxConfiguration(desc, ctx, filter);
    updateLdapConfiguration(desc, ctx);
    updateAdminConnectorConfiguration(desc, ctx);
    updateJmxConfiguration(desc, ctx);
    updateReplicas(desc, ctx, filter);
    updateReplication(desc, ctx, filter);
    updatePublicKeyCertificate(desc, ctx, filter);
    updateMiscellaneous(desc, ctx, filter);
    updatePublicKeyCertificate(desc, ctx);
    updateMiscellaneous(desc, ctx);
    desc.serverProperties.put(ServerProperty.HOST_NAME,
        ConnectionUtils.getHostName(ctx));
@@ -797,8 +757,7 @@
    return desc;
  }
  private static void updateLdapConfiguration(ServerDescriptor desc,
      InitialLdapContext ctx, TopologyCacheFilter cacheFilter)
  private static void updateLdapConfiguration(ServerDescriptor desc, InitialLdapContext ctx)
  throws NamingException
  {
    SearchControls ctls = new SearchControls();
@@ -865,8 +824,7 @@
    }
  }
  private static void updateAdminConnectorConfiguration(ServerDescriptor desc,
      InitialLdapContext ctx, TopologyCacheFilter cacheFilter)
  private static void updateAdminConnectorConfiguration(ServerDescriptor desc, InitialLdapContext ctx)
  throws NamingException
  {
    SearchControls ctls = new SearchControls();
@@ -911,9 +869,7 @@
    }
  }
  private static void updateJmxConfiguration(ServerDescriptor desc,
      InitialLdapContext ctx, TopologyCacheFilter cacheFilter)
  throws NamingException
  private static void updateJmxConfiguration(ServerDescriptor desc, InitialLdapContext ctx) throws NamingException
  {
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
@@ -1288,8 +1244,7 @@
   @throws NamingException if unable to retrieve certificate from bound
   instance.
   */
  private static void updatePublicKeyCertificate(ServerDescriptor desc,
      InitialLdapContext ctx, TopologyCacheFilter filter) throws NamingException
  private static void updatePublicKeyCertificate(ServerDescriptor desc, InitialLdapContext ctx) throws NamingException
  {
    /* TODO: this DN is declared in some core constants file. Create a constants
       file for the installer and import it into the core. */
@@ -1333,9 +1288,7 @@
    }
  }
  private static void updateMiscellaneous(ServerDescriptor desc,
      InitialLdapContext ctx, TopologyCacheFilter cacheFilter)
  throws NamingException
  private static void updateMiscellaneous(ServerDescriptor desc, InitialLdapContext ctx) throws NamingException
  {
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
@@ -1494,22 +1447,6 @@
    return v;
  }
  /*
   * The following 2 methods are convenience methods to retrieve String values
   * from an entry.
   */
  private static String getFirstValue(SearchResult entry, String attrName)
  throws NamingException
  {
    return ConnectionUtils.getFirstValue(entry, attrName);
  }
  private static Set<String> getValues(SearchResult entry, String attrName)
  throws NamingException
  {
    return ConnectionUtils.getValues(entry, attrName);
  }
  /**
   * An convenience method to know if the provided ID corresponds to a
   * configuration backend or not.
opendj3-server-dev/src/ads/org/opends/admin/ads/util/ConnectionUtils.java
@@ -55,6 +55,8 @@
import org.opends.server.replication.plugin.EntryHistorical;
import org.opends.server.schema.SchemaConstants;
import com.forgerock.opendj.cli.Utils;
/**
 * Class providing some utilities to create LDAP connections using JNDI and
 * to manage entries retrieved using JNDI.
@@ -745,35 +747,6 @@
  }
  /**
   * Returns the String that can be used to represent a given host name in a
   * LDAP URL. This method must be used when we have IPv6 addresses (the address
   * in the LDAP URL must be enclosed with brackets).
   *
   * @param host
   *          The host name.
   * @return The String that can be used to represent a given host name in a
   *         LDAP URL.
   */
  public static String getHostNameForLdapUrl(String host)
  {
    if ((host != null) && host.indexOf(":") != -1)
    {
      // Assume an IPv6 address has been specified and adds the brackets
      // for the URL.
      host = host.trim();
      if (!host.startsWith("["))
      {
        host = "[" + host;
      }
      if (!host.endsWith("]"))
      {
        host = host + "]";
      }
    }
    return host;
  }
  /**
   * Returns the LDAP URL for the provided parameters.
   * @param host the host name.
   * @param port the LDAP port.
@@ -782,17 +755,8 @@
   */
  public static String getLDAPUrl(String host, int port, boolean useSSL)
  {
    String ldapUrl;
    host = getHostNameForLdapUrl(host);
    if (useSSL)
    {
      ldapUrl = "ldaps://"+host+":"+port;
    }
    else
    {
      ldapUrl = "ldap://"+host+":"+port;
    }
    return ldapUrl;
    host = Utils.getHostNameForLdapUrl(host);
    return (useSSL ? "ldaps://" : "ldap://") + host + ":" + port;
  }
  /**
opendj3-server-dev/src/ads/org/opends/admin/ads/util/ServerLoader.java
@@ -24,16 +24,12 @@
 *      Copyright 2008-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2013-2014 ForgeRock AS.
 */
package org.opends.admin.ads.util;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import javax.naming.AuthenticationException;
import javax.naming.NamingException;
import javax.naming.NoPermissionException;
@@ -41,13 +37,18 @@
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.admin.ads.ADSContext;
import org.opends.admin.ads.ADSContext.ServerProperty;
import org.opends.admin.ads.ServerDescriptor;
import org.opends.admin.ads.TopologyCacheException;
import org.opends.admin.ads.TopologyCacheException.Type;
import org.opends.admin.ads.TopologyCacheFilter;
import org.opends.admin.ads.ADSContext.ServerProperty;
import static org.opends.server.util.StaticUtils.close;
import com.forgerock.opendj.cli.Utils;
import static org.opends.server.util.StaticUtils.*;
/**
 * Class used to load the configuration of a server.  Basically the code
@@ -129,9 +130,8 @@
    return lastException;
  }
  /**
   * {@inheritDoc}
   */
  /** {@inheritDoc} */
  @Override
  public void interrupt()
  {
    if (!isOver)
@@ -158,6 +158,7 @@
  /**
   * The method where we try to generate the ServerDescriptor object.
   */
  @Override
  public void run()
  {
    lastException = null;
@@ -209,20 +210,11 @@
    {
      logger.warn(LocalizableMessage.raw(
          "NamingException error reading server: "+getLastLdapUrl(), ne));
      if (ctx == null)
      {
        lastException =
            new TopologyCacheException(
                TopologyCacheException.Type.GENERIC_CREATING_CONNECTION, ne,
                trustManager, getLastLdapUrl());
      }
      else
      {
        lastException =
          new TopologyCacheException(
              TopologyCacheException.Type.GENERIC_READING_SERVER, ne,
              trustManager, getLastLdapUrl());
      }
      Type type = ctx == null
          ? TopologyCacheException.Type.GENERIC_CREATING_CONNECTION
          : TopologyCacheException.Type.GENERIC_READING_SERVER;
      lastException = new TopologyCacheException(
          type, ne, trustManager, getLastLdapUrl());
    }
    catch (Throwable t)
    {
@@ -311,15 +303,12 @@
   */
  private String getLdapUrl(Map<ServerProperty,Object> serverProperties)
  {
    String ldapUrl = null;
    Object v = serverProperties.get(ServerProperty.LDAP_ENABLED);
    boolean ldapEnabled = (v != null) && "true".equalsIgnoreCase(v.toString());
    if (ldapEnabled)
    if (isLdapEnabled(serverProperties))
    {
      ldapUrl = "ldap://"+getHostNameForLdapUrl(serverProperties)+":"+
      serverProperties.get(ServerProperty.LDAP_PORT);
      return "ldap://" + getHostNameForLdapUrl(serverProperties) + ":"
          + serverProperties.get(ServerProperty.LDAP_PORT);
    }
    return ldapUrl;
    return null;
  }
  /**
@@ -332,18 +321,12 @@
   */
  private String getStartTlsLdapUrl(Map<ServerProperty,Object> serverProperties)
  {
    String ldapUrl = null;
    Object v = serverProperties.get(ServerProperty.LDAP_ENABLED);
    boolean ldapEnabled = (v != null) && "true".equalsIgnoreCase(v.toString());
    v = serverProperties.get(ServerProperty.STARTTLS_ENABLED);
    boolean startTLSEnabled = (v != null) &&
    "true".equalsIgnoreCase(v.toString());
    if (ldapEnabled && startTLSEnabled)
    if (isLdapEnabled(serverProperties) && isStartTlsEnabled(serverProperties))
    {
      ldapUrl = "ldap://"+getHostNameForLdapUrl(serverProperties)+":"+
      serverProperties.get(ServerProperty.LDAP_PORT);
      return "ldap://" + getHostNameForLdapUrl(serverProperties) + ":"
          + serverProperties.get(ServerProperty.LDAP_PORT);
    }
    return ldapUrl;
    return null;
  }
  /**
@@ -356,15 +339,13 @@
   */
  private String getLdapsUrl(Map<ServerProperty,Object> serverProperties)
  {
    String ldapsUrl = null;
    Object v = serverProperties.get(ServerProperty.LDAPS_ENABLED);
    boolean ldapsEnabled = (v != null) && "true".equalsIgnoreCase(v.toString());
    boolean ldapsEnabled = isLdapsEnabled(serverProperties);
    if (ldapsEnabled)
    {
      ldapsUrl = "ldaps://"+getHostNameForLdapUrl(serverProperties)+":"+
      serverProperties.get(ServerProperty.LDAPS_PORT);
      return "ldaps://" + getHostNameForLdapUrl(serverProperties) + ":"
          + serverProperties.get(ServerProperty.LDAPS_PORT);
    }
    return ldapsUrl;
    return null;
  }
  /**
@@ -378,26 +359,44 @@
  private String getAdminConnectorUrl(
    Map<ServerProperty,Object> serverProperties)
  {
    String adminUrl = null;
    boolean portDefined;
    Object v = serverProperties.get(ServerProperty.ADMIN_ENABLED);
    if ((v != null) && "true".equalsIgnoreCase(String.valueOf(v)))
    if (isPropertyEnabled(serverProperties, ServerProperty.ADMIN_ENABLED))
    {
      v = serverProperties.get(ServerProperty.ADMIN_PORT);
      Object v = serverProperties.get(ServerProperty.ADMIN_PORT);
      portDefined = v != null;
    }
    else
    {
      portDefined = false;
    }
    if (portDefined)
    {
      adminUrl = "ldaps://"+getHostNameForLdapUrl(serverProperties)+":"+
      serverProperties.get(ServerProperty.ADMIN_PORT);
      return "ldaps://" + getHostNameForLdapUrl(serverProperties) + ":"
          + serverProperties.get(ServerProperty.ADMIN_PORT);
    }
    return null;
    }
    return adminUrl;
  private boolean isLdapEnabled(Map<ServerProperty, Object> serverProperties)
  {
    return isPropertyEnabled(serverProperties, ServerProperty.LDAP_ENABLED);
  }
  private boolean isLdapsEnabled(Map<ServerProperty, Object> serverProperties)
  {
    return isPropertyEnabled(serverProperties, ServerProperty.LDAPS_ENABLED);
  }
  private boolean isStartTlsEnabled(Map<ServerProperty, Object> serverProperties)
  {
    return isPropertyEnabled(serverProperties, ServerProperty.STARTTLS_ENABLED);
  }
  private boolean isPropertyEnabled(Map<ServerProperty, Object> serverProperties, ServerProperty property)
  {
    Object v = serverProperties.get(property);
    return v != null && "true".equalsIgnoreCase(v.toString());
  }
  /**
@@ -411,7 +410,7 @@
      Map<ServerProperty,Object> serverProperties)
  {
    String host = (String)serverProperties.get(ServerProperty.HOST_NAME);
    return ConnectionUtils.getHostNameForLdapUrl(host);
    return Utils.getHostNameForLdapUrl(host);
  }
  /**
@@ -422,19 +421,18 @@
   */
  private boolean isAdministratorDn()
  {
    boolean isAdministratorDn = false;
    try
    {
      LdapName theDn = new LdapName(dn);
      LdapName containerDn =
        new LdapName(ADSContext.getAdministratorContainerDN());
      isAdministratorDn = theDn.startsWith(containerDn);
      return theDn.startsWith(containerDn);
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error parsing authentication DNs.", t));
    }
    return isAdministratorDn;
    return false;
  }
  /**
opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java
@@ -27,8 +27,6 @@
package org.opends.guitools.controlpanel.datamodel;
import static com.forgerock.opendj.util.OperatingSystem.isWindows;
import java.io.File;
import java.net.InetAddress;
import java.util.Collection;
@@ -67,6 +65,11 @@
import com.forgerock.opendj.cli.CliConstants;
import static com.forgerock.opendj.cli.Utils.*;
import static com.forgerock.opendj.util.OperatingSystem.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
/**
 * This is the classes that is shared among all the different places in the
 * Control Panel.  It contains information about the server status and
@@ -248,17 +251,15 @@
        toRemove.add(i);
      }
    }
    if (!toRemove.isEmpty())
    {
      boolean returnValue = modifiedIndexes.removeAll(toRemove);
      indexModified(toRemove.iterator().next());
      return returnValue;
    }
    else
    {
      return false;
    }
  }
  /**
   * Unregisters all the modified indexes on a given backend.
@@ -566,11 +567,11 @@
          }
          else if (lastRemoteAdministrationURL != null)
          {
            ctx = Utils.createLdapsContext(lastRemoteAdministrationURL,
            ctx = createLdapsContext(lastRemoteAdministrationURL,
                lastWorkingBindDN,
                lastWorkingBindPwd,
                getConnectTimeout(), null,
                getTrustManager());
                getTrustManager(), null);
          }
        }
        catch (ConfigReadException cre)
@@ -819,7 +820,6 @@
            regenerateDescriptor();
            Thread.sleep(poolingPeriod);
          }
        }
        catch (Throwable t)
        {
@@ -944,11 +944,8 @@
      // been called).
      return localAdminConnectorURL;
    }
    else
    {
      return adminConnectorURL;
    }
  }
  /**
   * Gets the Administration Connector URL based in what is read in the local
@@ -1033,9 +1030,7 @@
            }
            else
            {
              url = sProtocol +"://"+
              ConnectionUtils.getHostNameForLdapUrl(server.getHostname())+
              ":"+port;
              url = sProtocol + "://" + getHostNameForLdapUrl(server.getHostname()) + ":" + port;
            }
          }
        }
@@ -1046,16 +1041,11 @@
            if (server.isLocal())
            {
              InetAddress address = addresses.first();
              url = sProtocol +"://"+
              ConnectionUtils.getHostNameForLdapUrl(address.getHostAddress())+
              ":"+
              port;
              url = sProtocol + "://" + getHostNameForLdapUrl(address.getHostAddress()) + ":" + port;
            }
            else
            {
              url = sProtocol +"://"+
              ConnectionUtils.getHostNameForLdapUrl(server.getHostname())+
              ":"+port;
              url = sProtocol + "://" + getHostNameForLdapUrl(server.getHostname()) + ":" + port;
            }
          }
        }
@@ -1072,8 +1062,6 @@
   * @return the Administration Connector URL.
   */
  private static String getAdminConnectorURL(ServerDescriptor server) {
    String url = null;
    ConnectionHandlerDescriptor desc = server.getAdminConnector();
    if (desc != null)
    {
@@ -1081,21 +1069,17 @@
      SortedSet<InetAddress> addresses = desc.getAddresses();
      if (addresses.size() == 0) {
        if (port > 0) {
          url = ConnectionUtils.getLDAPUrl("localhost", port, true);
          return getLDAPUrl("localhost", port, true);
        }
      } else {
        if (port > 0) {
          InetAddress address = addresses.first();
          String a = address.getHostAddress();
          url = ConnectionUtils.getLDAPUrl(a, port, true);
          return getLDAPUrl(a, port, true);
        }
      }
    }
    else
    {
      url = null;
    }
    return url;
    return null;
  }
  /**
opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java
@@ -79,6 +79,7 @@
import static com.forgerock.opendj.cli.Utils.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
@@ -583,10 +584,10 @@
            {
              usedUrl = ConnectionUtils.getLDAPUrl(hostName.getText().trim(),
                  new Integer(port.getText().trim()), true);
              ctx = Utils.createLdapsContext(usedUrl, dn.getText(),
              ctx = createLdapsContext(usedUrl, dn.getText(),
                  String.valueOf(pwd.getPassword()),
                  getInfo().getConnectTimeout(), null,
                  getInfo().getTrustManager());
                  getInfo().getTrustManager(), null);
              checkVersion(ctx);
            }
opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/util/Utilities.java
@@ -26,10 +26,6 @@
 */
package org.opends.guitools.controlpanel.util;
import static org.opends.messages.AdminToolMessages.*;
import static com.forgerock.opendj.util.OperatingSystem.isWindows;
import static com.forgerock.opendj.util.OperatingSystem.isMacOS;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
@@ -94,6 +90,9 @@
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.ldap.ByteString;
import org.opends.guitools.controlpanel.ControlPanel;
import org.opends.guitools.controlpanel.browser.IconPool;
import org.opends.guitools.controlpanel.datamodel.CategorizedComboBoxElement;
@@ -108,13 +107,8 @@
import org.opends.guitools.controlpanel.event.TextComponentFocusListener;
import org.opends.guitools.controlpanel.ui.ColorAndFontConstants;
import org.opends.guitools.controlpanel.ui.components.LabelWithHelpIcon;
import org.opends.guitools.controlpanel.ui.components.
 SelectableLabelWithHelpIcon;
import org.opends.guitools.controlpanel.ui.renderer.
 AccessibleTableHeaderRenderer;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.ldap.ByteString;
import org.opends.guitools.controlpanel.ui.components.SelectableLabelWithHelpIcon;
import org.opends.guitools.controlpanel.ui.renderer.AccessibleTableHeaderRenderer;
import org.opends.quicksetup.Installation;
import org.opends.quicksetup.ui.UIFactory;
import org.opends.quicksetup.util.Utils;
@@ -133,8 +127,12 @@
import org.opends.server.util.ServerConstants;
import org.opends.server.util.StaticUtils;
import static com.forgerock.opendj.cli.Utils.*;
import static com.forgerock.opendj.util.OperatingSystem.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.server.types.CommonSchemaElements.*;
import static com.forgerock.opendj.cli.Utils.wrapText;
/**
 * A static class that provides miscellaneous functions.
@@ -961,12 +959,7 @@
      loader = ControlPanel.class.getClassLoader();
    }
    java.net.URL imgURL = loader.getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    } else {
      System.err.println("Couldn't find file: " + path);
      return null;
    }
    return imgURL != null ? new ImageIcon(imgURL) : null;
  }
  /**
@@ -1293,14 +1286,7 @@
    {
      parent = parent.getParent();
    }
    if (parent != null)
    {
      return (JFrame)parent;
    }
    else
    {
      return null;
    }
    return parent != null ? (JFrame) parent : null;
  }
  /**
@@ -1491,17 +1477,15 @@
   */
  public static boolean areDnsEqual(String dn1, String dn2)
  {
    boolean areDnsEqual = false;
    try
    {
      LdapName name1 = new LdapName(dn1);
      LdapName name2 = new LdapName(dn2);
      areDnsEqual = name1.equals(name2);
      return name1.equals(name2);
    } catch (Exception ex)
    {
      return false;
    }
    return areDnsEqual;
  }
@@ -2328,20 +2312,17 @@
      ControlPanelInfo controlInfo, String bindDN, String pwd)
  throws NamingException, ConfigReadException
  {
    InitialLdapContext ctx;
    String usedUrl = controlInfo.getAdminConnectorURL();
    if (usedUrl == null)
    {
      throw new ConfigReadException(
          ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
    }
    ctx = Utils.createLdapsContext(usedUrl,
        bindDN, pwd, controlInfo.getConnectTimeout(), null,
        controlInfo.getTrustManager());
    /*
     * Search for the config to check that it is the directory manager.
     */
    InitialLdapContext ctx = createLdapsContext(usedUrl,
        bindDN, pwd, controlInfo.getConnectTimeout(), null,
        controlInfo.getTrustManager(), null);
    // Search for the config to check that it is the directory manager.
    checkCanReadConfig(ctx);
    return ctx;
  }
@@ -2386,9 +2367,9 @@
        throw new ConfigReadException(
            ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
      }
      ctx = Utils.createLdapsContext(usedUrl,
      ctx = createLdapsContext(usedUrl,
          bindDN, pwd, controlInfo.getConnectTimeout(), null,
          controlInfo.getTrustManager());
          controlInfo.getTrustManager(), null);
    }
    else
    {
@@ -2398,7 +2379,7 @@
        throw new ConfigReadException(
            ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
      }
      ctx = Utils.createLdapContext(usedUrl,
      ctx = createLdapContext(usedUrl,
          bindDN, pwd, controlInfo.getConnectTimeout(), null);
    }
@@ -2597,24 +2578,21 @@
  public static Object getFirstMonitoringValue(CustomSearchResult sr,
      String attrName)
  {
    Object o = null;
    if (sr != null)
    {
      List<Object> values = sr.getAttributeValues(attrName);
      if ((values != null) && (values.size() > 0))
      if (values != null && values.size() > 0)
      {
        o = values.iterator().next();
        Object o = values.iterator().next();
        try
        {
          Long l = Long.parseLong(o.toString());
          o = l;
          return Long.parseLong(o.toString());
        }
        catch (Throwable t1)
        {
          try
          {
            Double d = Double.parseDouble(o.toString());
            o = d;
            return Double.parseDouble(o.toString());
          }
          catch (Throwable t2)
          {
@@ -2622,7 +2600,7 @@
        }
      }
    }
    return o;
    return null;
  }
  /**
@@ -2634,41 +2612,37 @@
  public static String getMonitoringValue(MonitoringAttributes attr,
      CustomSearchResult monitoringEntry)
  {
    String returnValue;
    Object monitoringValue =
      Utilities.getFirstMonitoringValue(monitoringEntry,
        attr.getAttributeName());
    if (monitoringValue == null)
    {
      returnValue = NO_VALUE_SET.toString();
      return NO_VALUE_SET.toString();
    }
    else if (isNotImplemented(attr, monitoringEntry))
    {
      returnValue = NOT_IMPLEMENTED.toString();
      return NOT_IMPLEMENTED.toString();
    }
    else if (attr.isNumericDate())
    {
      if("0".equals(monitoringValue.toString()))
      {
        returnValue = NO_VALUE_SET.toString();
        return NO_VALUE_SET.toString();
      }
      else
      {
        Long l = Long.parseLong(monitoringValue.toString());
        Date date = new Date(l);
        returnValue = ConfigFromDirContext.formatter.format(date);
        return ConfigFromDirContext.formatter.format(date);
      }
    }
    else if (attr.isTime())
    {
      if("-1".equals(monitoringValue.toString()))
      {
        returnValue = NO_VALUE_SET.toString();
        return NO_VALUE_SET.toString();
      }
      else
      {
        returnValue = monitoringValue.toString();
      }
      return monitoringValue.toString();
    }
    else if (attr.isGMTDate())
    {
@@ -2676,11 +2650,11 @@
      {
        Date date = ConfigFromDirContext.utcParser.parse(
            monitoringValue.toString());
        returnValue = ConfigFromDirContext.formatter.format(date);
        return ConfigFromDirContext.formatter.format(date);
      }
      catch (Throwable t)
      {
        returnValue = monitoringValue.toString();
        return monitoringValue.toString();
      }
    }
    else if (attr.isValueInBytes())
@@ -2688,13 +2662,9 @@
      Long l = Long.parseLong(monitoringValue.toString());
      long mb = l / (1024 * 1024);
      long kbs = (l - (mb * 1024 * 1024)) / 1024;
      returnValue = INFO_CTRL_PANEL_MEMORY_VALUE.get(mb , kbs).toString();
      return INFO_CTRL_PANEL_MEMORY_VALUE.get(mb, kbs).toString();
    }
    else
    {
      returnValue = monitoringValue.toString();
    }
    return returnValue;
    return monitoringValue.toString();
  }
  /**
@@ -2708,7 +2678,6 @@
  public static boolean isNotImplemented(MonitoringAttributes attr,
      CustomSearchResult monitoringEntry)
  {
    boolean returnValue;
    Object monitoringValue = Utilities.getFirstMonitoringValue(
        monitoringEntry,
        attr.getAttributeName());
@@ -2717,18 +2686,14 @@
      try
      {
        Long.parseLong(String.valueOf(monitoringValue));
        returnValue = false;
        return false;
      }
      catch (Throwable t)
      {
        returnValue = true;
        return true;
      }
    }
    else
    {
      returnValue = false;
    }
    return returnValue;
    return false;
  }
  /**
opendj3-server-dev/src/guitools/org/opends/guitools/uninstaller/UninstallCliHelper.java
@@ -81,6 +81,7 @@
import static com.forgerock.opendj.cli.Utils.*;
import static org.forgerock.util.Utils.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
@@ -1128,9 +1129,7 @@
    String ldapUrl = ConnectionUtils.getLDAPUrl(host, port, useSSL);
    if (useSSL)
    {
      ctx =
          Utils.createLdapsContext(ldapUrl, bindDn, pwd, connectTimeout, null,
              trustManager);
      ctx = createLdapsContext(ldapUrl, bindDn, pwd, connectTimeout, null, trustManager, null);
    }
    else if (useStartTLS)
    {
@@ -1140,7 +1139,7 @@
    }
    else
    {
      ctx = Utils.createLdapContext(ldapUrl, bindDn, pwd, connectTimeout, null);
      ctx = createLdapContext(ldapUrl, bindDn, pwd, connectTimeout, null);
    }
    if (!ConnectionUtils.connectedAsAdministrativeUser(ctx))
    {
opendj3-server-dev/src/quicksetup/org/opends/quicksetup/installer/Installer.java
@@ -121,6 +121,9 @@
import static com.forgerock.opendj.cli.Utils.*;
import static org.forgerock.util.Utils.*;
import static org.opends.admin.ads.ServerDescriptor.*;
import static org.opends.admin.ads.ServerDescriptor.ServerProperty.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.quicksetup.Step.*;
import static org.opends.quicksetup.util.Utils.*;
@@ -1517,9 +1520,6 @@
      // Try to connect
      DataReplicationOptions repl = getUserData().getReplicationOptions();
      AuthenticationData auth = repl.getAuthenticationData();
      String ldapUrl = getLdapUrl(auth);
      String dn = auth.getDn();
      String pwd = auth.getPwd();
      if (isVerbose())
      {
        notifyListeners(getFormattedWithPoints(
@@ -1527,18 +1527,7 @@
      }
      try
      {
        if (auth.useSecureConnection())
        {
          ApplicationTrustManager trustManager = getTrustManager();
          trustManager.setHost(auth.getHostName());
          ctx = createLdapsContext(ldapUrl, dn, pwd,
              getConnectTimeout(), null, trustManager);
        }
        else
        {
          ctx = createLdapContext(ldapUrl, dn, pwd,
              getConnectTimeout(), null);
        }
        ctx = createInitialLdapContext(auth);
        ADSContext adsContext = new ADSContext(ctx);
        if (createdRemoteAds)
@@ -1774,8 +1763,7 @@
      }
      for (ServerDescriptor server : lastLoadedCache.getServers())
      {
        Object v = server.getServerProperties().get
        (ServerDescriptor.ServerProperty.REPLICATION_SERVER_ID);
        Object v = server.getServerProperties().get(REPLICATION_SERVER_ID);
        if (v != null)
        {
          knownReplicationServerIds.add((Integer)v);
@@ -1791,8 +1779,7 @@
        for (ReplicaDescriptor replica : suffix.getReplicas())
        {
          knownServerIds.add(replica.getReplicationId());
          Object v = replica.getServer().getServerProperties().get
          (ServerDescriptor.ServerProperty.REPLICATION_SERVER_ID);
          Object v = replica.getServer().getServerProperties().get(REPLICATION_SERVER_ID);
          if (v != null)
          {
            knownReplicationServerIds.add((Integer)v);
@@ -1903,10 +1890,8 @@
      for (ServerDescriptor server : hm.keySet())
      {
        notifyListeners(getFormattedWithPoints(
            INFO_PROGRESS_CONFIGURING_REPLICATION_REMOTE.get(
                    getHostPort(server))));
        Integer v = (Integer)server.getServerProperties().get(
            ServerDescriptor.ServerProperty.REPLICATION_SERVER_PORT);
            INFO_PROGRESS_CONFIGURING_REPLICATION_REMOTE.get(getHostPort(server))));
        Integer v = (Integer)server.getServerProperties().get(REPLICATION_SERVER_PORT);
        int replicationPort;
        boolean enableSecureReplication;
        if (v != null)
@@ -2348,7 +2333,7 @@
        filter.setSearchMonitoringInformation(false);
        filter.addBaseDNToSearch(ADSContext.getAdministrationSuffixDN());
        filter.addBaseDNToSearch(Constants.SCHEMA_DN);
        ServerDescriptor s = ServerDescriptor.createStandalone(rCtx, filter);
        ServerDescriptor s = createStandalone(rCtx, filter);
        for (ReplicaDescriptor replica : s.getReplicas())
        {
          String dn = replica.getSuffix().getDN();
@@ -2432,7 +2417,7 @@
            TopologyCacheFilter filter = new TopologyCacheFilter();
            filter.setSearchMonitoringInformation(false);
            filter.addBaseDNToSearch(dn);
            ServerDescriptor s = ServerDescriptor.createStandalone(rCtx, filter);
            ServerDescriptor s = createStandalone(rCtx, filter);
            for (ReplicaDescriptor r : s.getReplicas())
            {
              if (areDnsEqual(r.getSuffix().getDN(), dn))
@@ -2538,22 +2523,7 @@
    {
      if (isRemoteServer)
      {
        /* In case the user specified an existing topology... */
        String ldapUrl = getLdapUrl(auth);
        String dn = auth.getDn();
        String pwd = auth.getPwd();
        if (auth.useSecureConnection())
        {
          ApplicationTrustManager trustManager = getTrustManager();
          trustManager.setHost(auth.getHostName());
          remoteCtx = createLdapsContext(ldapUrl, dn, pwd,
              getConnectTimeout(), null, trustManager);
        }
        else
        {
          remoteCtx = createLdapContext(ldapUrl, dn, pwd,
              getConnectTimeout(), null);
        }
        remoteCtx = createInitialLdapContext(auth);
        adsContext = new ADSContext(remoteCtx); // adsContext owns remoteCtx
        /* Check the remote server for ADS. If it does not exist, create the
@@ -2570,8 +2540,7 @@
          TopologyCacheFilter filter = new TopologyCacheFilter();
          filter.setSearchMonitoringInformation(false);
          filter.setSearchBaseDNInformation(false);
          ServerDescriptor server
                  = ServerDescriptor.createStandalone(remoteCtx, filter);
          ServerDescriptor server = createStandalone(remoteCtx, filter);
          server.updateAdsPropertiesWithServerProperties();
          adsContext.registerServer(server.getAdsProperties());
          createdRemoteAds = true;
@@ -2606,8 +2575,7 @@
      TopologyCacheFilter filter = new TopologyCacheFilter();
      filter.setSearchMonitoringInformation(false);
      filter.setSearchBaseDNInformation(false);
      ServerDescriptor server = ServerDescriptor.createStandalone(localCtx,
          filter);
      ServerDescriptor server = createStandalone(localCtx, filter);
      server.updateAdsPropertiesWithServerProperties();
      if (0 == adsContext.registerOrUpdateServer(server.getAdsProperties())) {
        if (isRemoteServer)
@@ -2620,8 +2588,7 @@
      }
      if (isRemoteServer)
      {
        ServerDescriptor.seedAdsTrustStore(localCtx,
                                           adsContext.getTrustedCertificates());
        seedAdsTrustStore(localCtx, adsContext.getTrustedCertificates());
      }
      if (isVerbose())
      {
@@ -2695,6 +2662,22 @@
    }
  }
  private InitialLdapContext createInitialLdapContext(AuthenticationData auth) throws NamingException
  {
    String ldapUrl = getLdapUrl(auth);
    String dn = auth.getDn();
    String pwd = auth.getPwd();
    if (auth.useSecureConnection())
    {
      ApplicationTrustManager trustManager = getTrustManager();
      trustManager.setHost(auth.getHostName());
      return createLdapsContext(ldapUrl, dn, pwd,
          getConnectTimeout(), null, trustManager, null);
    }
    return createLdapContext(ldapUrl, dn, pwd, getConnectTimeout(), null);
  }
  /**
   * Tells whether we must create a suffix that we are not going to replicate
   * with other servers or not.
@@ -3479,7 +3462,7 @@
      try
      {
        ctx = createLdapsContext(ldapUrl, dn, pwd,
            getConnectTimeout(), null, trustManager);
            getConnectTimeout(), null, trustManager, null);
      }
      catch (Throwable t)
      {
@@ -3489,7 +3472,7 @@
          dn = ADSContext.getAdministratorDN(dn);
          effectiveDn[0] = dn;
          ctx = createLdapsContext(ldapUrl, dn, pwd,
              getConnectTimeout(), null, trustManager);
              getConnectTimeout(), null, trustManager, null);
        }
        else
        {
@@ -4116,8 +4099,7 @@
      type = SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
    }
    ServerDescriptor s = ServerDescriptor.createStandalone(ctx,
        new TopologyCacheFilter());
    ServerDescriptor s = createStandalone(ctx, new TopologyCacheFilter());
    Set<ReplicaDescriptor> replicas = s.getReplicas();
    for (ReplicaDescriptor replica : replicas)
    {
@@ -4225,8 +4207,7 @@
      for (ReplicaDescriptor replica : suffix.getReplicas())
      {
        ServerDescriptor server = replica.getServer();
        Object v = server.getServerProperties().get(
            ServerDescriptor.ServerProperty.IS_REPLICATION_SERVER);
        Object v = server.getServerProperties().get(IS_REPLICATION_SERVER);
        if (!Boolean.TRUE.equals(v))
        {
          AuthenticationData authData = new AuthenticationData();
@@ -4247,7 +4228,7 @@
    String dn = getUserData().getDirectoryManagerDn();
    String pwd = getUserData().getDirectoryManagerPwd();
    return createLdapsContext(ldapUrl, dn, pwd,
        getConnectTimeout(), null, null);
        getConnectTimeout(), null, null, null);
  }
  /**
opendj3-server-dev/src/quicksetup/org/opends/quicksetup/util/ServerController.java
@@ -26,15 +26,18 @@
 */
package org.opends.quicksetup.util;
import static org.opends.messages.QuickSetupMessages.*;
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.util.OperatingSystem.isWindows;
import static com.forgerock.opendj.cli.Utils.getThrowableMsg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.LocalizableMessageBuilder;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.quicksetup.*;
import org.opends.quicksetup.installer.InstallerHelper;
import org.opends.server.util.SetupUtils;
@@ -42,14 +45,12 @@
import com.forgerock.opendj.cli.CliConstants;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.Utils.*;
import static com.forgerock.opendj.util.OperatingSystem.*;
import java.util.ArrayList;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.messages.QuickSetupMessages.*;
/**
 * Class used to manipulate an OpenDS server.
@@ -467,7 +468,7 @@
              hostName = "0.0.0.0";
            }
            hostName = ConnectionUtils.getHostNameForLdapUrl(hostName);
            hostName = getHostNameForLdapUrl(hostName);
            String ldapUrl = "ldaps://"+hostName+":" + port;
            try
            {
@@ -476,10 +477,8 @@
              {
                timeout = application.getUserData().getConnectTimeout();
              }
              ctx = Utils.createLdapsContext(
                  ldapUrl,
                  userDn, userPw, timeout,
                  null, null);
              ctx = createLdapsContext(ldapUrl, userDn, userPw, timeout,
                  null, null, null);
              connected = true;
            }
            catch (NamingException ne)
opendj3-server-dev/src/quicksetup/org/opends/quicksetup/util/Utils.java
@@ -64,6 +64,7 @@
import static com.forgerock.opendj.util.OperatingSystem.*;
import static org.forgerock.util.Utils.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.server.util.DynamicConstants.*;
@@ -709,66 +710,6 @@
  }
  /**
   * Creates a clear LDAP connection and returns the corresponding LdapContext.
   * This methods uses the specified parameters to create a JNDI environment
   * hashtable and creates an InitialLdapContext instance.
   *
   * @param ldapURL
   *          the target LDAP 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
   *
   * @throws NamingException
   *           the exception thrown when instantiating InitialLdapContext
   *
   * @return the created InitialLdapContext.
   * @see javax.naming.Context
   * @see javax.naming.ldap.InitialLdapContext
   */
  public static InitialLdapContext createLdapContext(String ldapURL, String dn,
      String pwd, int timeout, Hashtable<String, String> env)
      throws NamingException
  {
    return ConnectionUtils.createLdapContext(ldapURL, dn, pwd, timeout, env);
  }
  /**
   * Creates an LDAPS connection and returns the corresponding LdapContext.
   * This method uses the TrusteSocketFactory class so that the specified
   * trust manager gets called during the SSL handshake. If trust manager is
   * null, certificates are not verified 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.
   *
   * @return the established connection with the given parameters.
   *
   * @throws NamingException the exception thrown when instantiating
   * InitialLdapContext.
   *
   * @see javax.naming.Context
   * @see javax.naming.ldap.InitialLdapContext
   * @see org.opends.admin.ads.util.TrustedSocketFactory
   */
  public static InitialLdapContext createLdapsContext(String ldapsURL,
      String dn, String pwd, int timeout, Hashtable<String, String> env,
      TrustManager trustManager) throws NamingException {
    return ConnectionUtils.createLdapsContext(ldapsURL, dn, pwd, timeout, env,
        trustManager, null);
  }
  /**
   * Creates an LDAP+StartTLS connection and returns the corresponding
   * LdapContext.
   * This method first creates an LdapContext with anonymous bind. Then it
@@ -1060,21 +1001,6 @@
  }
  /**
   * Returns the String representation of the first value of an attribute in a
   * LDAP entry.
   * @param entry the entry.
   * @param attrName the attribute name.
   * @return the String representation of the first value of an attribute in a
   * LDAP entry.
   * @throws NamingException if there is an error processing the entry.
   */
  static public String getFirstValue(SearchResult entry, String attrName)
  throws NamingException
  {
    return ConnectionUtils.getFirstValue(entry, attrName);
  }
  /**
   * 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>.
opendj3-server-dev/src/server/org/opends/server/admin/client/ldap/JNDIDirContextAdaptor.java
@@ -22,12 +22,10 @@
 *
 *
 *      Copyright 2008-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2013 ForgeRock AS
 *      Portions Copyright 2013-2014 ForgeRock AS
 */
package org.opends.server.admin.client.ldap;
import java.util.Collection;
import java.util.Hashtable;
import java.util.LinkedList;
@@ -48,14 +46,13 @@
import javax.naming.ldap.Rdn;
import org.opends.admin.ads.util.BlindTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.TrustedSocketFactory;
import org.opends.server.admin.client.AuthenticationException;
import org.opends.server.admin.client.AuthenticationNotSupportedException;
import org.opends.server.admin.client.CommunicationException;
import org.opends.server.schema.SchemaConstants;
import static com.forgerock.opendj.cli.Utils.*;
/**
 * An LDAP connection adaptor which maps LDAP requests onto an
@@ -102,29 +99,12 @@
      String name, String password) throws CommunicationException,
      AuthenticationNotSupportedException, AuthenticationException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env
        .put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    String hostname = ConnectionUtils.getHostNameForLdapUrl(host) ;
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String hostname = getHostNameForLdapUrl(host);
    env.put(Context.PROVIDER_URL, "ldap://" + hostname + ":" + port);
    env.put(Context.SECURITY_PRINCIPAL, name);
    env.put(Context.SECURITY_CREDENTIALS, password);
    DirContext ctx;
    try {
      ctx = new InitialLdapContext(env, null);
    } catch (javax.naming.CommunicationException e) {
      throw new CommunicationException(e);
    } catch (javax.naming.AuthenticationException e) {
      throw new AuthenticationException(e);
    } catch (javax.naming.AuthenticationNotSupportedException e) {
      throw new AuthenticationNotSupportedException(e);
    } catch (NamingException e) {
      // Assume some kind of communication problem.
      throw new CommunicationException(e);
    }
    return new JNDIDirContextAdaptor(ctx);
    return createJNDIDirContextAdaptor(env);
  }
  /**
@@ -153,9 +133,8 @@
      String name, String password) throws CommunicationException,
      AuthenticationNotSupportedException, AuthenticationException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    String hostname = ConnectionUtils.getHostNameForLdapUrl(host) ;
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String hostname = getHostNameForLdapUrl(host);
    env.put(Context.PROVIDER_URL, "ldaps://" + hostname + ":" + port);
    env.put(Context.SECURITY_PRINCIPAL, name);
    env.put(Context.SECURITY_CREDENTIALS, password);
@@ -164,8 +143,13 @@
    env.put(Context.SECURITY_PROTOCOL, "ssl");
    env.put("java.naming.ldap.factory.socket",
        org.opends.admin.ads.util.TrustedSocketFactory.class.getName());
    TrustedSocketFactory.setCurrentThreadTrustManager(new BlindTrustManager(),
              null);
    TrustedSocketFactory.setCurrentThreadTrustManager(new BlindTrustManager(), null);
    return createJNDIDirContextAdaptor(env);
  }
  private static JNDIDirContextAdaptor createJNDIDirContextAdaptor(Hashtable<String, Object> env)
      throws CommunicationException, AuthenticationException, AuthenticationNotSupportedException
  {
    DirContext ctx;
    try {
      ctx = new InitialLdapContext(env, null);
@@ -179,38 +163,29 @@
      // Assume some kind of communication problem.
      throw new CommunicationException(e);
    }
    return new JNDIDirContextAdaptor(ctx);
  }
  // The JNDI connection context.
  /** The JNDI connection context. */
  private final DirContext dirContext;
  // Create a new JNDI connection adaptor using the provider JNDI
  // DirContext.
  /**
   * Create a new JNDI connection adaptor using the provider JNDI
   * DirContext.
   */
  private JNDIDirContextAdaptor(DirContext dirContext) {
    this.dirContext = dirContext;
  }
  /**
   * {@inheritDoc}
   */
  /** {@inheritDoc} */
  @Override
  public void createEntry(LdapName dn, Attributes attributes)
      throws NamingException {
    dirContext.createSubcontext(dn, attributes).close();
  }
  /**
   * {@inheritDoc}
   */
  /** {@inheritDoc} */
  @Override
  public void deleteSubtree(LdapName dn) throws NamingException {
    // Delete the children first.
@@ -224,20 +199,16 @@
  /**
   * {@inheritDoc}
   */
  /** {@inheritDoc} */
  @Override
  public boolean entryExists(LdapName dn) throws NamingException {
    boolean entryExists = false;
    String filter = "(objectClass=*)";
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls
        .setReturningAttributes(new String[] { SchemaConstants.NO_ATTRIBUTES });
    controls.setReturningAttributes(new String[] { SchemaConstants.NO_ATTRIBUTES });
    try {
      NamingEnumeration<SearchResult> results = dirContext.search(dn, filter,
          controls);
      NamingEnumeration<SearchResult> results = dirContext.search(dn, filter, controls);
      try
      {
        while (results.hasMore()) {
@@ -258,9 +229,7 @@
  /**
   * {@inheritDoc}
   */
  /** {@inheritDoc} */
  @Override
  public Collection<LdapName> listEntries(LdapName dn, String filter)
      throws NamingException {
@@ -293,9 +262,7 @@
  /**
   * {@inheritDoc}
   */
  /** {@inheritDoc} */
  @Override
  public void modifyEntry(LdapName dn, Attributes mods) throws NamingException {
    ModificationItem[] modList = new ModificationItem[mods.size()];
@@ -310,9 +277,7 @@
  /**
   * {@inheritDoc}
   */
  /** {@inheritDoc} */
  @Override
  public Attributes readEntry(LdapName dn, Collection<String> attrIds)
      throws NamingException {
@@ -322,9 +287,7 @@
  /**
   * {@inheritDoc}
   */
  /** {@inheritDoc} */
  @Override
  public void unbind() {
    try {
opendj3-server-dev/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java
@@ -78,7 +78,6 @@
import org.opends.admin.ads.ADSContext.AdministratorProperty;
import org.opends.admin.ads.ADSContext.ServerProperty;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.OpendsCertificateException;
import org.opends.admin.ads.util.PreferredConnection;
import org.opends.admin.ads.util.ServerLoader;
@@ -144,7 +143,11 @@
import static com.forgerock.opendj.util.OperatingSystem.*;
import static org.forgerock.util.Utils.*;
import static org.opends.admin.ads.ServerDescriptor.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.admin.ads.util.PreferredConnection.*;
import static org.opends.admin.ads.ServerDescriptor.getReplicationServer;
import static org.opends.admin.ads.ServerDescriptor.getServerRepresentation;
import static org.opends.admin.ads.ServerDescriptor.getSuffixDisplay;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.messages.ToolMessages.INFO_TASK_TOOL_TASK_SUCESSFULL;
@@ -598,8 +601,7 @@
   *          the Logger to be used to log the error message.
   * @return the Global Administrator UID as provided by the user.
   */
  protected String askForAdministratorUID(String defaultValue,
      LocalizedLogger logger)
  private String askForAdministratorUID(String defaultValue, LocalizedLogger logger)
  {
    try
    {
@@ -619,7 +621,7 @@
   *          the Logger to be used to log the error message.
   * @return the Global Administrator password as provided by the user.
   */
  protected String askForAdministratorPwd(LocalizedLogger logger)
  private String askForAdministratorPwd(LocalizedLogger logger)
  {
    try
    {
@@ -644,8 +646,7 @@
   *          the logger where the errors will be written.
   * @return the value provided by the user.
   */
  protected int askInteger(LocalizableMessage prompt, int defaultValue,
      LocalizedLogger logger)
  private int askInteger(LocalizableMessage prompt, int defaultValue, LocalizedLogger logger)
  {
    int newInt = -1;
    while (newInt == -1)
@@ -1111,27 +1112,22 @@
      throws NamingException
  {
    InitialLdapContext ctx;
    String ldapUrl = ConnectionUtils.getLDAPUrl(host, port, useSSL);
    String ldapUrl = getLDAPUrl(host, port, useSSL);
    if (useSSL)
    {
      ctx =
          createLdapsContext(ldapUrl, bindDn, pwd, connectTimeout, null,
              trustManager);
      ctx = createLdapsContext(ldapUrl, bindDn, pwd, connectTimeout, null, trustManager, null);
    }
    else if (useStartTLS)
    {
      ctx =
          createStartTLSContext(ldapUrl, bindDn, pwd, connectTimeout,
              null, trustManager, null);
      ctx = createStartTLSContext(ldapUrl, bindDn, pwd, connectTimeout, null, trustManager, null);
    }
    else
    {
      ctx = ConnectionUtils.createLdapContext(ldapUrl, bindDn, pwd, connectTimeout, null);
      ctx = createLdapContext(ldapUrl, bindDn, pwd, connectTimeout, null);
    }
    if (!ConnectionUtils.connectedAsAdministrativeUser(ctx))
    if (!connectedAsAdministrativeUser(ctx))
    {
      throw new NoPermissionException(ERR_NOT_ADMINISTRATIVE_USER.get()
          .toString());
      throw new NoPermissionException(ERR_NOT_ADMINISTRATIVE_USER.get().toString());
    }
    return ctx;
  }
@@ -1148,7 +1144,7 @@
   * @throws ClientException
   *           if there was an error establishing the connection.
   */
  protected InitialLdapContext createInitialLdapContextInteracting(
  private InitialLdapContext createInitialLdapContextInteracting(
      LDAPConnectionConsoleInteraction ci) throws ClientException
  {
    return createInitialLdapContextInteracting(ci, isInteractive()
@@ -1157,16 +1153,15 @@
  private OpendsCertificateException getCertificateRootException(Throwable t)
  {
    OpendsCertificateException oce = null;
    while (t != null && oce == null)
    while (t != null)
    {
      t = t.getCause();
      if (t instanceof OpendsCertificateException)
      {
        oce = (OpendsCertificateException) t;
        return (OpendsCertificateException) t;
      }
    }
    return oce;
    return null;
  }
  /**
@@ -1183,13 +1178,13 @@
   * @throws ClientException
   *           if there was an error establishing the connection.
   */
  protected InitialLdapContext createInitialLdapContextInteracting(
  private InitialLdapContext createInitialLdapContextInteracting(
      LDAPConnectionConsoleInteraction ci, boolean promptForCertificate)
      throws ClientException
  {
    // Interact with the user though the console to get
    // LDAP connection information
    String hostName = ConnectionUtils.getHostNameForLdapUrl(ci.getHostName());
    String hostName = getHostNameForLdapUrl(ci.getHostName());
    Integer portNumber = ci.getPortNumber();
    String bindDN = ci.getBindDN();
    String bindPassword = ci.getBindPassword();
@@ -1205,10 +1200,8 @@
      {
        try
        {
          ctx =
              ConnectionUtils.createLdapsContext(ldapsUrl, bindDN,
                  bindPassword, ci.getConnectTimeout(), null, trustManager,
                  keyManager);
          ctx = createLdapsContext(ldapsUrl, bindDN, bindPassword, ci.getConnectTimeout(),
              null, trustManager, keyManager);
          ctx.reconnect(null);
          break;
        }
@@ -1275,8 +1268,7 @@
      {
        try
        {
          ctx =
              ConnectionUtils.createStartTLSContext(ldapUrl, bindDN,
          ctx = createStartTLSContext(ldapUrl, bindDN,
                  bindPassword, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, null,
                  trustManager, keyManager, null);
          ctx.reconnect(null);
@@ -1333,8 +1325,7 @@
      {
        try
        {
          ctx =
              ConnectionUtils.createLdapContext(ldapUrl, bindDN, bindPassword,
          ctx = createLdapContext(ldapUrl, bindDN, bindPassword,
                  CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, null);
          ctx.reconnect(null);
          break;
@@ -1543,16 +1534,14 @@
        {
          isOver = true;
          LocalizableMessage errorMsg;
          String server = ConnectionUtils.getHostPort(ctx);
          if (lastLogMsg == null)
          String server = getHostPort(ctx);
          if (lastLogMsg != null)
          {
            errorMsg = INFO_ERROR_DURING_PURGE_HISTORICAL_NO_LOG.get(
                state, server);
            errorMsg = INFO_ERROR_DURING_PURGE_HISTORICAL_LOG.get(lastLogMsg, state, server);
          }
          else
          {
            errorMsg = INFO_ERROR_DURING_PURGE_HISTORICAL_LOG.get(
                lastLogMsg, state, server);
            errorMsg = INFO_ERROR_DURING_PURGE_HISTORICAL_NO_LOG.get(state, server);
          }
          if (helper.isCompletedWithErrors(state))
@@ -2086,8 +2075,8 @@
      boolean replicationServer1Configured = repPort1 > 0;
      if (replicationServer1Configured && !configureReplicationServer1)
      {
        final LocalizableMessage msg = INFO_REPLICATION_SERVER_CONFIGURED_WARNING_PROMPT.get(
            ConnectionUtils.getHostPort(ctx1), repPort1);
        final LocalizableMessage msg =
            INFO_REPLICATION_SERVER_CONFIGURED_WARNING_PROMPT.get(getHostPort(ctx1), repPort1);
        if (!askConfirmation(msg, false))
        {
          cancelled = true;
@@ -2361,8 +2350,8 @@
      boolean replicationServer2Configured = repPort2 > 0;
      if (replicationServer2Configured && !configureReplicationServer2)
      {
        final LocalizableMessage prompt = INFO_REPLICATION_SERVER_CONFIGURED_WARNING_PROMPT.get(
            ConnectionUtils.getHostPort(ctx2), repPort2);
        final LocalizableMessage prompt =
            INFO_REPLICATION_SERVER_CONFIGURED_WARNING_PROMPT.get(getHostPort(ctx2), repPort2);
        if (!askConfirmation(prompt, false))
        {
          cancelled = true;
@@ -2713,8 +2702,7 @@
    if (disableReplicationServer && repPort < 0)
    {
      disableReplicationServer = false;
      final LocalizableMessage msg =
          INFO_REPLICATION_PROMPT_NO_REPLICATION_SERVER_TO_DISABLE.get(ConnectionUtils.getHostPort(ctx));
      final LocalizableMessage msg = INFO_REPLICATION_PROMPT_NO_REPLICATION_SERVER_TO_DISABLE.get(getHostPort(ctx));
      try
      {
        cancelled = askConfirmation(msg, false, logger);
@@ -2747,8 +2735,8 @@
        try
        {
          uData.setDisableReplicationServer(askConfirmation(
         INFO_REPLICATION_DISABLE_ALL_SUFFIXES_DISABLE_REPLICATION_SERVER.get(
             ConnectionUtils.getHostPort(ctx), repPort), true, logger));
              INFO_REPLICATION_DISABLE_ALL_SUFFIXES_DISABLE_REPLICATION_SERVER.get(getHostPort(ctx), repPort), true,
              logger));
        }
        catch (ClientException ce)
        {
@@ -2895,7 +2883,7 @@
    if (!cancelled)
    {
      // Ask for confirmation to initialize.
      String hostPortSource = ConnectionUtils.getHostPort(ctx);
      String hostPortSource = getHostPort(ctx);
      LocalizableMessage msg;
      if (initializeADS(uData.getBaseDNs()))
      {
@@ -3351,8 +3339,8 @@
    if (!cancelled)
    {
      // Ask for confirmation to initialize.
      String hostPortSource = ConnectionUtils.getHostPort(ctxSource);
      String hostPortDestination = ConnectionUtils.getHostPort(ctxDestination);
      String hostPortSource = getHostPort(ctxSource);
      String hostPortDestination = getHostPort(ctxDestination);
      LocalizableMessage msg;
      if (initializeADS(uData.getBaseDNs()))
      {
@@ -3765,10 +3753,10 @@
  {
    boolean cancelled = false;
    boolean triedWithUserProvidedAdmin = false;
    String host = ConnectionUtils.getHostName(ctx[0]);
    int port = ConnectionUtils.getPort(ctx[0]);
    boolean isSSL = ConnectionUtils.isSSL(ctx[0]);
    boolean isStartTLS = ConnectionUtils.isStartTLS(ctx[0]);
    String host = getHostName(ctx[0]);
    int port = getPort(ctx[0]);
    boolean isSSL = isSSL(ctx[0]);
    boolean isStartTLS = isStartTLS(ctx[0]);
    if (getTrustManager() == null)
    {
      // This is required when the user did  connect to the server using SSL or
@@ -3792,8 +3780,7 @@
              getTrustManager(), getConnectTimeout());
          cache.getFilter().setSearchMonitoringInformation(false);
          cache.getFilter().setSearchBaseDNInformation(false);
          cache.setPreferredConnections(
              PreferredConnection.getPreferredConnections(ctx[0]));
          cache.setPreferredConnections(getPreferredConnections(ctx[0]));
          cache.reloadTopology();
          reloadTopology = false;
@@ -3868,8 +3855,7 @@
                        getConnectTimeout());
                    cache.getFilter().setSearchMonitoringInformation(false);
                    cache.getFilter().setSearchBaseDNInformation(false);
                    cache.setPreferredConnections(
                        PreferredConnection.getPreferredConnections(ctx[0]));
                    cache.setPreferredConnections(getPreferredConnections(ctx[0]));
                    connected = true;
                  }
                  catch (Throwable t)
@@ -4303,14 +4289,12 @@
          if (!uData.configureReplicationServer1() && repPort1 > 0)
          {
            println(INFO_REPLICATION_SERVER_CONFIGURED_WARNING.get(
                ConnectionUtils.getHostPort(ctx1), repPort1));
            println(INFO_REPLICATION_SERVER_CONFIGURED_WARNING.get(getHostPort(ctx1), repPort1));
            println();
          }
          if (!uData.configureReplicationServer2() && repPort2 > 0)
          {
            println(INFO_REPLICATION_SERVER_CONFIGURED_WARNING.get(
                ConnectionUtils.getHostPort(ctx2), repPort2));
            println(INFO_REPLICATION_SERVER_CONFIGURED_WARNING.get(getHostPort(ctx2), repPort2));
            println();
          }
        }
@@ -4350,9 +4334,7 @@
          && time2 != -1
          && Math.abs(time1 - time2) > Installer.THRESHOLD_CLOCK_DIFFERENCE_WARNING * 60 * 1000)
      {
        println(INFO_WARNING_SERVERS_CLOCK_DIFFERENCE.get(
            ConnectionUtils.getHostPort(ctx1),
            ConnectionUtils.getHostPort(ctx2),
          println(INFO_WARNING_SERVERS_CLOCK_DIFFERENCE.get(getHostPort(ctx1), getHostPort(ctx2),
            Installer.THRESHOLD_CLOCK_DIFFERENCE_WARNING));
      }
      println();
@@ -4372,12 +4354,12 @@
  {
    final String host = isFirstSetOfValues ? uData.getHostName1() : uData.getHostName2();
    final int port = isFirstSetOfValues ? uData.getPort1() : uData.getPort2();
    final String bindDn = isFirstSetOfValues ? uData.getBindDn1() : uData.getBindDn2();
    final String pwd = isFirstSetOfValues ? uData.getPwd1() : uData.getPwd2();
    try
    {
      return createAdministrativeContext(
          host, port, useSSL, useStartTLS,
          isFirstSetOfValues ? uData.getBindDn1() : uData.getBindDn2(),
          isFirstSetOfValues ? uData.getPwd1() : uData.getPwd2(),
          host, port, useSSL, useStartTLS, bindDn, pwd,
          getConnectTimeout(), getTrustManager());
    }
    catch (NamingException ne)
@@ -4434,9 +4416,7 @@
              !uData.disableAll())
          {
            uData.setDisableReplicationServer(false);
            println(
                INFO_REPLICATION_WARNING_NO_REPLICATION_SERVER_TO_DISABLE.get(
                    ConnectionUtils.getHostPort(ctx)));
            println(INFO_REPLICATION_WARNING_NO_REPLICATION_SERVER_TO_DISABLE.get(getHostPort(ctx)));
            println();
          }
        }
@@ -4452,9 +4432,8 @@
        {
          // Inform the user that the replication server will not be disabled.
          // Inform also of the user of the disableReplicationServerArg
          println(
           INFO_REPLICATION_DISABLE_ALL_SUFFIXES_KEEP_REPLICATION_SERVER.get(
               ConnectionUtils.getHostPort(ctx),
          println(INFO_REPLICATION_DISABLE_ALL_SUFFIXES_KEEP_REPLICATION_SERVER.get(
               getHostPort(ctx),
               argParser.disableReplicationServerArg.getLongIdentifier(),
               argParser.disableAllArg.getLongIdentifier()));
        }
@@ -4558,9 +4537,8 @@
          try
          {
            println();
            LocalizableMessage msg = formatter.getFormattedProgress(
                INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN,
                    ConnectionUtils.getHostPort(ctxSource)));
            LocalizableMessage msg =
                formatter.getFormattedProgress(INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN, getHostPort(ctxSource)));
            print(msg);
            println();
            initializeSuffix(baseDN, ctxSource, ctxDestination, true);
@@ -4644,8 +4622,7 @@
          try
          {
            println();
            print(formatter.getFormattedProgress(
                INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN, ConnectionUtils.getHostPort(ctx))));
            print(formatter.getFormattedProgress(INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN, getHostPort(ctx))));
            println();
            initializeAllSuffix(baseDN, ctx, true);
            returnValue = SUCCESSFUL;
@@ -5344,10 +5321,7 @@
    filter.setSearchMonitoringInformation(false);
    filter.addBaseDNToSearch(ADSContext.getAdministrationSuffixDN());
    filter.addBaseDNToSearch(Constants.SCHEMA_DN);
    for (String dn : uData.getBaseDNs())
    {
      filter.addBaseDNToSearch(dn);
    }
    addBaseDNs(filter, uData.getBaseDNs());
    ServerDescriptor server1 = createStandalone(ctx1, filter);
    ServerDescriptor server2 = createStandalone(ctx2, filter);
@@ -5361,36 +5335,18 @@
      final Set<LocalizableMessage> messages = new LinkedHashSet<LocalizableMessage>();
      try
      {
        final Set<PreferredConnection> cnx =
          new LinkedHashSet<PreferredConnection>();
        cnx.addAll(PreferredConnection.getPreferredConnections(ctx1));
        cnx.addAll(PreferredConnection.getPreferredConnections(ctx2));
        if (adsCtx1.hasAdminData())
        final Set<PreferredConnection> cnx = new LinkedHashSet<PreferredConnection>();
        cnx.addAll(getPreferredConnections(ctx1));
        cnx.addAll(getPreferredConnections(ctx2));
        TopologyCache cache1 = createTopologyCache(adsCtx1, cnx, uData);
        if (cache1 != null)
        {
          TopologyCache cache = new TopologyCache(adsCtx1, getTrustManager(),
              getConnectTimeout());
          cache.setPreferredConnections(cnx);
          cache.getFilter().setSearchMonitoringInformation(false);
          for (String dn : uData.getBaseDNs())
          {
            cache.getFilter().addBaseDNToSearch(dn);
          messages.addAll(cache1.getErrorMessages());
          }
          cache.reloadTopology();
          messages.addAll(cache.getErrorMessages());
        }
        if (adsCtx2.hasAdminData())
        TopologyCache cache2 = createTopologyCache(adsCtx2, cnx, uData);
        if (cache2 != null)
        {
          TopologyCache cache = new TopologyCache(adsCtx2, getTrustManager(),
              getConnectTimeout());
          cache.setPreferredConnections(cnx);
          cache.getFilter().setSearchMonitoringInformation(false);
          for (String dn : uData.getBaseDNs())
          {
            cache.getFilter().addBaseDNToSearch(dn);
          }
          cache.reloadTopology();
          messages.addAll(cache.getErrorMessages());
          messages.addAll(cache2.getErrorMessages());
        }
      }
      catch (TopologyCacheException tce)
@@ -5665,10 +5621,8 @@
        String arg = (t instanceof OpenDsException) ?
            ((OpenDsException)t).getMessageObject().toString() : t.toString();
        throw new ReplicationCliException(
            ERR_REPLICATION_ENABLE_SEEDING_TRUSTSTORE.get(
                ConnectionUtils.getHostPort(ctxDestination),
                ConnectionUtils.getHostPort(adsCtxSource.getDirContext()),
               arg),
            ERR_REPLICATION_ENABLE_SEEDING_TRUSTSTORE.get(getHostPort(ctxDestination),
            getHostPort(adsCtxSource.getDirContext()), arg),
            ERROR_SEEDING_TRUSTORE, t);
      }
    }
@@ -5691,41 +5645,23 @@
      baseDNs.add(Constants.SCHEMA_DN);
      uData.setBaseDNs(baseDNs);
    }
    TopologyCache cache1 = null;
    TopologyCache cache2 = null;
    try
    {
      Set<PreferredConnection> cnx =
        new LinkedHashSet<PreferredConnection>();
      cnx.addAll(PreferredConnection.getPreferredConnections(ctx1));
      cnx.addAll(PreferredConnection.getPreferredConnections(ctx2));
      if (adsCtx1.hasAdminData())
      Set<PreferredConnection> cnx = new LinkedHashSet<PreferredConnection>();
      cnx.addAll(getPreferredConnections(ctx1));
      cnx.addAll(getPreferredConnections(ctx2));
      cache1 = createTopologyCache(adsCtx1, cnx, uData);
      if (cache1 != null)
      {
        cache1 = new TopologyCache(adsCtx1, getTrustManager(),
            getConnectTimeout());
        cache1.setPreferredConnections(cnx);
        cache1.getFilter().setSearchMonitoringInformation(false);
        for (String dn : uData.getBaseDNs())
        {
          cache1.getFilter().addBaseDNToSearch(dn);
        }
        cache1.reloadTopology();
        usedReplicationServerIds.addAll(getReplicationServerIds(cache1));
      }
      if (adsCtx2.hasAdminData())
      cache2 = createTopologyCache(adsCtx2, cnx, uData);
      if (cache1 != null)
      {
        cache2 = new TopologyCache(adsCtx2, getTrustManager(),
            getConnectTimeout());
        cache2.setPreferredConnections(cnx);
        cache2.getFilter().setSearchMonitoringInformation(false);
        for (String dn : uData.getBaseDNs())
        {
          cache2.getFilter().addBaseDNToSearch(dn);
        }
        cache2.reloadTopology();
        usedReplicationServerIds.addAll(getReplicationServerIds(cache2));
        usedReplicationServerIds.addAll(getReplicationServerIds(cache1));
      }
    }
    catch (ADSContextException adce)
@@ -5748,8 +5684,7 @@
    }
    else if (uData.configureReplicationServer1())
    {
      twoReplServers.add(getReplicationServer(
          ConnectionUtils.getHostName(ctx1), uData.getReplicationPort1()));
      twoReplServers.add(getReplicationServer(getHostName(ctx1), uData.getReplicationPort1()));
    }
    if (server2.isReplicationServer())
    {
@@ -5758,8 +5693,7 @@
    }
    else if (uData.configureReplicationServer2())
    {
      twoReplServers.add(getReplicationServer(
          ConnectionUtils.getHostName(ctx2), uData.getReplicationPort2()));
      twoReplServers.add(getReplicationServer(getHostName(ctx2), uData.getReplicationPort2()));
    }
    for (String baseDN : uData.getBaseDNs())
@@ -5806,7 +5740,7 @@
      catch (OpenDsException ode)
      {
        throw new ReplicationCliException(
            getMessageForReplicationServerException(ConnectionUtils.getHostPort(ctx1)),
            getMessageForReplicationServerException(getHostPort(ctx1)),
            ERROR_CONFIGURING_REPLICATIONSERVER, ode);
      }
    }
@@ -5819,7 +5753,7 @@
      catch (OpenDsException ode)
      {
        throw new ReplicationCliException(
            getMessageForReplicationServerException(ConnectionUtils.getHostPort(ctx1)),
            getMessageForReplicationServerException(getHostPort(ctx1)),
            ERROR_CONFIGURING_REPLICATIONSERVER, ode);
      }
      if (argParser.replicationPort1Arg.isPresent()
@@ -5846,7 +5780,7 @@
      catch (OpenDsException ode)
      {
        throw new ReplicationCliException(
            getMessageForReplicationServerException(ConnectionUtils.getHostPort(ctx1)),
            getMessageForReplicationServerException(getHostPort(ctx1)),
            ERROR_CONFIGURING_REPLICATIONSERVER, ode);
      }
    }
@@ -5859,7 +5793,7 @@
      catch (OpenDsException ode)
      {
        throw new ReplicationCliException(
            getMessageForReplicationServerException(ConnectionUtils.getHostPort(ctx1)),
            getMessageForReplicationServerException(getHostPort(ctx1)),
            ERROR_CONFIGURING_REPLICATIONSERVER, ode);
      }
      if (argParser.replicationPort2Arg.isPresent()
@@ -5890,7 +5824,7 @@
        }
        catch (OpenDsException ode)
        {
          LocalizableMessage msg = getMessageForEnableException(ConnectionUtils.getHostPort(ctx1), baseDN);
          LocalizableMessage msg = getMessageForEnableException(getHostPort(ctx1), baseDN);
          throw new ReplicationCliException(msg,
              ERROR_ENABLING_REPLICATION_ON_BASEDN, ode);
        }
@@ -5906,7 +5840,7 @@
        }
        catch (OpenDsException ode)
        {
          LocalizableMessage msg = getMessageForEnableException(ConnectionUtils.getHostPort(ctx2), baseDN);
          LocalizableMessage msg = getMessageForEnableException(getHostPort(ctx2), baseDN);
          throw new ReplicationCliException(msg,
              ERROR_ENABLING_REPLICATION_ON_BASEDN, ode);
        }
@@ -5934,9 +5868,7 @@
    if (adsMergeDone)
    {
      PointAdder pointAdder = new PointAdder(this);
      print(
          INFO_ENABLE_REPLICATION_INITIALIZING_ADS_ALL.get(
              ConnectionUtils.getHostPort(ctxSource)));
      print(INFO_ENABLE_REPLICATION_INITIALIZING_ADS_ALL.get(getHostPort(ctxSource)));
      pointAdder.start();
      try
      {
@@ -5955,8 +5887,7 @@
    {
      print(formatter.getFormattedWithPoints(
          INFO_ENABLE_REPLICATION_INITIALIZING_ADS.get(
              ConnectionUtils.getHostPort(ctxDestination),
              ConnectionUtils.getHostPort(ctxSource))));
              getHostPort(ctxDestination), getHostPort(ctxSource))));
      initializeSuffix(ADSContext.getAdministrationSuffixDN(), ctxSource,
          ctxDestination, false);
@@ -5980,10 +5911,8 @@
      if (adsMergeDone)
      {
        PointAdder pointAdder = new PointAdder(this);
        println(
            INFO_ENABLE_REPLICATION_INITIALIZING_SCHEMA.get(
                ConnectionUtils.getHostPort(ctxDestination),
                ConnectionUtils.getHostPort(ctxSource)));
        println(INFO_ENABLE_REPLICATION_INITIALIZING_SCHEMA.get(
            getHostPort(ctxDestination), getHostPort(ctxSource)));
        pointAdder.start();
        try
        {
@@ -5997,18 +5926,30 @@
      }
      else
      {
        print(formatter.getFormattedWithPoints(
            INFO_ENABLE_REPLICATION_INITIALIZING_SCHEMA.get(
                ConnectionUtils.getHostPort(ctxDestination),
                ConnectionUtils.getHostPort(ctxSource))));
        initializeSuffix(Constants.SCHEMA_DN, ctxSource,
          ctxDestination, false);
        print(formatter.getFormattedWithPoints(INFO_ENABLE_REPLICATION_INITIALIZING_SCHEMA.get(
            getHostPort(ctxDestination), getHostPort(ctxSource))));
        initializeSuffix(Constants.SCHEMA_DN, ctxSource, ctxDestination, false);
      }
      print(formatter.getFormattedDone());
      println();
    }
  }
  private TopologyCache createTopologyCache(ADSContext adsCtx, Set<PreferredConnection> cnx, ReplicationUserData uData)
      throws ADSContextException, TopologyCacheException
  {
    if (adsCtx.hasAdminData())
    {
      TopologyCache cache = new TopologyCache(adsCtx, getTrustManager(), getConnectTimeout());
      cache.setPreferredConnections(cnx);
      cache.getFilter().setSearchMonitoringInformation(false);
      addBaseDNs(cache.getFilter(), uData.getBaseDNs());
      cache.reloadTopology();
      return cache;
    }
    return null;
  }
  private ServerDescriptor createStandalone(InitialLdapContext ctx, TopologyCacheFilter filter)
      throws ReplicationCliException
  {
@@ -6019,7 +5960,7 @@
    catch (NamingException ne)
    {
      throw new ReplicationCliException(
          getMessageForException(ne, ConnectionUtils.getHostPort(ctx)),
          getMessageForException(ne, getHostPort(ctx)),
          ERROR_READING_CONFIGURATION, ne);
    }
  }
@@ -6040,10 +5981,7 @@
    if (!uData.disableAll())
    {
      filter.addBaseDNToSearch(ADSContext.getAdministrationSuffixDN());
      for (String dn : uData.getBaseDNs())
      {
        filter.addBaseDNToSearch(dn);
      }
      addBaseDNs(filter, uData.getBaseDNs());
    }
    ServerDescriptor server = createStandalone(ctx, filter);
@@ -6059,15 +5997,11 @@
      {
        cache = new TopologyCache(adsCtx, getTrustManager(),
            getConnectTimeout());
        cache.setPreferredConnections(
            PreferredConnection.getPreferredConnections(ctx));
        cache.setPreferredConnections(getPreferredConnections(ctx));
        cache.getFilter().setSearchMonitoringInformation(false);
        if (!uData.disableAll())
        {
          for (String dn : uData.getBaseDNs())
          {
            cache.getFilter().addBaseDNToSearch(dn);
          }
          addBaseDNs(cache.getFilter(), uData.getBaseDNs());
        }
        cache.reloadTopology();
      }
@@ -6352,7 +6286,7 @@
      }
      catch (OpenDsException ode)
      {
        LocalizableMessage msg = getMessageForDisableException(ConnectionUtils.getHostPort(ctx), baseDN);
        LocalizableMessage msg = getMessageForDisableException(getHostPort(ctx), baseDN);
        throw new ReplicationCliException(msg,
            ERROR_DISABLING_REPLICATION_ON_BASEDN, ode);
      }
@@ -6390,13 +6324,13 @@
          }
        }
      }
      String bindDn = ConnectionUtils.getBindDN(ctx);
      String pwd = ConnectionUtils.getBindPassword(ctx);
      String bindDn = getBindDN(ctx);
      String pwd = getBindPassword(ctx);
      for (ServerDescriptor s : serversToUpdate)
      {
        removeReferencesInServer(s, replicationServerHostPort, bindDn, pwd,
            baseDNsToUpdate, disableReplicationServer,
            PreferredConnection.getPreferredConnections(ctx));
            getPreferredConnections(ctx));
      }
      if (disableReplicationServer)
@@ -6458,6 +6392,14 @@
    }
  }
  private void addBaseDNs(TopologyCacheFilter filter, List<String> baseDNs)
  {
    for (String dn : baseDNs)
    {
      filter.addBaseDNToSearch(dn);
    }
  }
  /**
   * Displays the replication status of the different base DNs in the servers
   * registered in the ADS.
@@ -6475,14 +6417,9 @@
    TopologyCache cache;
    try
    {
      cache = new TopologyCache(adsCtx, getTrustManager(),
          getConnectTimeout());
      cache.setPreferredConnections(
          PreferredConnection.getPreferredConnections(ctx));
      for (String dn : uData.getBaseDNs())
      {
        cache.getFilter().addBaseDNToSearch(dn);
      }
      cache = new TopologyCache(adsCtx, getTrustManager(), getConnectTimeout());
      cache.setPreferredConnections(getPreferredConnections(ctx));
      addBaseDNs(cache.getFilter(), uData.getBaseDNs());
      cache.reloadTopology();
    }
    catch (TopologyCacheException tce)
@@ -6583,8 +6520,7 @@
      }
      if (!rServers.isEmpty())
      {
        displayStatus(rServers, uData.isScriptFriendly(),
            PreferredConnection.getPreferredConnections(ctx));
        displayStatus(rServers, uData.isScriptFriendly(), getPreferredConnections(ctx));
        somethingDisplayed = true;
      }
    }
@@ -6617,7 +6553,7 @@
      Set<ServerDescriptor> serversWithNoReplica =
        new HashSet<ServerDescriptor>();
      displayStatus(orderedReplicaLists, uData.isScriptFriendly(),
            PreferredConnection.getPreferredConnections(ctx),
            getPreferredConnections(ctx),
            cache.getServers(),
            replicasWithNoReplicationServer, serversWithNoReplica);
      somethingDisplayed = true;
@@ -6690,13 +6626,13 @@
    {
      for (ReplicaDescriptor replica : replicas)
      {
        hostPorts.add(getHostPort(replica.getServer(), cnx));
        hostPorts.add(getHostPort2(replica.getServer(), cnx));
      }
      for (String hostPort : hostPorts)
      {
        for (ReplicaDescriptor replica : replicas)
        {
          if (getHostPort(replica.getServer(), cnx).equals(hostPort))
          if (getHostPort2(replica.getServer(), cnx).equals(hostPort))
          {
            orderedReplicas.add(replica);
          }
@@ -6759,7 +6695,7 @@
      tableBuilder.appendCell(LocalizableMessage.raw(replica.getSuffix().getDN()));
      // Server port
      tableBuilder.appendCell(
          LocalizableMessage.raw(getHostPort(replica.getServer(), cnx)));
          LocalizableMessage.raw(getHostPort2(replica.getServer(), cnx)));
      // Number of entries
      int nEntries = replica.getEntries();
      if (nEntries >= 0)
@@ -6852,10 +6788,8 @@
      // Suffix DN
      tableBuilder.appendCell(EMPTY_MSG);
      // Server port
      tableBuilder.appendCell(LocalizableMessage.raw(getHostPort(server, cnx)));
      tableBuilder.appendCell(LocalizableMessage.raw(getHostPort2(server, cnx)));
      // Number of entries
      if (scriptFriendly)
      {
@@ -6959,7 +6893,7 @@
    {
      tableBuilder.startRow();
      // Server port
      tableBuilder.appendCell(LocalizableMessage.raw(getHostPort(server, cnx)));
      tableBuilder.appendCell(LocalizableMessage.raw(getHostPort2(server, cnx)));
      // Replication port
      int replicationPort = server.getReplicationServerPort();
      if (replicationPort >= 0)
@@ -7183,8 +7117,7 @@
      Set<Integer> usedReplicationServerIds) throws OpenDsException
  {
    print(formatter.getFormattedWithPoints(
        INFO_REPLICATION_ENABLE_CONFIGURING_REPLICATION_SERVER.get(
            ConnectionUtils.getHostPort(ctx))));
        INFO_REPLICATION_ENABLE_CONFIGURING_REPLICATION_SERVER.get(getHostPort(ctx))));
    ManagementContext mCtx = LDAPManagementContext.createFromContext(
        JNDIDirContextAdaptor.adapt(ctx));
@@ -7201,8 +7134,7 @@
    }
    catch (ManagedObjectNotFoundException monfe)
    {
      logger.info(LocalizableMessage.raw("Synchronization server does not exist in "+
          ConnectionUtils.getHostPort(ctx)));
      logger.info(LocalizableMessage.raw("Synchronization server does not exist in " + getHostPort(ctx)));
    }
    if (sync == null)
    {
@@ -7286,8 +7218,7 @@
      Set<String> replicationServers) throws OpenDsException
  {
    print(formatter.getFormattedWithPoints(
        INFO_REPLICATION_ENABLE_UPDATING_REPLICATION_SERVER.get(
            ConnectionUtils.getHostPort(ctx))));
        INFO_REPLICATION_ENABLE_UPDATING_REPLICATION_SERVER.get(getHostPort(ctx))));
    ManagementContext mCtx = LDAPManagementContext.createFromContext(
        JNDIDirContextAdaptor.adapt(ctx));
@@ -7367,14 +7298,12 @@
        ADSContext.getAdministrationSuffixDN()))
    {
      print(formatter.getFormattedWithPoints(
          INFO_REPLICATION_ENABLE_CONFIGURING_ADS.get(
              ConnectionUtils.getHostPort(ctx))));
          INFO_REPLICATION_ENABLE_CONFIGURING_ADS.get(getHostPort(ctx))));
    }
    else
    {
      print(formatter.getFormattedWithPoints(
          INFO_REPLICATION_ENABLE_CONFIGURING_BASEDN.get(baseDN,
              ConnectionUtils.getHostPort(ctx))));
          INFO_REPLICATION_ENABLE_CONFIGURING_BASEDN.get(baseDN, getHostPort(ctx))));
    }
    ManagementContext mCtx = LDAPManagementContext.createFromContext(
        JNDIDirContextAdaptor.adapt(ctx));
@@ -7523,13 +7452,13 @@
      }
      catch (NamingException ne)
      {
        String hostPort = getHostPort(s, cache.getPreferredConnections());
        String hostPort = getHostPort2(s, cache.getPreferredConnections());
        LocalizableMessage msg = getMessageForException(ne, hostPort);
        throw new ReplicationCliException(msg, ERROR_CONNECTING, ne);
      }
      catch (OpenDsException ode)
      {
        String hostPort = getHostPort(s, cache.getPreferredConnections());
        String hostPort = getHostPort2(s, cache.getPreferredConnections());
        LocalizableMessage msg = getMessageForEnableException(hostPort, baseDN);
        throw new ReplicationCliException(msg,
            ERROR_ENABLING_REPLICATION_ON_BASEDN, ode);
@@ -7573,8 +7502,7 @@
      TopologyCacheFilter filter = new TopologyCacheFilter();
      filter.setSearchMonitoringInformation(false);
      filter.addBaseDNToSearch(baseDN);
      ServerDescriptor source = ServerDescriptor.createStandalone(ctxSource,
          filter);
      ServerDescriptor source = ServerDescriptor.createStandalone(ctxSource, filter);
      for (ReplicaDescriptor replica : source.getReplicas())
      {
        if (areDnsEqual(replica.getSuffix().getDN(), baseDN))
@@ -7586,7 +7514,7 @@
    }
    catch (NamingException ne)
    {
      String hostPort = ConnectionUtils.getHostPort(ctxSource);
      String hostPort = getHostPort(ctxSource);
      LocalizableMessage msg = getMessageForException(ne, hostPort);
      throw new ReplicationCliException(msg, ERROR_READING_CONFIGURATION, ne);
    }
@@ -7594,8 +7522,7 @@
    if (replicationId == -1)
    {
      throw new ReplicationCliException(
          ERR_INITIALIZING_REPLICATIONID_NOT_FOUND.get(
              ConnectionUtils.getHostPort(ctxSource), baseDN),
          ERR_INITIALIZING_REPLICATIONID_NOT_FOUND.get(getHostPort(ctxSource), baseDN),
          REPLICATIONID_NOT_FOUND, null);
    }
@@ -7622,7 +7549,7 @@
      try
      {
        installer.initializeSuffix(ctxDestination, replicationId, baseDN,
            displayProgress, ConnectionUtils.getHostPort(ctxSource));
            displayProgress, getHostPort(ctxSource));
        initDone = true;
      }
      catch (PeerNotFoundException pnfe)
@@ -7824,7 +7751,7 @@
        {
          isOver = true;
          LocalizableMessage errorMsg;
          String server = ConnectionUtils.getHostPort(ctx);
          String server = getHostPort(ctx);
          if (lastLogMsg == null)
          {
            errorMsg = isPre
@@ -7899,7 +7826,7 @@
    int i = 1;
    boolean isOver = false;
    String dn = null;
    String serverDisplay = ConnectionUtils.getHostPort(ctx);
    String serverDisplay = getHostPort(ctx);
    BasicAttributes attrs = new BasicAttributes();
    Attribute oc = new BasicAttribute("objectclass");
    oc.add("top");
@@ -8188,7 +8115,7 @@
    try
    {
      ctx = loader.createContext();
      hostPort = ConnectionUtils.getHostPort(ctx);
      hostPort = getHostPort(ctx);
      ManagementContext mCtx = LDAPManagementContext.createFromContext(
          JNDIDirContextAdaptor.adapt(ctx));
      RootCfgClient root = mCtx.getRootConfiguration();
@@ -8275,7 +8202,7 @@
    }
    catch (NamingException ne)
    {
      hostPort = getHostPort(server, cnx);
      hostPort = getHostPort2(server, cnx);
      LocalizableMessage msg = getMessageForException(ne, hostPort);
      throw new ReplicationCliException(msg, ERROR_CONNECTING, ne);
    }
@@ -8312,7 +8239,7 @@
  private void deleteReplicationDomain(InitialLdapContext ctx,
      String baseDN) throws ReplicationCliException
  {
    String hostPort = ConnectionUtils.getHostPort(ctx);
    String hostPort = getHostPort(ctx);
    try
    {
      ManagementContext mCtx = LDAPManagementContext.createFromContext(
@@ -8342,8 +8269,7 @@
            if (areDnsEqual(domain.getBaseDN().toString(), baseDN))
            {
              print(formatter.getFormattedWithPoints(
                  INFO_REPLICATION_DISABLING_BASEDN.get(baseDN,
                      hostPort)));
                  INFO_REPLICATION_DISABLING_BASEDN.get(baseDN, hostPort)));
              sync.removeReplicationDomain(domainName);
              sync.commit();
@@ -8371,7 +8297,7 @@
  private void disableReplicationServer(InitialLdapContext ctx)
  throws ReplicationCliException
  {
    String hostPort = ConnectionUtils.getHostPort(ctx);
    String hostPort = getHostPort(ctx);
    try
    {
      ManagementContext mCtx = LDAPManagementContext.createFromContext(
@@ -8817,7 +8743,7 @@
   * @param cnx the preferred connections list.
   * @return the host port string representation of the provided server.
   */
  protected String getHostPort(ServerDescriptor server,
  private String getHostPort2(ServerDescriptor server,
      Collection<PreferredConnection> cnx)
  {
    String hostPort = null;
@@ -9756,8 +9682,7 @@
    Collection<ReplicaDescriptor> replicas = getReplicas(ctxDomain);
    int replicationPort = getReplicationPort(ctxOther);
    boolean isReplicationServerConfigured = replicationPort != -1;
    String replicationServer = getReplicationServer(
      ConnectionUtils.getHostName(ctxOther), replicationPort);
    String replicationServer = getReplicationServer(getHostName(ctxOther), replicationPort);
    for (ReplicaDescriptor replica : replicas)
    {
      if (!isReplicationServerConfigured)
@@ -9794,61 +9719,14 @@
  {
    int replicationPort1 = getReplicationPort(ctx1);
    boolean isReplicationServer1Configured = replicationPort1 != -1;
    String replicationServer1 = getReplicationServer(
      ConnectionUtils.getHostName(ctx1), replicationPort1);
    String replicationServer1 = getReplicationServer(getHostName(ctx1), replicationPort1);
    int replicationPort2 = getReplicationPort(ctx2);
    boolean isReplicationServer2Configured = replicationPort2 != -1;
    String replicationServer2 = getReplicationServer(
      ConnectionUtils.getHostName(ctx2), replicationPort2);
    String replicationServer2 = getReplicationServer(getHostName(ctx2), replicationPort2);
    TopologyCache cache1 = null;
    TopologyCache cache2 = null;
    if (isReplicationServer1Configured)
    {
      try
      {
        ADSContext adsContext = new ADSContext(ctx1);
        if (adsContext.hasAdminData())
        {
          cache1 = new TopologyCache(adsContext, getTrustManager(),
              getConnectTimeout());
          cache1.getFilter().setSearchMonitoringInformation(false);
          cache1.setPreferredConnections(
              PreferredConnection.getPreferredConnections(ctx1));
          cache1.reloadTopology();
        }
      }
      catch (Throwable t)
      {
        logger.warn(LocalizableMessage.raw("Error loading topology cache in "+
            ConnectionUtils.getLdapUrl(ctx1)+": "+t, t));
      }
    }
    if (isReplicationServer2Configured)
    {
      try
      {
        ADSContext adsContext = new ADSContext(ctx2);
        if (adsContext.hasAdminData())
        {
          cache2 = new TopologyCache(adsContext, getTrustManager(),
              getConnectTimeout());
          cache2.getFilter().setSearchMonitoringInformation(false);
          cache2.setPreferredConnections(
              PreferredConnection.getPreferredConnections(ctx2));
          cache2.reloadTopology();
        }
      }
      catch (Throwable t)
      {
        logger.warn(LocalizableMessage.raw("Error loading topology cache in "+
            ConnectionUtils.getLdapUrl(ctx2)+": "+t, t));
      }
    }
    TopologyCache cache1 = isReplicationServer1Configured ? createTopologyCache(ctx1) : null;
    TopologyCache cache2 = isReplicationServer2Configured ? createTopologyCache(ctx2) : null;
    if (cache1 != null && cache2 != null)
    {
      updateAvailableAndReplicatedSuffixesForNoDomainOneSense(cache1, cache2,
@@ -9868,6 +9746,27 @@
    }
  }
  private TopologyCache createTopologyCache(InitialLdapContext ctx)
  {
    try
    {
      ADSContext adsContext = new ADSContext(ctx);
      if (adsContext.hasAdminData())
      {
        TopologyCache cache = new TopologyCache(adsContext, getTrustManager(), getConnectTimeout());
        cache.getFilter().setSearchMonitoringInformation(false);
        cache.setPreferredConnections(getPreferredConnections(ctx));
        cache.reloadTopology();
        return cache;
      }
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error loading topology cache in " + getLdapUrl(ctx) + ": " + t, t));
    }
    return null;
  }
  private void addAllAvailableSuffixes(Collection<String> availableSuffixes,
      Set<SuffixDescriptor> suffixes, String rsToFind)
  {
@@ -9946,47 +9845,8 @@
      return;
    }
    Set<SuffixDescriptor> suffixes = new HashSet<SuffixDescriptor>();
    try
    {
      if (adsCtx1.hasAdminData())
      {
        TopologyCache cache = new TopologyCache(adsCtx1,
            getTrustManager(), getConnectTimeout());
        cache.getFilter().setSearchMonitoringInformation(false);
        for (String dn : uData.getBaseDNs())
        {
          cache.getFilter().addBaseDNToSearch(dn);
        }
        cache.reloadTopology();
        suffixes.addAll(cache.getSuffixes());
      }
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error loading topology cache from "+
          ConnectionUtils.getHostPort(adsCtx1.getDirContext())+": "+t, t));
    }
    try
    {
      if (adsCtx2.hasAdminData())
      {
        TopologyCache cache = new TopologyCache(adsCtx2,
            getTrustManager(), getConnectTimeout());
        cache.getFilter().setSearchMonitoringInformation(false);
        cache.reloadTopology();
        for (String dn : uData.getBaseDNs())
        {
          cache.getFilter().addBaseDNToSearch(dn);
        }
        suffixes.addAll(cache.getSuffixes());
      }
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error loading topology cache from "+
          ConnectionUtils.getHostPort(adsCtx2.getDirContext())+": "+t, t));
    }
    createTopologyCache(adsCtx1, uData, suffixes);
    createTopologyCache(adsCtx2, uData, suffixes);
    int repPort1 = getReplicationPort(adsCtx1.getDirContext());
    String repServer1 =  getReplicationServer(uData.getHostName1(), repPort1);
@@ -10035,6 +9895,26 @@
    }
  }
  private void createTopologyCache(ADSContext adsCtx, ReplicationUserData uData, Set<SuffixDescriptor> suffixes)
  {
    try
    {
      if (adsCtx.hasAdminData())
      {
        TopologyCache cache = new TopologyCache(adsCtx, getTrustManager(), getConnectTimeout());
        cache.getFilter().setSearchMonitoringInformation(false);
        addBaseDNs(cache.getFilter(), uData.getBaseDNs());
        cache.reloadTopology();
        suffixes.addAll(cache.getSuffixes());
      }
    }
    catch (Throwable t)
    {
      String msg = "Error loading topology cache from " + getHostPort(adsCtx.getDirContext()) + ": " + t;
      logger.warn(LocalizableMessage.raw(msg, t));
    }
  }
  /**
   * Merge the contents of the two registries but only does it partially.
   * Only one of the two ADSContext will be updated (in terms of data in
@@ -10057,46 +9937,11 @@
    PointAdder pointAdder = new PointAdder(this);
    try
    {
      Set<PreferredConnection> cnx =
        new LinkedHashSet<PreferredConnection>();
      cnx.addAll(PreferredConnection.getPreferredConnections(
          adsCtx1.getDirContext()));
      cnx.addAll(PreferredConnection.getPreferredConnections(
          adsCtx2.getDirContext()));
      // Check that there are no errors.  We do not allow to do the merge with
      // errors.
      TopologyCache cache1 = new TopologyCache(adsCtx1, getTrustManager(),
          getConnectTimeout());
      cache1.setPreferredConnections(cnx);
      cache1.getFilter().setSearchBaseDNInformation(false);
      try
      {
        cache1.reloadTopology();
      }
      catch (TopologyCacheException te)
      {
        logger.error(LocalizableMessage.raw("Error reading topology cache of "+
            ConnectionUtils.getHostPort(adsCtx1.getDirContext())+ " "+te, te));
        throw new ReplicationCliException(
            ERR_REPLICATION_READING_ADS.get(te.getMessageObject()),
            ERROR_UPDATING_ADS, te);
      }
      TopologyCache cache2 = new TopologyCache(adsCtx2, getTrustManager(),
          getConnectTimeout());
      cache2.setPreferredConnections(cnx);
      cache2.getFilter().setSearchBaseDNInformation(false);
      try
      {
        cache2.reloadTopology();
      }
      catch (TopologyCacheException te)
      {
        logger.error(LocalizableMessage.raw("Error reading topology cache of "+
            ConnectionUtils.getHostPort(adsCtx2.getDirContext())+ " "+te, te));
        throw new ReplicationCliException(
            ERR_REPLICATION_READING_ADS.get(te.getMessageObject()),
            ERROR_UPDATING_ADS, te);
      }
      Set<PreferredConnection> cnx = new LinkedHashSet<PreferredConnection>();
      cnx.addAll(getPreferredConnections(adsCtx1.getDirContext()));
      cnx.addAll(getPreferredConnections(adsCtx2.getDirContext()));
      TopologyCache cache1 = createTopologyCache(adsCtx1, cnx);
      TopologyCache cache2 = createTopologyCache(adsCtx2, cnx);
      // Look for the cache with biggest number of replication servers:
      // that one is going to be source.
@@ -10134,10 +9979,8 @@
      if (isInteractive())
      {
        LocalizableMessage msg = INFO_REPLICATION_MERGING_REGISTRIES_CONFIRMATION.get(
            ConnectionUtils.getHostPort(ctxSource),
            ConnectionUtils.getHostPort(ctxDestination),
            ConnectionUtils.getHostPort(ctxSource),
            ConnectionUtils.getHostPort(ctxDestination));
            getHostPort(ctxSource), getHostPort(ctxDestination),
            getHostPort(ctxSource), getHostPort(ctxDestination));
        if (!askConfirmation(msg, true))
        {
          throw new ReplicationCliException(ERR_REPLICATION_USER_CANCELLED.get(), USER_CANCELLED, null);
@@ -10146,10 +9989,8 @@
      else
      {
        LocalizableMessage msg = INFO_REPLICATION_MERGING_REGISTRIES_DESCRIPTION.get(
            ConnectionUtils.getHostPort(ctxSource),
            ConnectionUtils.getHostPort(ctxDestination),
            ConnectionUtils.getHostPort(ctxSource),
            ConnectionUtils.getHostPort(ctxDestination));
            getHostPort(ctxSource), getHostPort(ctxDestination),
            getHostPort(ctxSource), getHostPort(ctxDestination));
        println(msg);
        println();
      }
@@ -10162,7 +10003,7 @@
      {
        throw new ReplicationCliException(
            ERR_REPLICATION_CANNOT_MERGE_WITH_ERRORS.get(
                ConnectionUtils.getHostPort(adsCtx1.getDirContext()),
                getHostPort(adsCtx1.getDirContext()),
                getMessageFromCollection(cache1Errors,
                    Constants.LINE_SEPARATOR)),
                    ERROR_READING_ADS, null);
@@ -10173,7 +10014,7 @@
      {
        throw new ReplicationCliException(
            ERR_REPLICATION_CANNOT_MERGE_WITH_ERRORS.get(
                ConnectionUtils.getHostPort(adsCtx2.getDirContext()),
                getHostPort(adsCtx2.getDirContext()),
                getMessageFromCollection(cache2Errors,
                    Constants.LINE_SEPARATOR)),
                    ERROR_READING_ADS, null);
@@ -10296,9 +10137,9 @@
      catch (ADSContextException adce)
      {
        logger.error(LocalizableMessage.raw("Error merging registry of "+
            ConnectionUtils.getHostPort(adsCtxSource.getDirContext())+
            getHostPort(adsCtxSource.getDirContext())+
            " with registry of "+
            ConnectionUtils.getHostPort(adsCtxDestination.getDirContext())+" "+
            getHostPort(adsCtxDestination.getDirContext())+" "+
            adce, adce));
        if (adce.getError() == ADSContextException.ErrorType.ERROR_MERGING)
        {
@@ -10321,7 +10162,7 @@
          {
            logger.info(LocalizableMessage.raw("Seeding to replication server on "+
                server.getHostPort(true)+" with certificates of "+
                ConnectionUtils.getHostPort(adsCtxSource.getDirContext())));
                getHostPort(adsCtxSource.getDirContext())));
            InitialLdapContext ctx = null;
            try
            {
@@ -10341,12 +10182,9 @@
        logger.error(LocalizableMessage.raw("Error seeding truststore: "+t, t));
        String arg = (t instanceof OpenDsException) ?
            ((OpenDsException)t).getMessageObject().toString() : t.toString();
            throw new ReplicationCliException(
                ERR_REPLICATION_ENABLE_SEEDING_TRUSTSTORE.get(
                    ConnectionUtils.getHostPort(adsCtx2.getDirContext()),
                    ConnectionUtils.getHostPort(adsCtx1.getDirContext()),
                    arg),
                    ERROR_SEEDING_TRUSTORE, t);
        LocalizableMessage msg = ERR_REPLICATION_ENABLE_SEEDING_TRUSTSTORE.get(
            getHostPort(adsCtx2.getDirContext()), getHostPort(adsCtx1.getDirContext()), arg);
        throw new ReplicationCliException(msg, ERROR_SEEDING_TRUSTORE, t);
      }
      pointAdder.stop();
      print(formatter.getSpace());
@@ -10361,13 +10199,30 @@
    }
  }
  private InitialLdapContext getDirContextForServer(TopologyCache cache,
      ServerDescriptor server) throws NamingException
  private TopologyCache createTopologyCache(ADSContext adsCtx, Set<PreferredConnection> cnx)
      throws ReplicationCliException
  {
    String dn = ConnectionUtils.getBindDN(
        cache.getAdsContext().getDirContext());
    String pwd = ConnectionUtils.getBindPassword(
        cache.getAdsContext().getDirContext());
    TopologyCache cache = new TopologyCache(adsCtx, getTrustManager(), getConnectTimeout());
    cache.setPreferredConnections(cnx);
    cache.getFilter().setSearchBaseDNInformation(false);
    try
    {
      cache.reloadTopology();
      return cache;
    }
    catch (TopologyCacheException te)
    {
      logger.error(LocalizableMessage.raw(
          "Error reading topology cache of " + getHostPort(adsCtx.getDirContext()) + " " + te, te));
      throw new ReplicationCliException(ERR_REPLICATION_READING_ADS.get(te.getMessageObject()), ERROR_UPDATING_ADS, te);
    }
  }
  private InitialLdapContext getDirContextForServer(TopologyCache cache, ServerDescriptor server)
      throws NamingException
  {
    String dn = getBindDN(cache.getAdsContext().getDirContext());
    String pwd = getBindPassword(cache.getAdsContext().getDirContext());
    TopologyCacheFilter filter = new TopologyCacheFilter();
    filter.setSearchMonitoringInformation(false);
    filter.setSearchBaseDNInformation(false);
@@ -10476,7 +10331,6 @@
        binDir += File.separatorChar;
      }
    }
    return binDir;
  }
opendj3-server-dev/src/server/org/opends/server/tools/status/StatusCli.java
@@ -24,16 +24,16 @@
 *      Copyright 2007-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2014 ForgeRock AS
 */
package org.opends.server.tools.status;
import static com.forgerock.opendj.cli.ArgumentConstants.LIST_TABLE_SEPARATOR;
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.CliMessages.*;
import static com.forgerock.opendj.cli.Utils.*;
import static org.forgerock.util.Utils.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.INFO_ERROR_READING_SERVER_CONFIGURATION;
import static org.opends.messages.QuickSetupMessages.INFO_NOT_AVAILABLE_LABEL;
import static com.forgerock.opendj.cli.Utils.MAX_LINE_WIDTH;
import static org.forgerock.util.Utils.closeSilently;
import java.io.File;
import java.io.InputStream;
@@ -65,14 +65,13 @@
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.ldap.AuthorizationException;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.LdapException;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.LDAPOptions;
import org.forgerock.opendj.ldap.LdapException;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.SSLContextBuilder;
import org.forgerock.opendj.ldap.TrustManagers;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.guitools.controlpanel.datamodel.BackendDescriptor;
import org.opends.guitools.controlpanel.datamodel.BaseDNDescriptor;
import org.opends.guitools.controlpanel.datamodel.BaseDNTableModel;
@@ -1277,7 +1276,7 @@
  {
    // Interact with the user though the console to get
    // LDAP connection information
    final String hostName = ConnectionUtils.getHostNameForLdapUrl(ci.getHostName());
    final String hostName = getHostNameForLdapUrl(ci.getHostName());
    final Integer portNumber = ci.getPortNumber();
    final String bindDN = ci.getBindDN();
    final String bindPassword = ci.getBindPassword();