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

Jean-Noël Rouvignac
07.24.2016 18dc6866af53fb06efb0879f9c9c369e698d7379
Remove ConnectionWrapper constructor accepting an InitialLdapContext

Replaced with a few ConnectionWrapper constructors that are building both the SDK Connection and the InitialLdapContext.
13 files modified
864 ■■■■ changed files
opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCache.java 14 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java 217 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java 22 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java 84 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java 13 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java 36 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LoginPanel.java 27 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java 14 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java 21 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/ui/LoginDialog.java 37 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java 44 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java 322 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java 13 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCache.java
@@ -30,7 +30,6 @@
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import org.forgerock.i18n.LocalizableMessage;
@@ -38,10 +37,10 @@
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.ConnectionWrapper;
import org.opends.admin.ads.util.PreferredConnection;
import org.opends.admin.ads.util.ServerLoader;
import org.opends.quicksetup.util.Utils;
import org.opends.server.util.StaticUtils;
import static com.forgerock.opendj.cli.Utils.*;
@@ -441,15 +440,11 @@
          "domain-name", "server-id"
        });
    InitialLdapContext ctx = null;
    NamingEnumeration<SearchResult> monitorEntries = null;
    try
    ServerLoader loader = getServerLoader(replicationServer.getAdsProperties());
    try (ConnectionWrapper conn = loader.createConnectionWrapper())
    {
      ServerLoader loader =
          getServerLoader(replicationServer.getAdsProperties());
      ctx = loader.createContext();
      monitorEntries = ctx.search(
      monitorEntries = conn.getLdapContext().search(
          new LdapName("cn=monitor"), "(missing-changes=*)", ctls);
      while (monitorEntries.hasMore())
@@ -505,7 +500,6 @@
              "Unexpected error closing enumeration on monitor entries" + t, t));
        }
      }
      StaticUtils.close(ctx);
    }
  }
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java
@@ -15,36 +15,36 @@
 */
package org.opends.admin.ads.util;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.AUTHN_BIND_REQUEST;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.CONNECT_TIMEOUT;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.SSL_CONTEXT;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.SSL_USE_STARTTLS;
import static org.opends.admin.ads.util.ConnectionUtils.getBindDN;
import static org.opends.admin.ads.util.ConnectionUtils.getBindPassword;
import static org.opends.admin.ads.util.ConnectionUtils.getHostPort;
import static org.opends.admin.ads.util.ConnectionUtils.isSSL;
import static org.opends.admin.ads.util.ConnectionUtils.isStartTLS;
import static org.forgerock.opendj.config.client.ldap.LDAPManagementContext.*;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.admin.ads.util.PreferredConnection.Type.*;
import static org.opends.messages.AdminToolMessages.*;
import java.io.Closeable;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.util.concurrent.TimeUnit;
import javax.naming.NamingException;
import javax.naming.NoPermissionException;
import javax.naming.ldap.InitialLdapContext;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.forgerock.opendj.config.LDAPProfile;
import org.forgerock.opendj.config.client.ManagementContext;
import org.forgerock.opendj.config.client.ldap.LDAPManagementContext;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.LdapException;
import org.forgerock.opendj.ldap.SSLContextBuilder;
import org.forgerock.opendj.ldap.requests.Requests;
import org.forgerock.opendj.ldap.requests.SimpleBindRequest;
import org.forgerock.opendj.server.config.client.RootCfgClient;
import org.forgerock.util.Options;
import org.forgerock.util.time.Duration;
import org.opends.admin.ads.util.PreferredConnection.Type;
import org.opends.server.types.HostPort;
import org.opends.server.util.StaticUtils;
@@ -62,12 +62,21 @@
  private final LDAPConnectionFactory connectionFactory;
  private final Connection connection;
  private final InitialLdapContext ldapContext;
  private final int connectTimeout;
  private final TrustManager trustManager;
  private final KeyManager keyManager;
  /**
   * Creates a connection wrapper from JNDI context and connection data.
   * Creates a connection wrapper.
   *
   * @param ctx
   *          the initial ldap context for JNDI
   * @param ldapUrl
   *          the ldap URL containing the host name and port number to connect to
   * @param connectionType
   *          the type of connection (LDAP, LDAPS, START_TLS)
   * @param bindDn
   *          the bind DN
   * @param bindPwd
   *          the bind password
   * @param connectTimeout
   *            connect timeout to use for the connection
   * @param trustManager
@@ -75,23 +84,156 @@
   * @throws NamingException
   *           If an error occurs
   */
  public ConnectionWrapper(InitialLdapContext ctx, long connectTimeout, TrustManager trustManager)
      throws NamingException
  public ConnectionWrapper(String ldapUrl, Type connectionType, String bindDn, String bindPwd, int connectTimeout,
      ApplicationTrustManager trustManager) throws NamingException
  {
    ldapContext = ctx;
    this(toHostPort(ldapUrl), connectionType, bindDn, bindPwd, connectTimeout, trustManager);
  }
  private static HostPort toHostPort(String ldapUrl) throws NamingException
  {
    try
    {
      URI uri = new URI(ldapUrl);
      return new HostPort(uri.getHost(), uri.getPort());
    }
    catch (URISyntaxException e)
    {
      // FIXME JNR
      throw new NamingException(e.getLocalizedMessage());
    }
  }
  /**
   * Creates a connection wrapper.
   *
   * @param hostPort
   *          the host name and port number to connect to
   * @param connectionType
   *          the type of connection (LDAP, LDAPS, START_TLS)
   * @param bindDn
   *          the bind DN
   * @param bindPwd
   *          the bind password
   * @param connectTimeout
   *          connect timeout to use for the connection
   * @param trustManager
   *          trust manager to use for a secure connection
   * @throws NamingException
   *           If an error occurs
   */
  public ConnectionWrapper(HostPort hostPort, Type connectionType, String bindDn, String bindPwd, int connectTimeout,
      TrustManager trustManager) throws NamingException
  {
    this(hostPort, connectionType, bindDn, bindPwd, connectTimeout, trustManager, null);
  }
  /**
   * Creates a connection wrapper.
   *
   * @param hostPort
   *          the host name and port number to connect to
   * @param connectionType
   *          the type of connection (LDAP, LDAPS, START_TLS)
   * @param bindDn
   *          the bind DN
   * @param bindPwd
   *          the bind password
   * @param connectTimeout
   *          connect timeout to use for the connection
   * @param trustManager
   *          trust manager to use for a secure connection
   * @param keyManager
   *          key manager to use for a secure connection
   * @throws NamingException
   *           If an error occurs
   */
  public ConnectionWrapper(HostPort hostPort, PreferredConnection.Type connectionType, String bindDn, String bindPwd,
      int connectTimeout, TrustManager trustManager, KeyManager keyManager) throws NamingException
  {
    this.connectTimeout = connectTimeout;
    this.trustManager = trustManager;
    this.keyManager = keyManager;
    final Options options = toOptions(connectionType, bindDn, bindPwd, connectTimeout, trustManager, keyManager);
    ldapContext = createAdministrativeContext(hostPort, options);
    connectionFactory = buildConnectionFactory(options, hostPort);
    connection = buildConnection();
  }
  private static Options toOptions(Type connectionType, String bindDn, String bindPwd, long connectTimeout,
      TrustManager trustManager, KeyManager keyManager) throws NamingException
  {
    final boolean isStartTls = START_TLS.equals(connectionType);
    final boolean isLdaps = LDAPS.equals(connectionType);
    Options options = Options.defaultOptions();
    options.set(CONNECT_TIMEOUT, new Duration(connectTimeout, TimeUnit.MILLISECONDS));
    if (isSSL(ctx) || isStartTLS(ctx))
    if (isLdaps || isStartTls)
    {
      options.set(SSL_CONTEXT, getSSLContext(trustManager)).set(SSL_USE_STARTTLS, isStartTLS(ctx));
      options.set(SSL_CONTEXT, getSSLContext(trustManager, keyManager))
             .set(SSL_USE_STARTTLS, isStartTls);
    }
    options.set(AUTHN_BIND_REQUEST, Requests.newSimpleBindRequest(getBindDN(ctx), getBindPassword(ctx).toCharArray()));
    HostPort hostPort = getHostPort(ctx);
    connectionFactory = new LDAPConnectionFactory(hostPort.getHost(), hostPort.getPort(), options);
    options.set(AUTHN_BIND_REQUEST, Requests.newSimpleBindRequest(bindDn, bindPwd.toCharArray()));
    return options;
  }
  private static SSLContext getSSLContext(TrustManager trustManager, KeyManager keyManager) throws NamingException
  {
    try
    {
      connection = connectionFactory.getConnection();
      return new SSLContextBuilder().setTrustManager(trustManager != null ? trustManager : new BlindTrustManager())
          .setKeyManager(keyManager).getSSLContext();
    }
    catch (GeneralSecurityException e)
    {
      throw new NamingException("Unable to perform SSL initialization:" + e.getMessage());
    }
  }
  private InitialLdapContext createAdministrativeContext(HostPort hostPort, Options options) throws NamingException
  {
    final InitialLdapContext ctx = createAdministrativeContext0(hostPort, options);
    if (!connectedAsAdministrativeUser(ctx))
    {
      throw new NoPermissionException(ERR_NOT_ADMINISTRATIVE_USER.get().toString());
    }
    return ctx;
  }
  private InitialLdapContext createAdministrativeContext0(HostPort hostPort, Options options) throws NamingException
  {
    SSLContext sslContext = options.get(SSL_CONTEXT);
    boolean useSSL = sslContext != null;
    boolean useStartTLS = options.get(SSL_USE_STARTTLS);
    SimpleBindRequest bindRequest = (SimpleBindRequest) options.get(AUTHN_BIND_REQUEST);
    String bindDn = bindRequest.getName();
    String bindPwd = new String(bindRequest.getPassword());
    final String ldapUrl = getLDAPUrl(hostPort, useSSL);
    if (useSSL)
    {
      return createLdapsContext(ldapUrl, bindDn, bindPwd, connectTimeout, null, trustManager, keyManager);
    }
    else if (useStartTLS)
    {
      return createStartTLSContext(ldapUrl, bindDn, bindPwd, connectTimeout, null, trustManager, keyManager, null);
    }
    else
    {
      return createLdapContext(ldapUrl, bindDn, bindPwd, connectTimeout, null);
    }
  }
  private LDAPConnectionFactory buildConnectionFactory(Options options, HostPort hostPort)
  {
    return new LDAPConnectionFactory(hostPort.getHost(), hostPort.getPort(), options);
  }
  private Connection buildConnection() throws NamingException
  {
    try
    {
      return connectionFactory.getConnection();
    }
    catch (LdapException e)
    {
@@ -110,17 +252,6 @@
  }
  /**
   * Returns the root configuration client by using the inrnal Connection.
   *
   * @return the root configuration client
   */
  public RootCfgClient getRootConfiguration()
  {
    ManagementContext ctx = LDAPManagementContext.newManagementContext(getConnection(), LDAPProfile.getInstance());
    return ctx.getRootConfiguration();
  }
  /**
   * Returns the ldap context (JNDI).
   *
   * @return the ldap context
@@ -130,18 +261,14 @@
    return ldapContext;
  }
  private SSLContext getSSLContext(TrustManager trustManager) throws NamingException
  /**
   * Returns the root configuration client by using the inrnal Connection.
   *
   * @return the root configuration client
   */
  public RootCfgClient getRootConfiguration()
  {
    try
    {
      return new SSLContextBuilder()
        .setTrustManager(trustManager != null ? trustManager : new BlindTrustManager())
        .getSSLContext();
    }
    catch (GeneralSecurityException e)
    {
      throw new NamingException("Unable to perform SSL initialization:" + e.getMessage());
    }
    return newManagementContext(getConnection(), LDAPProfile.getInstance()).getRootConfiguration();
  }
  @Override
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java
@@ -12,11 +12,11 @@
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2008-2009 Sun Microsystems, Inc.
 * Portions Copyright 2013-2015 ForgeRock AS.
 * Portions Copyright 2013-2016 ForgeRock AS.
 */
package org.opends.admin.ads.util;
import java.util.LinkedHashSet;
import java.util.Collections;
import java.util.Set;
import javax.naming.ldap.InitialLdapContext;
@@ -71,13 +71,13 @@
    return type;
  }
  /** {@inheritDoc} */
  @Override
  public int hashCode()
  {
    return (type+ldapUrl.toLowerCase()).hashCode();
  }
  /** {@inheritDoc} */
  @Override
  public boolean equals(Object o)
  {
    if (this == o)
@@ -93,15 +93,13 @@
    return false;
  }
  /**
   * Commodity method that returns a PreferredConnection object with the
   * information on a given InitialLdapContext.
   * @param ctx the connection we retrieve the information from.
   * @return a preferred connection object.
   */
  public static PreferredConnection getPreferredConnection(
      InitialLdapContext ctx)
  public static PreferredConnection getPreferredConnection(InitialLdapContext ctx)
  {
    String ldapUrl = ConnectionUtils.getLdapUrl(ctx);
    PreferredConnection.Type type;
@@ -120,20 +118,14 @@
    return new PreferredConnection(ldapUrl, type);
  }
  /**
   * Commodity method that generates a list of preferred connection (of just
   * one) with the information on a given InitialLdapContext.
   * @param ctx the connection we retrieve the information from.
   * @return a list containing the preferred connection object.
   */
  public static Set<PreferredConnection> getPreferredConnections(
      InitialLdapContext ctx)
  public static Set<PreferredConnection> getPreferredConnections(InitialLdapContext ctx)
  {
    PreferredConnection cnx = PreferredConnection.getPreferredConnection(ctx);
    Set<PreferredConnection> returnValue = new LinkedHashSet<>();
    returnValue.add(cnx);
    return returnValue;
    return Collections.singleton(getPreferredConnection(ctx));
  }
}
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java
@@ -24,7 +24,6 @@
import javax.naming.NamingException;
import javax.naming.NoPermissionException;
import javax.naming.TimeLimitExceededException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import org.forgerock.i18n.LocalizableMessage;
@@ -38,8 +37,6 @@
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
 * uses some provided properties and authentication information to connect
@@ -151,11 +148,11 @@
  public void run()
  {
    lastException = null;
    InitialLdapContext ctx = null;
    try
    boolean connCreated = false;
    try (ConnectionWrapper conn = createConnectionWrapper())
    {
      ctx = createContext();
      serverDescriptor = ServerDescriptor.createStandalone(ctx, filter);
      connCreated = true;
      serverDescriptor = ServerDescriptor.createStandalone(conn.getLdapContext(), filter);
      serverDescriptor.setAdsProperties(serverProperties);
      serverDescriptor.updateAdsPropertiesWithServerProperties();
    }
@@ -181,7 +178,7 @@
    {
      logger.warn(LocalizableMessage.raw(
          "NamingException error reading server: " + getLastLdapUrl(), e));
      Type type = ctx != null
      Type type = connCreated
          ? TopologyCacheException.Type.GENERIC_READING_SERVER
          : TopologyCacheException.Type.GENERIC_CREATING_CONNECTION;
      lastException = new TopologyCacheException(type, e, trustManager, getLastLdapUrl());
@@ -200,59 +197,10 @@
    finally
    {
      isOver = true;
      close(ctx);
    }
  }
  /**
   * Create an InitialLdapContext based in the provide server properties and
   * authentication data provided in the constructor.
   * @return an InitialLdapContext based in the provide server properties and
   * authentication data provided in the constructor.
   * @throws NamingException if an error occurred while creating the
   * InitialLdapContext.
   */
  public InitialLdapContext createContext() throws NamingException
  {
    InitialLdapContext ctx = null;
    if (trustManager != null)
    {
      trustManager.resetLastRefusedItems();
      String host = (String)serverProperties.get(ServerProperty.HOST_NAME);
      trustManager.setHost(host);
    }
    /* Try to connect to the server in a certain order of preference.  If an
     * URL fails, we will try with the others.
     */
    LinkedHashSet<PreferredConnection> conns = getLDAPURLsByPreference();
    for (PreferredConnection connection : conns)
    {
      if (ctx == null)
      {
        lastLdapUrl = connection.getLDAPURL();
        switch (connection.getType())
        {
        case LDAPS:
          ctx = ConnectionUtils.createLdapsContext(lastLdapUrl, dn, pwd,
              timeout, null, trustManager, null);
          break;
        case START_TLS:
          ctx = ConnectionUtils.createStartTLSContext(lastLdapUrl, dn, pwd,
              timeout, null, trustManager, null, null);
          break;
        default:
          ctx = ConnectionUtils.createLdapContext(lastLdapUrl, dn, pwd,
              timeout, null);
        }
      }
    }
    return ctx;
  }
  /**
   * Returns a Connection Wrapper.
   *
   * @return the connection wrapper
@@ -261,7 +209,27 @@
   */
  public ConnectionWrapper createConnectionWrapper() throws NamingException
  {
    return new ConnectionWrapper(createContext(), timeout, trustManager);
    if (trustManager != null)
    {
      trustManager.resetLastRefusedItems();
      String host = (String)serverProperties.get(ServerProperty.HOST_NAME);
      trustManager.setHost(host);
    }
    /* Try to connect to the server in a certain order of preference.  If an
     * URL fails, we will try with the others.
     */
    for (PreferredConnection connection : getLDAPURLsByPreference())
    {
      lastLdapUrl = connection.getLDAPURL();
      ConnectionWrapper conn = new ConnectionWrapper(lastLdapUrl, connection.getType(), dn, pwd, timeout, trustManager);
      if (conn.getLdapContext() != null)
      {
        return conn;
      }
    }
    return null;
  }
  /**
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java
@@ -17,6 +17,7 @@
package org.opends.guitools.controlpanel.datamodel;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.admin.ads.util.PreferredConnection.Type.*;
import static org.opends.guitools.controlpanel.util.Utilities.*;
import static org.opends.server.tools.ConfigureWindowsService.*;
import static com.forgerock.opendj.cli.Utils.*;
@@ -463,20 +464,16 @@
        // Try with previous credentials.
        try
        {
          InitialLdapContext context = null;
          if (isLocal)
          {
            context = Utilities.getAdminDirContext(this, lastWorkingBindDN, lastWorkingBindPwd);
            connWrapper = Utilities.getAdminDirContext(this, lastWorkingBindDN, lastWorkingBindPwd);
          }
          else if (lastRemoteAdministrationURL != null)
          {
            context = createLdapsContext(lastRemoteAdministrationURL,
                lastWorkingBindDN,
                lastWorkingBindPwd,
                getConnectTimeout(), null,
                getTrustManager(), null);
            connWrapper = new ConnectionWrapper(
                lastRemoteAdministrationURL, LDAPS, lastWorkingBindDN, lastWorkingBindPwd,
                getConnectTimeout(), getTrustManager());
          }
          connWrapper = new ConnectionWrapper(context, getConnectTimeout(), getTrustManager());
        }
        catch (ConfigReadException | NamingException cre)
        {
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java
@@ -44,6 +44,7 @@
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.DN;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.ConnectionWrapper;
@@ -62,14 +63,14 @@
import org.opends.quicksetup.util.UIKeyStore;
import org.opends.quicksetup.util.Utils;
import org.opends.server.monitors.VersionMonitorProvider;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.HostPort;
import org.opends.server.types.OpenDsException;
import org.opends.server.util.DynamicConstants;
import org.opends.server.util.StaticUtils;
import static com.forgerock.opendj.cli.Utils.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.admin.ads.util.PreferredConnection.Type.*;
import static org.opends.guitools.controlpanel.util.Utilities.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
@@ -507,11 +508,10 @@
      setEnabledOK(false);
      displayMessage(INFO_CTRL_PANEL_VERIFYING_AUTHENTICATION_SUMMARY.get());
      BackgroundTask<InitialLdapContext> worker =
        new BackgroundTask<InitialLdapContext>()
      BackgroundTask<ConnectionWrapper> worker = new BackgroundTask<ConnectionWrapper>()
      {
        @Override
        public InitialLdapContext processBackgroundTask() throws Throwable
        public ConnectionWrapper processBackgroundTask() throws Throwable
        {
          final ControlPanelInfo info = getInfo();
          info.stopPooling();
@@ -538,24 +538,21 @@
              return null;
            }
          }
          InitialLdapContext ctx = null;
          ConnectionWrapper conn = null;
          try
          {
            if (isLocal)
            {
              usedUrl = info.getAdminConnectorURL();
              ctx = Utilities.getAdminDirContext(info, dn.getText(),
                  String.valueOf(pwd.getPassword()));
              conn = Utilities.getAdminDirContext(info, dn.getText(), String.valueOf(pwd.getPassword()));
            }
            else
            {
              usedUrl = ConnectionUtils.getLDAPUrl(hostName.getText().trim(),
                  Integer.valueOf(port.getText().trim()), true);
              ctx = createLdapsContext(usedUrl, dn.getText(),
                  String.valueOf(pwd.getPassword()),
                  info.getConnectTimeout(), null,
                  info.getTrustManager(), null);
              checkVersion(ctx);
              HostPort hostPort = new HostPort(hostName.getText().trim(), Integer.valueOf(port.getText().trim()));
              usedUrl = ConnectionUtils.getLDAPUrl(hostPort, true);
              conn = new ConnectionWrapper(hostPort, LDAPS, dn.getText(), String.valueOf(pwd.getPassword()),
                  info.getConnectTimeout(), info.getTrustManager());
              checkVersion(conn.getLdapContext());
            }
            StaticUtils.sleep(500);
@@ -569,20 +566,19 @@
            });
            closeInfoConnections();
            info.setIsLocal(isLocal);
            info.setConnection(
                new ConnectionWrapper(ctx, info.getConnectTimeout(), info.getTrustManager()));
            info.setConnection(conn);
            info.setUserDataDirContext(null);
            info.regenerateDescriptor();
            return ctx;
            return conn;
          } catch (Throwable t)
          {
            StaticUtils.close(ctx);
            StaticUtils.close(conn);
            throw t;
          }
        }
        @Override
        public void backgroundTaskCompleted(InitialLdapContext ctx, Throwable throwable)
        public void backgroundTaskCompleted(ConnectionWrapper conn, Throwable throwable)
        {
          boolean handleCertificateException = false;
          boolean localServerErrorConnecting = false;
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LoginPanel.java
@@ -14,7 +14,6 @@
 * Copyright 2008-2009 Sun Microsystems, Inc.
 * Portions Copyright 2011-2016 ForgeRock AS.
 */
package org.opends.guitools.controlpanel.ui;
import java.awt.Component;
@@ -25,7 +24,6 @@
import java.util.LinkedHashSet;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
@@ -33,6 +31,7 @@
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.DN;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.datamodel.ConfigReadException;
@@ -43,10 +42,10 @@
import org.opends.quicksetup.ui.CertificateDialog;
import org.opends.quicksetup.util.UIKeyStore;
import org.opends.quicksetup.util.Utils;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.util.StaticUtils;
import static com.forgerock.opendj.cli.Utils.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
@@ -190,19 +189,16 @@
      setEnabledCancel(false);
      displayMessage(INFO_CTRL_PANEL_VERIFYING_AUTHENTICATION_SUMMARY.get());
      BackgroundTask<InitialLdapContext> worker =
        new BackgroundTask<InitialLdapContext>()
      BackgroundTask<ConnectionWrapper> worker = new BackgroundTask<ConnectionWrapper>()
      {
        /** {@inheritDoc} */
        @Override
        public InitialLdapContext processBackgroundTask() throws Throwable
        public ConnectionWrapper processBackgroundTask() throws Throwable
        {
          InitialLdapContext ctx = null;
          ConnectionWrapper conn = null;
          try
          {
            usedUrl = getInfo().getAdminConnectorURL();
            ctx = Utilities.getAdminDirContext(getInfo(), dn.getText(),
                String.valueOf(pwd.getPassword()));
            conn = Utilities.getAdminDirContext(getInfo(), dn.getText(), String.valueOf(pwd.getPassword()));
            if (getInfo().getConnection() != null)
            {
@@ -240,22 +236,19 @@
                    INFO_CTRL_PANEL_READING_CONFIGURATION_SUMMARY.get());
              }
            });
            getInfo().setConnection(
                new ConnectionWrapper(ctx, getInfo().getConnectTimeout(), getInfo().getTrustManager()));
            getInfo().setConnection(conn);
            getInfo().setUserDataDirContext(null);
            getInfo().regenerateDescriptor();
            return ctx;
            return conn;
          } catch (Throwable t)
          {
            StaticUtils.close(ctx);
            StaticUtils.close(conn);
            throw t;
          }
        }
        /** {@inheritDoc} */
        @Override
        public void backgroundTaskCompleted(InitialLdapContext ctx,
            Throwable throwable)
        public void backgroundTaskCompleted(ConnectionWrapper conn, Throwable throwable)
        {
          boolean handleCertificateException = false;
          if (throwable != null)
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java
@@ -20,6 +20,7 @@
import static com.forgerock.opendj.util.OperatingSystem.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.admin.ads.util.PreferredConnection.Type.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.quicksetup.Installation.*;
@@ -95,6 +96,7 @@
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.forgerock.opendj.ldap.schema.MatchingRule;
import org.forgerock.opendj.ldap.schema.Syntax;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.ControlPanel;
import org.opends.guitools.controlpanel.browser.IconPool;
import org.opends.guitools.controlpanel.datamodel.CategorizedComboBoxElement;
@@ -2173,8 +2175,7 @@
   * or the provided credentials do not have enough rights.
   * @throws ConfigReadException if there is an error reading the configuration.
   */
  public static InitialLdapContext getAdminDirContext(
      ControlPanelInfo controlInfo, String bindDN, String pwd)
  public static ConnectionWrapper getAdminDirContext(ControlPanelInfo controlInfo, String bindDN, String pwd)
  throws NamingException, ConfigReadException
  {
    String usedUrl = controlInfo.getAdminConnectorURL();
@@ -2184,12 +2185,11 @@
          ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
    }
    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;
    ConnectionWrapper conn = new ConnectionWrapper(
        usedUrl, LDAPS, bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
    checkCanReadConfig(conn.getLdapContext());
    return conn;
  }
opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java
@@ -18,8 +18,10 @@
import static org.forgerock.util.Utils.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.admin.ads.util.PreferredConnection.Type.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.Utils.*;
@@ -48,6 +50,7 @@
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.admin.ads.util.PreferredConnection.Type;
import org.opends.guitools.controlpanel.datamodel.ConnectionProtocolPolicy;
import org.opends.guitools.controlpanel.datamodel.ControlPanelInfo;
import org.opends.quicksetup.Application;
@@ -64,6 +67,7 @@
import org.opends.quicksetup.util.ServerController;
import org.opends.quicksetup.util.Utils;
import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
import org.opends.server.types.HostPort;
import org.opends.server.util.StaticUtils;
import org.opends.server.util.cli.LDAPConnectionConsoleInteraction;
@@ -94,8 +98,7 @@
  private ControlPanelInfo info;
  private boolean forceNonInteractive;
  private boolean useSSL = true;
  private boolean useStartTLS;
  private Type connectionType = LDAPS;
  /** Default constructor. */
  public UninstallCliHelper()
@@ -120,8 +123,7 @@
   *           If there is an error processing data in non-interactive mode and
   *           an error must be thrown (not in force on error mode).
   */
  public UninstallUserData createUserData(UninstallerArgumentParser args,
      String[] rawArguments)
  public UninstallUserData createUserData(UninstallerArgumentParser args, String[] rawArguments)
  throws UserDataException, ClientException
  {
    parser = args;
@@ -1134,7 +1136,7 @@
    logger.info(LocalizableMessage.raw("Updating user data with remote servers."));
    InitialLdapContext ctx = null;
    ConnectionWrapper conn = null;
    try
    {
      info.setTrustManager(userData.getTrustManager());
@@ -1157,11 +1159,10 @@
      {
        logger.error(LocalizableMessage.raw("Error parsing url: "+adminConnectorUrl));
      }
      ctx = createAdministrativeContext(host, port, useSSL, useStartTLS, dn,
          pwd, getConnectTimeout(), userData.getTrustManager());
      ConnectionWrapper connWrapper = new ConnectionWrapper(ctx, getConnectTimeout(), userData.getTrustManager());
      conn = new ConnectionWrapper(new HostPort(host, port), connectionType, dn, pwd,
          getConnectTimeout(), userData.getTrustManager());
      ADSContext adsContext = new ADSContext(connWrapper);
      ADSContext adsContext = new ADSContext(conn);
      if (interactive && userData.getTrustManager() == null)
      {
        // This is required when the user did  connect to the server using SSL
@@ -1208,7 +1209,7 @@
    }
    finally
    {
      StaticUtils.close(ctx);
      StaticUtils.close(conn);
    }
    if (exceptionOccurred)
    {
opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/ui/LoginDialog.java
@@ -27,7 +27,6 @@
import java.util.ArrayList;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
@@ -74,7 +73,7 @@
{
  private static final long serialVersionUID = 9049409381101152000L;
  private JFrame parent;
  private final JFrame parent;
  private JLabel lHostName;
  private JLabel lUid;
@@ -89,10 +88,8 @@
  private boolean isCanceled = true;
  private ApplicationTrustManager trustManager;
  private int timeout;
  private InitialLdapContext ctx;
  private final ApplicationTrustManager trustManager;
  private final int timeout;
  private ConnectionWrapper connWrapper;
@@ -191,15 +188,6 @@
  /**
   * Returns the connection we got with the provided authentication.
   * @return the connection we got with the provided authentication.
   */
  public InitialLdapContext getContext()
  {
    return ctx;
  }
  /**
   * Returns the connection we got with the provided authentication.
   *
   * @return the connection
   */
@@ -378,20 +366,15 @@
    dispose();
  }
  /**
   * Method called when user clicks on OK.
   *
   */
  /** Method called when user clicks on OK. */
  private void okClicked()
  {
    BackgroundTask<Boolean> worker = new BackgroundTask<Boolean>()
    {
      @Override
      public Boolean processBackgroundTask() throws NamingException,
      ApplicationException
      public Boolean processBackgroundTask() throws NamingException, ApplicationException
      {
        Boolean isServerRunning = Boolean.TRUE;
        ctx = null;
        connWrapper = null;
        try
        {
          ControlPanelInfo info = ControlPanelInfo.getInstance();
@@ -409,16 +392,15 @@
            throw new ApplicationException(ReturnCode.APPLICATION_ERROR,
                ERR_COULD_NOT_FIND_VALID_LDAPURL.get(), null);
          }
          ctx = org.opends.guitools.controlpanel.util.Utilities.getAdminDirContext(info, dn, pwd);
          connWrapper = new ConnectionWrapper(ctx, info.getConnectTimeout(), info.getTrustManager());
          connWrapper = org.opends.guitools.controlpanel.util.Utilities.getAdminDirContext(info, dn, pwd);
          return true; // server is running
        } catch (NamingException ne)
        {
          if (isServerRunning())
          {
            throw ne;
          }
          isServerRunning = Boolean.FALSE;
          return false;
        } catch (ApplicationException | IllegalStateException e)
        {
          throw e;
@@ -426,7 +408,6 @@
        {
          throw new IllegalStateException("Unexpected throwable.", t);
        }
        return isServerRunning;
      }
      @Override
opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java
@@ -17,17 +17,20 @@
package org.opends.quicksetup.installer;
import static com.forgerock.opendj.util.OperatingSystem.isWindows;
import static com.forgerock.opendj.cli.ArgumentConstants.*;
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.admin.ads.util.PreferredConnection.*;
import static org.opends.admin.ads.util.PreferredConnection.Type.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.quicksetup.Step.*;
import static org.opends.quicksetup.installer.DataReplicationOptions.Type.*;
import static org.opends.quicksetup.installer.InstallProgressStep.*;
import static org.opends.quicksetup.util.Utils.*;
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.Utils.*;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
@@ -128,9 +131,9 @@
import org.opends.server.util.CertificateManager;
import org.opends.server.util.CollectionUtils;
import org.opends.server.util.DynamicConstants;
import org.opends.server.util.Platform.KeyType;
import org.opends.server.util.SetupUtils;
import org.opends.server.util.StaticUtils;
import org.opends.server.util.Platform.KeyType;
import com.forgerock.opendj.util.OperatingSystem;
@@ -2828,18 +2831,16 @@
    String dn = auth.getDn();
    String pwd = auth.getPwd();
    InitialLdapContext context;
    if (auth.useSecureConnection())
    {
      ApplicationTrustManager trustManager = getTrustManager();
      trustManager.setHost(auth.getHostPort().getHost());
      context = createLdapsContext(ldapUrl, dn, pwd, getConnectTimeout(), null, trustManager, null);
      return new ConnectionWrapper(ldapUrl, LDAPS, dn, pwd, getConnectTimeout(), getTrustManager());
    }
    else
    {
      context = createLdapContext(ldapUrl, dn, pwd, getConnectTimeout(), null);
      return new ConnectionWrapper(ldapUrl, LDAP, dn, pwd, getConnectTimeout(), getTrustManager());
    }
    return new ConnectionWrapper(context, getConnectTimeout(), getTrustManager());
  }
  /**
@@ -3470,8 +3471,7 @@
      throws UserDataException
  {
    host = getHostNameForLdapUrl(host);
    String ldapUrl = "ldaps://" + host + ":" + port;
    InitialLdapContext ctx = null;
    HostPort hostPort = new HostPort(host, port);
    ConnectionWrapper conn = null;
    ApplicationTrustManager trustManager = getTrustManager();
@@ -3482,7 +3482,7 @@
      effectiveDn[0] = dn;
      try
      {
        ctx = createLdapsContext(ldapUrl, dn, pwd, getConnectTimeout(), null, trustManager, null);
        conn = new ConnectionWrapper(hostPort, LDAPS, dn, pwd, getConnectTimeout(), trustManager);
      }
      catch (Throwable t)
      {
@@ -3491,14 +3491,13 @@
          // Try using a global administrator
          dn = ADSContext.getAdministratorDN(dn);
          effectiveDn[0] = dn;
          ctx = createLdapsContext(ldapUrl, dn, pwd, getConnectTimeout(), null, trustManager, null);
          conn = new ConnectionWrapper(hostPort, LDAPS, dn, pwd, getConnectTimeout(), trustManager);
        }
        else
        {
          throw t;
        }
      }
      conn = new ConnectionWrapper(ctx, getConnectTimeout(), trustManager);
      ADSContext adsContext = new ADSContext(conn);
      if (adsContext.hasAdminData())
      {
@@ -3573,7 +3572,7 @@
      }
      else
      {
        updateUserDataWithSuffixesInServer(ctx);
        updateUserDataWithSuffixesInServer(conn.getLdapContext());
      }
    }
    catch (UserDataException ude)
@@ -3637,7 +3636,6 @@
    }
    finally
    {
      StaticUtils.close(ctx);
      StaticUtils.close(conn);
    }
  }
@@ -4009,11 +4007,8 @@
      type = SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
    }
    lastLoadedCache = new TopologyCache(adsContext, trustManager, getConnectTimeout());
    LinkedHashSet<PreferredConnection> cnx = new LinkedHashSet<>();
    cnx.add(PreferredConnection.getPreferredConnection(adsContext.getDirContext()));
    // We cannot use getPreferredConnections since the user data has not been
    // updated yet.
    lastLoadedCache.setPreferredConnections(cnx);
    // We cannot use getPreferredConnections since the user data has not been updated yet.
    lastLoadedCache.setPreferredConnections(Collections.singleton(getPreferredConnection(adsContext.getDirContext())));
    lastLoadedCache.reloadTopology();
    Set<SuffixDescriptor> suffixes = lastLoadedCache.getSuffixes();
    Set<SuffixDescriptor> moreSuffixes = null;
@@ -4186,12 +4181,11 @@
  private ConnectionWrapper createLocalConnection() throws NamingException
  {
    String ldapUrl =
        "ldaps://" + getHostNameForLdapUrl(getUserData().getHostName()) + ":" + getUserData().getAdminConnectorPort();
    String dn = getUserData().getDirectoryManagerDn();
    String pwd = getUserData().getDirectoryManagerPwd();
    InitialLdapContext context = createLdapsContext(ldapUrl, dn, pwd, getConnectTimeout(), null, null, null);
    return new ConnectionWrapper(context, getConnectTimeout(), null);
    UserData uData = getUserData();
    HostPort hostPort = new HostPort(uData.getHostName(), uData.getAdminConnectorPort());
    String dn = uData.getDirectoryManagerDn();
    String pwd = uData.getDirectoryManagerPwd();
    return new ConnectionWrapper(hostPort, LDAPS, dn, pwd, getConnectTimeout(), null);
  }
  /**
opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java
@@ -17,6 +17,25 @@
 */
package org.opends.server.tools.dsreplication;
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.CommonArguments.*;
import static com.forgerock.opendj.cli.Utils.*;
import static com.forgerock.opendj.util.OperatingSystem.*;
import static java.util.Collections.*;
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.util.PreferredConnection.Type.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.messages.ToolMessages.*;
import static org.opends.quicksetup.util.Utils.*;
import static org.opends.server.tools.dsreplication.ReplicationCliArgumentParser.*;
import static org.opends.server.tools.dsreplication.ReplicationCliReturnCode.*;
import static org.opends.server.util.StaticUtils.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -93,6 +112,7 @@
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.admin.ads.util.OpendsCertificateException;
import org.opends.admin.ads.util.PreferredConnection;
import org.opends.admin.ads.util.PreferredConnection.Type;
import org.opends.admin.ads.util.ServerLoader;
import org.opends.guitools.controlpanel.datamodel.BackendDescriptor;
import org.opends.guitools.controlpanel.datamodel.BaseDNDescriptor;
@@ -148,24 +168,6 @@
import com.forgerock.opendj.cli.TextTablePrinter;
import com.forgerock.opendj.cli.ValidationCallback;
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.CommonArguments.*;
import static com.forgerock.opendj.cli.Utils.*;
import static com.forgerock.opendj.util.OperatingSystem.*;
import static java.util.Collections.*;
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.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.messages.ToolMessages.*;
import static org.opends.quicksetup.util.Utils.*;
import static org.opends.server.tools.dsreplication.ReplicationCliArgumentParser.*;
import static org.opends.server.tools.dsreplication.ReplicationCliReturnCode.*;
import static org.opends.server.util.StaticUtils.*;
/**
 * This class provides a tool that can be used to enable and disable replication
 * and also to initialize the contents of a replicated suffix with the contents
@@ -196,8 +198,7 @@
  private boolean forceNonInteractive;
  /** Always use SSL with the administration connector. */
  private final boolean useSSL = true;
  private final boolean useStartTLS = false;
  private final Type connectiontype = LDAPS;
  /**
   * The enumeration containing the different options we display when we ask
@@ -1074,7 +1075,7 @@
   * @throws NamingException
   *           if there was an error establishing the connection.
   */
  private InitialLdapContext createAdministrativeContext(HostPort hostPort,
  private static InitialLdapContext createAdministrativeContext(HostPort hostPort,
      boolean useSSL, boolean useStartTLS, String bindDn, String pwd,
      int connectTimeout, ApplicationTrustManager trustManager)
      throws NamingException
@@ -1100,24 +1101,6 @@
    return ctx;
  }
  /**
   * Creates an Initial LDAP Context interacting with the user if the
   * application is interactive.
   *
   * @param ci
   *          the LDAPConnectionConsoleInteraction object that is assumed to
   *          have been already run.
   * @return the initial LDAP context or <CODE>null</CODE> if the user did not
   *         accept to trust the certificates.
   * @throws ClientException
   *           if there was an error establishing the connection.
   */
  private InitialLdapContext createInitialLdapContextInteracting(LDAPConnectionConsoleInteraction ci)
      throws ClientException
  {
    return createInitialLdapContextInteracting(ci, isInteractive() && ci.isTrustStoreInMemory());
  }
  private ConnectionWrapper createConnectionInteracting(LDAPConnectionConsoleInteraction ci)
      throws ClientException
  {
@@ -1137,22 +1120,6 @@
    return null;
  }
  private ConnectionWrapper createConnectionInteracting(LDAPConnectionConsoleInteraction ci,
      boolean promptForCertificate) throws ClientException
  {
    try
    {
      InitialLdapContext ctx= createInitialLdapContextInteracting(ci, promptForCertificate);
      return new ConnectionWrapper(ctx, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, ci.getTrustManager());
    }
    catch (NamingException e)
    {
      String hostName = getHostNameForLdapUrl(ci.getHostName());
      Integer portNumber = ci.getPortNumber();
      throw new ClientException(ReturnCode.CLIENT_SIDE_CONNECT_ERROR, ERR_FAILED_TO_CONNECT.get(hostName, portNumber));
    }
  }
  /**
   * Creates an Initial LDAP Context interacting with the user if the
   * application is interactive.
@@ -1167,30 +1134,28 @@
   * @throws ClientException
   *           if there was an error establishing the connection.
   */
  private InitialLdapContext createInitialLdapContextInteracting(LDAPConnectionConsoleInteraction ci,
  private ConnectionWrapper createConnectionInteracting(LDAPConnectionConsoleInteraction ci,
      boolean promptForCertificate) throws ClientException
  {
    // Interact with the user though the console to get
    // LDAP connection information
    String hostName = getHostNameForLdapUrl(ci.getHostName());
    Integer portNumber = ci.getPortNumber();
    int portNumber = ci.getPortNumber();
    HostPort hostPort = new HostPort(hostName, portNumber);
    String bindDN = ci.getBindDN();
    String bindPassword = ci.getBindPassword();
    TrustManager trustManager = ci.getTrustManager();
    KeyManager keyManager = ci.getKeyManager();
    InitialLdapContext ctx;
    ConnectionWrapper conn;
    if (ci.useSSL())
    {
      String ldapsUrl = "ldaps://" + hostName + ":" + portNumber;
      while (true)
      {
        try
        {
          ctx = createLdapsContext(ldapsUrl, bindDN, bindPassword, ci.getConnectTimeout(),
              null, trustManager, keyManager);
          ctx.reconnect(null);
          conn = new ConnectionWrapper(
              hostPort, LDAPS, bindDN, bindPassword, ci.getConnectTimeout(), trustManager, keyManager);
          break;
        }
        catch (NamingException e)
@@ -1200,13 +1165,7 @@
            OpendsCertificateException oce = getCertificateRootException(e);
            if (oce != null)
            {
              String authType = null;
              if (trustManager instanceof ApplicationTrustManager)
              {
                ApplicationTrustManager appTrustManager =
                    (ApplicationTrustManager) trustManager;
                authType = appTrustManager.getLastRefusedAuthType();
              }
              String authType = getAuthType(trustManager);
              if (ci.checkServerCertificate(oce.getChain(), authType, hostName))
              {
                // If the certificate is trusted, update the trust manager.
@@ -1241,7 +1200,6 @@
                  ReturnCode.CLIENT_SIDE_CONNECT_ERROR, message);
            }
          }
          HostPort hostPort = new HostPort(hostName, portNumber);
          LocalizableMessage message = getMessageForException(e, hostPort.toString());
          throw new ClientException(ReturnCode.CLIENT_SIDE_CONNECT_ERROR, message);
        }
@@ -1249,32 +1207,27 @@
    }
    else if (ci.useStartTLS())
    {
      String ldapUrl = "ldap://" + hostName + ":" + portNumber;
      while (true)
      {
        try
        {
          ctx = createStartTLSContext(ldapUrl, bindDN,
                  bindPassword, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, null,
                  trustManager, keyManager, null);
          ctx.reconnect(null);
          break;
          conn = new ConnectionWrapper(
              hostPort, START_TLS, bindDN, bindPassword,
              CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, trustManager, keyManager);
          return conn;
        }
        catch (NamingException e)
        {
          if (promptForCertificate)
          if (!promptForCertificate)
          {
            OpendsCertificateException oce = getCertificateRootException(e);
            if (oce != null)
            {
              String authType = null;
              if (trustManager instanceof ApplicationTrustManager)
              {
                ApplicationTrustManager appTrustManager =
                    (ApplicationTrustManager) trustManager;
                authType = appTrustManager.getLastRefusedAuthType();
            throw failedToConnect(hostName, portNumber);
              }
          OpendsCertificateException oce = getCertificateRootException(e);
          if (oce == null)
          {
            throw failedToConnect(hostName, portNumber);
          }
          String authType = getAuthType(trustManager);
              if (ci.checkServerCertificate(oce.getChain(), authType, hostName))
              {
                // If the certificate is trusted, update the trust manager.
@@ -1289,49 +1242,44 @@
                return null;
              }
            }
            else
            {
              LocalizableMessage message =
                  ERR_FAILED_TO_CONNECT.get(hostName, portNumber);
              throw new ClientException(
                  ReturnCode.CLIENT_SIDE_CONNECT_ERROR, message);
            }
          }
          LocalizableMessage message =
              ERR_FAILED_TO_CONNECT.get(hostName, portNumber);
          throw new ClientException(ReturnCode.CLIENT_SIDE_CONNECT_ERROR,
              message);
        }
      }
    }
    else
    {
      String ldapUrl = "ldap://" + hostName + ":" + portNumber;
      while (true)
      {
        try
        {
          ctx = createLdapContext(ldapUrl, bindDN, bindPassword,
                  CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, null);
          ctx.reconnect(null);
          break;
          conn = new ConnectionWrapper(
              hostPort, LDAP, bindDN, bindPassword, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, null);
          return conn;
        }
        catch (NamingException e)
        {
          LocalizableMessage message =
              ERR_FAILED_TO_CONNECT.get(hostName, portNumber);
          throw new ClientException(ReturnCode.CLIENT_SIDE_CONNECT_ERROR,
              message);
          throw failedToConnect(hostName, portNumber);
        }
      }
    }
    return ctx;
    return conn;
  }
  private String getAuthType(TrustManager trustManager)
  {
    if (trustManager instanceof ApplicationTrustManager)
    {
      return ((ApplicationTrustManager) trustManager).getLastRefusedAuthType();
    }
    return null;
  }
  private ClientException failedToConnect(String hostName, Integer portNumber)
  {
    return new ClientException(ReturnCode.CLIENT_SIDE_CONNECT_ERROR, ERR_FAILED_TO_CONNECT.get(hostName, portNumber));
  }
  private ReplicationCliReturnCode purgeHistoricalRemotely(
      PurgeHistoricalUserData uData)
  {
    // Connect to the provided server
    InitialLdapContext ctx = createAdministrativeContext(uData);
    if (ctx == null)
    {
@@ -1598,14 +1546,13 @@
  {
    try
    {
      InitialLdapContext ctx = createAdministrativeContext(uData, bindDn);
      if (ctx != null)
      {
        return new ConnectionWrapper(ctx, getConnectTimeout(), getTrustManager(sourceServerCI));
      }
      return new ConnectionWrapper(uData.getHostPort(), connectiontype, bindDn, uData.getAdminPwd(),
          getConnectTimeout(), getTrustManager(sourceServerCI));
    }
    catch (NamingException e)
    {
      errPrintln();
      errPrintln(getMessageForException(e, uData.getHostPort().toString()));
      logger.error(LocalizableMessage.raw("Error when creating connection for:" + uData.getHostPort()));
    }
    return null;
@@ -1615,8 +1562,10 @@
  {
    try
    {
      return createAdministrativeContext(uData.getHostPort(), useSSL, useStartTLS, bindDn,
          uData.getAdminPwd(), getConnectTimeout(), getTrustManager(sourceServerCI));
      boolean useStartTLS = START_TLS.equals(connectiontype);
      boolean useSSL = LDAPS.equals(connectiontype);
      return createAdministrativeContext(uData.getHostPort(), useSSL, useStartTLS,
          bindDn, uData.getAdminPwd(), getConnectTimeout(), getTrustManager(sourceServerCI));
    }
    catch (NamingException ne)
    {
@@ -2076,20 +2025,6 @@
  private ConnectionWrapper getConnection(PurgeHistoricalUserData uData)
  {
    try
    {
      InitialLdapContext ctx = getInitialLdapContext(uData);
      return new ConnectionWrapper(ctx, sourceServerCI.getConnectTimeout(), sourceServerCI.getTrustManager());
    }
    catch (NamingException ce)
    {
      logger.warn(LocalizableMessage.raw("An error occured " + ce));
      return null;
    }
  }
  private InitialLdapContext getInitialLdapContext(PurgeHistoricalUserData uData)
  {
    boolean firstTry = true;
    Boolean serverRunning = null;
@@ -2128,15 +2063,15 @@
      {
        sourceServerCI.run();
        InitialLdapContext ctx = createInitialLdapContextInteracting(sourceServerCI);
        if (ctx != null)
        ConnectionWrapper conn = createConnectionInteracting(sourceServerCI);
        if (conn != null)
        {
          uData.setOnline(true);
          uData.setHostPort(new HostPort(sourceServerCI.getHostName(), sourceServerCI.getPortNumber()));
          uData.setAdminUid(sourceServerCI.getAdministratorUID());
          uData.setAdminPwd(sourceServerCI.getBindPassword());
        }
        return ctx;
        return conn;
      }
      catch (ClientException ce)
      {
@@ -2999,17 +2934,15 @@
   */
  private boolean promptIfRequired(InitializeAllReplicationUserData uData)
  {
    InitialLdapContext ctx = null;
    try
    try (ConnectionWrapper conn = getConnection(uData))
    {
      ctx = getInitialLdapContext(uData);
      if (ctx == null)
      if (conn == null)
      {
        return false;
      }
      List<String> suffixes = argParser.getBaseDNs();
      checkSuffixesForInitializeReplication(suffixes, ctx, true);
      checkSuffixesForInitializeReplication(suffixes, conn.getLdapContext(), true);
      if (suffixes.isEmpty())
      {
        return false;
@@ -3018,17 +2951,13 @@
      // Ask for confirmation to initialize.
      println();
      if (!askConfirmation(getPrompt(uData, ctx), true))
      if (!askConfirmation(getPrompt(uData, conn.getLdapContext()), true))
      {
        return false;
      }
      println();
      return true;
    }
    finally
    {
      close(ctx);
    }
  }
  private LocalizableMessage getPrompt(InitializeAllReplicationUserData uData, InitialLdapContext ctx)
@@ -3086,20 +3015,6 @@
  private ConnectionWrapper getConnection(MonoServerReplicationUserData uData)
  {
    try
    {
      InitialLdapContext ctx = getInitialLdapContext(uData);
      return new ConnectionWrapper(ctx, sourceServerCI.getConnectTimeout(), getTrustManager(sourceServerCI));
    }
    catch (NamingException ce)
    {
      logger.warn(LocalizableMessage.raw("An error occured " + ce));
      return null;
    }
  }
  private InitialLdapContext getInitialLdapContext(MonoServerReplicationUserData uData)
  {
    // Try to connect to the server.
    while (true)
    {
@@ -3111,8 +3026,8 @@
        }
        sourceServerCI.run();
        InitialLdapContext ctx = createInitialLdapContextInteracting(sourceServerCI);
        if (ctx != null)
        ConnectionWrapper conn = createConnectionInteracting(sourceServerCI);
        if (conn != null)
        {
          uData.setHostPort(new HostPort(sourceServerCI.getHostName(), sourceServerCI.getPortNumber()));
          uData.setAdminUid(sourceServerCI.getAdministratorUID());
@@ -3122,7 +3037,7 @@
            ((StatusReplicationUserData) uData).setScriptFriendly(argParser.isScriptFriendly());
          }
        }
        return ctx;
        return conn;
      }
      catch (ClientException ce)
      {
@@ -3429,7 +3344,8 @@
      try
      {
        InitialLdapContext ctx = createAdministrativeContext(server.getHostPort(),
            useSSL, useStartTLS, adminDN, adminPwd, getConnectTimeout(), getTrustManager(sourceServerCI));
            LDAPS.equals(connectiontype), START_TLS.equals(connectiontype), adminDN, adminPwd,
            getConnectTimeout(), getTrustManager(sourceServerCI));
        server.setBindDn(adminDN);
        server.setPwd(adminPwd);
        ctx.close();
@@ -3605,6 +3521,19 @@
    HostPort hostPort = getHostPort(ctx1);
    boolean isSSL = isSSL(ctx1);
    boolean isStartTLS = isStartTLS(ctx1);
    Type connectionType;
    if (isSSL)
    {
      connectionType = LDAPS;
    }
    else if (isStartTLS)
    {
      connectionType = START_TLS;
    }
    else
    {
      connectionType = LDAP;
    }
    if (getTrustManager(ci) == null)
    {
      // This is required when the user did  connect to the server using SSL or
@@ -3694,17 +3623,15 @@
                  close(ctx1);
                  try
                  {
                    final InitialLdapContext ctx2 = createAdministrativeContext(hostPort, isSSL, isStartTLS,
                        getAdministratorDN(adminUid), adminPwd, getConnectTimeout(), getTrustManager(ci));
                    final ConnectionWrapper connWrapper2 =
                        new ConnectionWrapper(ctx2, getConnectTimeout(), getTrustManager(ci));
                    final ConnectionWrapper connWrapper2 = new ConnectionWrapper(
                          hostPort, connectionType, getAdministratorDN(adminUid), adminPwd,
                          getConnectTimeout(), getTrustManager(ci));
                    connWrapper.set(connWrapper2);
                    adsContext = new ADSContext(connWrapper2);
                    cache = new TopologyCache(adsContext, getTrustManager(ci),
                        getConnectTimeout());
                    cache = new TopologyCache(adsContext, getTrustManager(ci), getConnectTimeout());
                    cache.getFilter().setSearchMonitoringInformation(false);
                    cache.getFilter().setSearchBaseDNInformation(false);
                    cache.setPreferredConnections(getPreferredConnections(ctx2));
                    cache.setPreferredConnections(getPreferredConnections(connWrapper2.getLdapContext()));
                    connected = true;
                  }
                  catch (Throwable t)
@@ -4178,36 +4105,17 @@
  {
    try
    {
      InitialLdapContext ctx = createAdministrativeContext(server, errorMessages);
      if (ctx != null)
      {
        return new ConnectionWrapper(ctx, getConnectTimeout(), getTrustManager(sourceServerCI));
      }
      return new ConnectionWrapper(server.getHostPort(), connectiontype, server.getBindDn(), server.getPwd(),
          getConnectTimeout(), getTrustManager(sourceServerCI));
    }
    catch (NamingException e)
    {
      errorMessages.add(getMessageForException(e, server.getHostPort().toString()));
      logger.error(LocalizableMessage.raw("Error when creating connection for:" + server.getHostPort()));
    }
    return null;
  }
  private InitialLdapContext createAdministrativeContext(EnableReplicationServerData server,
      List<LocalizableMessage> errorMessages)
  {
    try
    {
      return createAdministrativeContext(
          server.getHostPort(), useSSL, useStartTLS, server.getBindDn(), server.getPwd(),
          getConnectTimeout(), getTrustManager(sourceServerCI));
    }
    catch (NamingException ne)
    {
      errorMessages.add(getMessageForException(ne, server.getHostPort().toString()));
      logger.error(LocalizableMessage.raw("Complete error stack:"), ne);
      return null;
    }
  }
  /**
   * Disables the replication in the server for the provided suffixes using the
   * data in the DisableReplicationUserData object.  This method does not prompt
@@ -4396,7 +4304,7 @@
    try
    {
      return createAdministrativeContext(
          server, useSSL, useStartTLS,
          server, LDAPS.equals(connectiontype), START_TLS.equals(connectiontype),
          getAdministratorDN(uData.getAdminUid()), uData.getAdminPwd(),
          getConnectTimeout(), getTrustManager(sourceServerCI));
    }
@@ -7123,12 +7031,8 @@
    for (ServerDescriptor s : allServers)
    {
      logger.info(LocalizableMessage.raw("Configuring server "+server.getHostPort(true)));
      InitialLdapContext ctx = null;
      ConnectionWrapper conn = null;
      try
      try (ConnectionWrapper conn = getDirContextForServer(cache, s))
      {
        ctx = getDirContextForServer(cache, s);
        conn = new ConnectionWrapper(ctx, getConnectTimeout(), getTrustManager(sourceServerCI));
        if (serversToConfigureDomain.contains(s))
        {
          configureToReplicateBaseDN(conn, baseDN, repServers, usedIds);
@@ -7150,11 +7054,6 @@
        LocalizableMessage msg = getMessageForEnableException(hostPort, baseDN);
        throw new ReplicationCliException(msg, ERROR_ENABLING_REPLICATION_ON_BASEDN, ode);
      }
      finally
      {
        close(ctx);
        close(conn);
      }
      alreadyConfiguredServers.add(s.getId());
      alreadyConfiguredReplicationServers.add(s.getId());
    }
@@ -9603,16 +9502,9 @@
            logger.info(LocalizableMessage.raw("Seeding to replication server on "+
                server.getHostPort(true)+" with certificates of "+
                getHostPort(adsCtxSource.getDirContext())));
            InitialLdapContext ctx = null;
            try
            try (ConnectionWrapper conn = getDirContextForServer(cacheDestination, server))
            {
              ctx = getDirContextForServer(cacheDestination, server);
              ServerDescriptor.seedAdsTrustStore(ctx,
                  adsCtxSource.getTrustedCertificates());
            }
            finally
            {
              close(ctx);
              ServerDescriptor.seedAdsTrustStore(conn.getLdapContext(), adsCtxSource.getTrustedCertificates());
            }
          }
        }
@@ -9735,7 +9627,7 @@
    }
  }
  private InitialLdapContext getDirContextForServer(TopologyCache cache, ServerDescriptor server)
  private ConnectionWrapper getDirContextForServer(TopologyCache cache, ServerDescriptor server)
      throws NamingException
  {
    String dn = getBindDN(cache.getAdsContext().getDirContext());
@@ -9746,7 +9638,7 @@
    ServerLoader loader = new ServerLoader(server.getAdsProperties(),
        dn, pwd, getTrustManager(sourceServerCI), getConnectTimeout(),
        cache.getPreferredConnections(), filter);
    return loader.createContext();
    return loader.createConnectionWrapper();
  }
  /**
opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java
@@ -40,7 +40,6 @@
import javax.naming.AuthenticationException;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
@@ -54,6 +53,7 @@
import org.forgerock.opendj.config.client.ldap.LDAPManagementContext;
import org.forgerock.opendj.ldap.AuthorizationException;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.LdapException;
import org.forgerock.opendj.ldap.ResultCode;
@@ -75,7 +75,6 @@
import org.opends.guitools.controlpanel.util.ControlPanelLog;
import org.opends.guitools.controlpanel.util.Utilities;
import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.InitializationException;
import org.opends.server.types.NullOutputStream;
import org.opends.server.util.BuildVersion;
@@ -330,11 +329,9 @@
      if (mContext != null)
      {
        InitialLdapContext ctx = null;
        try {
          ctx = Utilities.getAdminDirContext(controlInfo, bindDn, bindPwd);
          controlInfo.setConnection(
              new ConnectionWrapper(ctx, controlInfo.getConnectTimeout(), controlInfo.getTrustManager()));
        try (ConnectionWrapper conn = Utilities.getAdminDirContext(controlInfo, bindDn, bindPwd))
        {
          controlInfo.setConnection(conn);
          controlInfo.regenerateDescriptor();
          writeStatus(controlInfo);
@@ -353,8 +350,6 @@
          println();
          println(cre.getMessageObject());
          return ReturnCode.ERROR_INITIALIZING_SERVER.get();
        } finally {
          StaticUtils.close(ctx);
        }
      } else {
        // The user did not provide authentication: just display the