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

Jean-Noël Rouvignac
01.45.2016 f3f9f37cd05c81867e2852746b169132d8f1b598
Partial OPENDJ-2625 Convert all code that uses JNDI to use the SDK instead

Passed ConnectionWrapper down several method calls.
Replaced uses of InitialLdapContext with ConnectionWrapper.
28 files modified
1195 ■■■■ changed files
opendj-server-legacy/src/main/java/org/opends/admin/ads/ADSContext.java 44 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/ADSContextHelper.java 25 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/ServerDescriptor.java 92 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionUtils.java 35 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java 89 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java 13 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java 2 ●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/BrowserController.java 50 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/LDAPConnectionPool.java 135 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/NodeRefresher.java 90 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java 64 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/DeleteEntryTask.java 33 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ModifyEntryTask.java 16 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/NewEntryTask.java 12 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java 24 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/Task.java 29 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/AbstractBrowseEntriesPanel.java 43 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/BrowseEntriesPanel.java 7 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/DuplicateEntryPanel.java 7 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/LDAPEntryReader.java 12 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java 103 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java 3 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/Application.java 3 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java 43 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/util/ServerController.java 180 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/quicksetup/util/Utils.java 7 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java 26 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java 8 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/admin/ads/ADSContext.java
@@ -274,7 +274,6 @@
  }
  /** The context used to retrieve information. */
  private final InitialLdapContext dirContext;
  private final ConnectionWrapper connectionWrapper;
  /**
@@ -286,7 +285,6 @@
  public ADSContext(ConnectionWrapper connectionWrapper)
  {
    this.connectionWrapper = connectionWrapper;
    this.dirContext = connectionWrapper.getLdapContext();
  }
  /**
@@ -296,7 +294,7 @@
   */
  public InitialLdapContext getDirContext()
  {
    return dirContext;
    return connectionWrapper.getLdapContext();
  }
  /**
@@ -339,7 +337,7 @@
      {
        createContainerEntry(getServerContainerDN());
      }
      dirContext.createSubcontext(dn, attrs).close();
      connectionWrapper.getLdapContext().createSubcontext(dn, attrs).close();
      if (serverProperties.containsKey(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE))
      {
        registerInstanceKeyCertificate(serverProperties, dn);
@@ -409,12 +407,12 @@
        Map<ServerProperty, Object> newServerProps = new HashMap<>(serverProperties);
        newServerProps.put(ServerProperty.ID, newServerId);
        LdapName newDn = makeDNFromServerProperties(newServerProps);
        dirContext.rename(dn, newDn);
        connectionWrapper.getLdapContext().rename(dn, newDn);
        dn = newDn;
        serverProperties.put(ServerProperty.ID, newServerId);
      }
      BasicAttributes attrs = makeAttrsFromServerProperties(serverProperties, false);
      dirContext.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
      connectionWrapper.getLdapContext().modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
      if (serverProperties.containsKey(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE))
      {
        registerInstanceKeyCertificate(serverProperties, dn);
@@ -464,7 +462,7 @@
        }
      }
      dirContext.destroySubcontext(dn);
      connectionWrapper.getLdapContext().destroySubcontext(dn);
    }
    catch (NameNotFoundException x)
    {
@@ -487,7 +485,7 @@
        String memberAttrName = ServerGroupProperty.MEMBERS.getAttributeName();
        String filter = "(" + memberAttrName + "=cn=" + serverID + ")";
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        ne = dirContext.search(getServerGroupContainerDN(), filter, sc);
        ne = connectionWrapper.getLdapContext().search(getServerGroupContainerDN(), filter, sc);
        while (ne.hasMore())
        {
          SearchResult sr = ne.next();
@@ -530,11 +528,11 @@
          newAttrs.put(newAttr);
          if (newAttr.size() > 0)
          {
            dirContext.modifyAttributes(groupDn, DirContext.REPLACE_ATTRIBUTE, newAttrs);
            connectionWrapper.getLdapContext().modifyAttributes(groupDn, DirContext.REPLACE_ATTRIBUTE, newAttrs);
          }
          else
          {
            dirContext.modifyAttributes(groupDn, DirContext.REMOVE_ATTRIBUTE, newAttrs);
            connectionWrapper.getLdapContext().modifyAttributes(groupDn, DirContext.REMOVE_ATTRIBUTE, newAttrs);
          }
        }
      }
@@ -708,7 +706,7 @@
      SearchControls sc = new SearchControls();
      sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      ne = dirContext.search(getServerContainerDN(), "(objectclass=*)", sc);
      ne = connectionWrapper.getLdapContext().search(getServerContainerDN(), "(objectclass=*)", sc);
      while (ne.hasMore())
      {
        SearchResult sr = ne.next();
@@ -724,7 +722,8 @@
            final String attrIDs[] = { "ds-cfg-public-key-certificate;binary" };
            sc1.setReturningAttributes(attrIDs);
            ne2 = dirContext.search(getInstanceKeysContainerDN(), "(ds-cfg-key-id=" + keyId + ")", sc);
            ne2 = connectionWrapper.getLdapContext().search(
                getInstanceKeysContainerDN(), "(ds-cfg-key-id=" + keyId + ")", sc);
            boolean found = false;
            while (ne2.hasMore())
            {
@@ -789,7 +788,7 @@
    attrs.put(oc);
    try
    {
      DirContext ctx = dirContext.createSubcontext(dn, attrs);
      DirContext ctx = connectionWrapper.getLdapContext().createSubcontext(dn, attrs);
      ctx.close();
    }
    catch (NameAlreadyBoundException x)
@@ -826,7 +825,7 @@
        {
          // Rename to entry
          LdapName newDN = nameFromDN("cn=" + Rdn.escapeValue(newGroupId) + "," + getServerGroupContainerDN());
          dirContext.rename(dn, newDN);
          connectionWrapper.getLdapContext().rename(dn, newDN);
          dn = newDN;
        }
@@ -840,7 +839,7 @@
      BasicAttributes attrs = makeAttrsFromServerGroupProperties(serverGroupProperties);
      // attribute modification
      dirContext.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
      connectionWrapper.getLdapContext().modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
    }
    catch (NameNotFoundException x)
    {
@@ -871,7 +870,7 @@
    {
      SearchControls sc = new SearchControls();
      sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      ne = dirContext.search(getServerGroupContainerDN(), "(objectclass=*)", sc);
      ne = connectionWrapper.getLdapContext().search(getServerGroupContainerDN(), "(objectclass=*)", sc);
      while (ne.hasMore())
      {
        SearchResult sr = ne.next();
@@ -914,7 +913,7 @@
      sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      String[] attList = { "cn", "userpassword", "ds-privilege-name", "description" };
      sc.setReturningAttributes(attList);
      ne = dirContext.search(getAdministratorContainerDN(), "(objectclass=*)", sc);
      ne = connectionWrapper.getLdapContext().search(getAdministratorContainerDN(), "(objectclass=*)", sc);
      while (ne.hasMore())
      {
        SearchResult sr = ne.next();
@@ -1019,7 +1018,7 @@
    try
    {
      Control[] controls = new Control[] { new SubtreeDeleteControl() };
      LdapContext tmpContext = dirContext.newInstance(controls);
      LdapContext tmpContext = connectionWrapper.getLdapContext().newInstance(controls);
      try
      {
        for (String dn : dns)
@@ -1102,7 +1101,7 @@
    try
    {
      DirContext ctx = dirContext.createSubcontext(dnCentralAdmin, attrs);
      DirContext ctx = connectionWrapper.getLdapContext().createSubcontext(dnCentralAdmin, attrs);
      ctx.close();
    }
    catch (NameAlreadyBoundException x)
@@ -1133,7 +1132,7 @@
    try
    {
      dirContext.destroySubcontext(dnCentralAdmin);
      connectionWrapper.getLdapContext().destroySubcontext(dnCentralAdmin);
    }
    catch (NameNotFoundException | NotContextException x)
    {
@@ -2112,7 +2111,7 @@
      throws ADSContextException
  {
    ADSContextHelper helper = new ADSContextHelper();
    helper.registerInstanceKeyCertificate(dirContext, serverProperties, serverEntryDn);
    helper.registerInstanceKeyCertificate(connectionWrapper, serverProperties, serverEntryDn);
  }
  /**
@@ -2145,7 +2144,8 @@
          { ADSContext.ServerProperty.INSTANCE_KEY_ID.getAttributeName(),
            ADSContext.ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE.getAttributeName() + ";binary" };
      searchControls.setReturningAttributes(attrIDs);
      NamingEnumeration<SearchResult> keyEntries = dirContext.search(baseDN, searchFilter, searchControls);
      NamingEnumeration<SearchResult> keyEntries =
          connectionWrapper.getLdapContext().search(baseDN, searchFilter, searchControls);
      try
      {
        while (keyEntries.hasMore())
opendj-server-legacy/src/main/java/org/opends/admin/ads/ADSContextHelper.java
@@ -25,23 +25,23 @@
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import org.opends.admin.ads.ADSContext.ServerProperty;
import org.opends.admin.ads.ADSContextException.ErrorType;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.forgerock.opendj.config.ManagedObjectNotFoundException;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.server.config.client.LDIFBackendCfgClient;
import org.forgerock.opendj.server.config.client.RootCfgClient;
import org.forgerock.opendj.server.config.meta.BackendCfgDefn;
import org.forgerock.opendj.server.config.meta.LDIFBackendCfgDefn;
import org.opends.admin.ads.ADSContext.ServerProperty;
import org.opends.admin.ads.ADSContextException.ErrorType;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.server.config.ConfigConstants;
import org.opends.server.crypto.CryptoManagerImpl;
import org.opends.server.types.CryptoManagerException;
import org.forgerock.opendj.ldap.DN;
/**
 * This is the only class in the org.opends.admin.ads package that uses the
@@ -61,7 +61,7 @@
  /**
   * Creates the Administration Suffix.
   * @param ctx the DirContext to be used.
   * @param conn the connection to be used.
   * @param backendName the name of the backend where the administration
   * suffix is stored.
   * @throws ADSContextException if the administration suffix could not be
@@ -120,7 +120,7 @@
  expected); add an instance key public-key certificate entry for the key
  certificate; and associate the certificate entry with the server entry via
  the key ID attribute.
  @param ctx the InitialLdapContext on the server we want to update.
  @param conn the connection on the server we want to update.
  @param serverProperties Properties of the server being registered to which
  the instance key entry belongs.
  @param serverEntryDn The server's ADS entry DN.
@@ -128,7 +128,7 @@
  problem getting the instance public key certificate ID.
   */
  void registerInstanceKeyCertificate(
      InitialLdapContext ctx, Map<ServerProperty, Object> serverProperties,
      ConnectionWrapper conn, Map<ServerProperty, Object> serverProperties,
      LdapName serverEntryDn)
  throws ADSContextException {
    assert serverProperties.containsKey(
@@ -162,8 +162,7 @@
    NamingEnumeration<SearchResult> results = null;
    try
    {
      results = ctx.search(ADSContext.getInstanceKeysContainerDN(), keyAttrs,
         attrIDs);
      results = conn.getLdapContext().search(ADSContext.getInstanceKeysContainerDN(), keyAttrs, attrIDs);
      boolean found = false;
      while (results.hasMore()) {
        final Attribute keyIdAttr =
@@ -194,14 +193,14 @@
        final LdapName keyDn = new LdapName(
            ServerProperty.INSTANCE_KEY_ID.getAttributeName() + "=" + Rdn.escapeValue(keyID)
                + "," + ADSContext.getInstanceKeysContainerDN());
        ctx.createSubcontext(keyDn, keyAttrs).close();
        conn.getLdapContext().createSubcontext(keyDn, keyAttrs).close();
      }
      if (serverEntryDn != null)
      {
        /* associate server entry with certificate entry via key ID attribute */
        ctx.modifyAttributes(serverEntryDn,
          InitialLdapContext.REPLACE_ATTRIBUTE,
        conn.getLdapContext().modifyAttributes(serverEntryDn,
          DirContext.REPLACE_ATTRIBUTE,
          new BasicAttributes(ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyID));
      }
    }
opendj-server-legacy/src/main/java/org/opends/admin/ads/ServerDescriptor.java
@@ -37,13 +37,12 @@
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
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.admin.ads.util.ConnectionWrapper;
import org.opends.quicksetup.Constants;
import org.opends.server.config.ConfigConstants;
import org.opends.server.types.HostPort;
@@ -635,37 +634,32 @@
  /**
   * Creates a ServerDescriptor object based on the configuration that we read
   * using the provided InitialLdapContext.
   * @param ctx the InitialLdapContext that will be used to read the
   * configuration of the server.
   * using the provided connection.
   * @param conn the connection that will be used to read the configuration of the server.
   * @param filter the topology cache filter describing the information that
   * must be retrieved.
   * @return a ServerDescriptor object that corresponds to the read
   * configuration.
   * @throws NamingException if a problem occurred reading the server
   * configuration.
   * @return a ServerDescriptor object that corresponds to the read configuration.
   * @throws NamingException if a problem occurred reading the server configuration.
   */
  public static ServerDescriptor createStandalone(InitialLdapContext ctx,
      TopologyCacheFilter filter)
  public static ServerDescriptor createStandalone(ConnectionWrapper conn, TopologyCacheFilter filter)
  throws NamingException
  {
    ServerDescriptor desc = new ServerDescriptor();
    updateLdapConfiguration(desc, ctx);
    updateAdminConnectorConfiguration(desc, ctx);
    updateJmxConfiguration(desc, ctx);
    updateReplicas(desc, ctx, filter);
    updateReplication(desc, ctx, filter);
    updatePublicKeyCertificate(desc, ctx);
    updateMiscellaneous(desc, ctx);
    updateLdapConfiguration(desc, conn);
    updateAdminConnectorConfiguration(desc, conn);
    updateJmxConfiguration(desc, conn);
    updateReplicas(desc, conn, filter);
    updateReplication(desc, conn, filter);
    updatePublicKeyCertificate(desc, conn);
    updateMiscellaneous(desc, conn);
    desc.serverProperties.put(ServerProperty.HOST_NAME,
        ConnectionUtils.getHostName(ctx));
    desc.serverProperties.put(ServerProperty.HOST_NAME, conn.getHostPort().getHost());
    return desc;
  }
  private static void updateLdapConfiguration(ServerDescriptor desc, InitialLdapContext ctx)
  private static void updateLdapConfiguration(ServerDescriptor desc, ConnectionWrapper conn)
      throws NamingException
  {
    SearchControls ctls = new SearchControls();
@@ -683,7 +677,7 @@
    LdapName jndiName = new LdapName("cn=config");
    NamingEnumeration<SearchResult> listeners =
      ctx.search(jndiName, filter, ctls);
      conn.getLdapContext().search(jndiName, filter, ctls);
    try
    {
@@ -733,7 +727,7 @@
    }
  }
  private static void updateAdminConnectorConfiguration(ServerDescriptor desc, InitialLdapContext ctx)
  private static void updateAdminConnectorConfiguration(ServerDescriptor desc, ConnectionWrapper conn)
      throws NamingException
  {
    SearchControls ctls = new SearchControls();
@@ -747,7 +741,7 @@
    LdapName jndiName = new LdapName("cn=config");
    NamingEnumeration<SearchResult> listeners =
      ctx.search(jndiName, filter, ctls);
      conn.getLdapContext().search(jndiName, filter, ctls);
    try
    {
@@ -778,7 +772,7 @@
    }
  }
  private static void updateJmxConfiguration(ServerDescriptor desc, InitialLdapContext ctx) throws NamingException
  private static void updateJmxConfiguration(ServerDescriptor desc, ConnectionWrapper conn) throws NamingException
  {
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
@@ -794,7 +788,7 @@
    LdapName jndiName = new LdapName("cn=config");
    NamingEnumeration<SearchResult> listeners =
      ctx.search(jndiName, filter, ctls);
      conn.getLdapContext().search(jndiName, filter, ctls);
    ArrayList<Integer> jmxPorts = new ArrayList<>();
    ArrayList<Integer> jmxsPorts = new ArrayList<>();
@@ -839,7 +833,7 @@
  }
  private static void updateReplicas(ServerDescriptor desc,
      InitialLdapContext ctx, TopologyCacheFilter cacheFilter)
      ConnectionWrapper conn, TopologyCacheFilter cacheFilter)
  throws NamingException
  {
    if (!cacheFilter.searchBaseDNInformation())
@@ -858,7 +852,7 @@
    LdapName jndiName = new LdapName("cn=config");
    NamingEnumeration<SearchResult> databases =
      ctx.search(jndiName, filter, ctls);
      conn.getLdapContext().search(jndiName, filter, ctls);
    try
    {
@@ -875,7 +869,7 @@
          Set<String> entries;
          if (cacheFilter.searchMonitoringInformation())
          {
            entries = getBaseDNEntryCount(ctx, id);
            entries = getBaseDNEntryCount(conn, id);
          }
          else
          {
@@ -950,7 +944,7 @@
  }
  private static void updateReplication(ServerDescriptor desc,
      InitialLdapContext ctx, TopologyCacheFilter cacheFilter)
      ConnectionWrapper conn, TopologyCacheFilter cacheFilter)
  throws NamingException
  {
    boolean replicationEnabled = false;
@@ -968,7 +962,7 @@
    try
    {
      syncProviders = ctx.search(jndiName, filter, ctls);
      syncProviders = conn.getLdapContext().search(jndiName, filter, ctls);
      while(syncProviders.hasMore())
      {
@@ -1015,7 +1009,7 @@
      syncProviders = null;
      try
      {
        syncProviders = ctx.search(jndiName, filter, ctls);
        syncProviders = conn.getLdapContext().search(jndiName, filter, ctls);
        while(syncProviders.hasMore())
        {
@@ -1077,7 +1071,7 @@
    NamingEnumeration<SearchResult> entries = null;
    try
    {
      entries = ctx.search(jndiName, filter, ctls);
      entries = conn.getLdapContext().search(jndiName, filter, ctls);
      while (entries.hasMore())
      {
@@ -1127,7 +1121,7 @@
      jndiName = new LdapName("cn=Crypto Manager,cn=config");
      entries = ctx.search(jndiName, filter, ctls);
      entries = conn.getLdapContext().search(jndiName, filter, ctls);
      try
      {
@@ -1157,11 +1151,11 @@
   ADS.
   @param desc The map to update with the instance key-pair public-key
   certificate.
   @param ctx The bound server instance.
   @param conn The connection to the server.
   @throws NamingException if unable to retrieve certificate from bound
   instance.
   */
  private static void updatePublicKeyCertificate(ServerDescriptor desc, InitialLdapContext ctx) throws NamingException
  private static void updatePublicKeyCertificate(ServerDescriptor desc, ConnectionWrapper conn) 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. */
@@ -1176,7 +1170,7 @@
        searchControls.setSearchScope(SearchControls.OBJECT_SCOPE);
        final String attrIDs[] = { "ds-cfg-public-key-certificate;binary" };
        searchControls.setReturningAttributes(attrIDs);
        final SearchResult certEntry = ctx.search(dn,
        final SearchResult certEntry = conn.getLdapContext().search(dn,
                   "(objectclass=ds-cfg-instance-key)", searchControls).next();
        final Attribute certAttr = certEntry.getAttributes().get(attrIDs[0]);
        if (null != certAttr) {
@@ -1195,7 +1189,7 @@
          oc.add("top");
          oc.add("ds-cfg-self-signed-cert-request");
          attrs.put(oc);
          ctx.createSubcontext(dn, attrs).close();
          conn.getLdapContext().createSubcontext(dn, attrs).close();
        }
        else {
          throw x;
@@ -1204,7 +1198,7 @@
    }
  }
  private static void updateMiscellaneous(ServerDescriptor desc, InitialLdapContext ctx) throws NamingException
  private static void updateMiscellaneous(ServerDescriptor desc, ConnectionWrapper conn) throws NamingException
  {
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
@@ -1216,7 +1210,7 @@
    LdapName jndiName = new LdapName("cn=schema");
    NamingEnumeration<SearchResult> listeners =
      ctx.search(jndiName, filter, ctls);
      conn.getLdapContext().search(jndiName, filter, ctls);
    try
    {
@@ -1241,7 +1235,7 @@
   certificates. This trust is necessary at least to initialize replication,
   which uses the trusted certificate entries in the ads-truststore for server
   authentication.
   @param ctx The bound instance.
   @param conn The connection to the server.
   @param keyEntryMap The set of valid (i.e., not tagged as compromised)
   instance key-pair public-key certificate entries in ADS represented as a map
   from keyID to public-key certificate (binary).
@@ -1249,7 +1243,7 @@
   ads-truststore via LDAP.
   */
  public static void seedAdsTrustStore(
          InitialLdapContext ctx,
          ConnectionWrapper conn,
          Map<String, byte[]> keyEntryMap)
          throws NamingException
  {
@@ -1270,24 +1264,24 @@
                      getAttributeName() + ";binary", keyEntry.getValue()));
      final LdapName keyDn = new LdapName(rdnAttr.getID() + "=" + Rdn.escapeValue(rdnAttr.get()) + "," + TRUSTSTORE_DN);
      try {
        ctx.createSubcontext(keyDn, keyAttrs).close();
        conn.getLdapContext().createSubcontext(keyDn, keyAttrs).close();
      }
      catch(NameAlreadyBoundException x){
        ctx.destroySubcontext(keyDn);
        ctx.createSubcontext(keyDn, keyAttrs).close();
        conn.getLdapContext().destroySubcontext(keyDn);
        conn.getLdapContext().createSubcontext(keyDn, keyAttrs).close();
      }
    }
  }
  /**
   * Returns the values of the ds-base-dn-entry count attributes for the given
   * backend monitor entry using the provided InitialLdapContext.
   * @param ctx the InitialLdapContext to use to update the configuration.
   * backend monitor entry using the provided connection.
   * @param conn the connection to use to update the configuration.
   * @param backendID the id of the backend.
   * @return the values of the ds-base-dn-entry count attribute.
   * @throws NamingException if there was an error.
   */
  private static Set<String> getBaseDNEntryCount(InitialLdapContext ctx,
  private static Set<String> getBaseDNEntryCount(ConnectionWrapper conn,
      String backendID) throws NamingException
  {
    LinkedHashSet<String> v = new LinkedHashSet<>();
@@ -1301,7 +1295,7 @@
    LdapName jndiName = new LdapName("cn=monitor");
    NamingEnumeration<SearchResult> listeners =
      ctx.search(jndiName, filter, ctls);
      conn.getLdapContext().search(jndiName, filter, ctls);
    try
    {
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionUtils.java
@@ -31,7 +31,6 @@
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.StartTlsRequest;
import javax.naming.ldap.StartTlsResponse;
@@ -212,7 +211,7 @@
  /**
   * Clones the provided InitialLdapContext and returns a connection using
   * the same parameters.
   * @param ctx the connection to be cloned.
   * @param conn the connection to be cloned.
   * @param timeout the timeout to establish the connection in milliseconds.
   * Use {@code 0} to express no timeout.
   * @param trustManager the trust manager to be used to connect.
@@ -220,41 +219,28 @@
   * @return the new InitialLdapContext connected to the server.
   * @throws NamingException if there was an error creating the new connection.
   */
  public static InitialLdapContext cloneInitialLdapContext(
      final InitialLdapContext ctx, int timeout, TrustManager trustManager,
  public static ConnectionWrapper cloneConnectionWrapper(
      final ConnectionWrapper conn, int timeout, TrustManager trustManager,
      KeyManager keyManager) throws NamingException
  {
    Hashtable<?, ?> env = ctx.getEnvironment();
    Control[] ctls = ctx.getConnectControls();
    Control[] newCtls = null;
    if (ctls != null)
    {
      newCtls = new Control[ctls.length];
      System.arraycopy(ctls, 0, newCtls, 0, ctls.length);
    }
    /* Contains the DirContext and the Exception if any */
    final Object[] pair = new Object[] {null, null};
    final Hashtable<?, ?> fEnv = env;
    final TrustManager fTrustManager = trustManager;
    final KeyManager   fKeyManager   = keyManager;
    final Control[] fNewCtls = newCtls;
    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          if (isSSL(ctx) || isStartTLS(ctx))
          if (conn.isSSL() || conn.isStartTLS())
          {
            TrustedSocketFactory.setCurrentThreadTrustManager(fTrustManager,
                fKeyManager);
            TrustedSocketFactory.setCurrentThreadTrustManager(fTrustManager, fKeyManager);
          }
          pair[0] = new InitialLdapContext(fEnv, fNewCtls);
          pair[0] = new ConnectionWrapper(conn);
        } catch (NamingException | RuntimeException ne) {
          pair[1] = ne;
        }
      }
    });
    return getInitialLdapContext(t, pair, timeout);
    return ConnectionUtils.<ConnectionWrapper> getConnection(t, pair, timeout);
  }
  /**
@@ -540,6 +526,11 @@
  private static InitialLdapContext getInitialLdapContext(Thread t,
      Object[] pair, int timeout) throws NamingException
  {
    return ConnectionUtils.<InitialLdapContext> getConnection(t, pair, timeout);
  }
  private static <T> T getConnection(Thread t, Object[] pair, int timeout) throws NamingException
  {
    try
    {
      if (timeout > 0)
@@ -601,7 +592,7 @@
            (Throwable) pair[1]);
      }
    }
    return (InitialLdapContext) pair[0];
    return (T) pair[0];
  }
  /**
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java
@@ -69,6 +69,7 @@
  private final int connectTimeout;
  private final TrustManager trustManager;
  private final KeyManager keyManager;
  private Type connectionType;
  /**
   * Creates a connection wrapper.
@@ -89,12 +90,21 @@
   *           If an error occurs
   */
  public ConnectionWrapper(String ldapUrl, Type connectionType, String bindDn, String bindPwd, int connectTimeout,
      ApplicationTrustManager trustManager) throws NamingException
      TrustManager trustManager) throws NamingException
  {
    this(toHostPort(ldapUrl), connectionType, bindDn, bindPwd, connectTimeout, trustManager);
    this(toHostPort(ldapUrl), connectionType, bindDn, bindPwd, connectTimeout, trustManager, null);
  }
  private static HostPort toHostPort(String ldapUrl) throws NamingException
  /**
   * Converts an ldapUrl to a HostPort.
   *
   * @param ldapUrl
   *          the ldapUrl to convert
   * @return the host and port extracted from the ldapUrl
   * @throws NamingException
   *           if the ldapUrl is not a valid URL
   */
  public static HostPort toHostPort(String ldapUrl) throws NamingException
  {
    try
    {
@@ -132,6 +142,20 @@
  }
  /**
   * Creates a connection wrapper by copying the provided one.
   *
   * @param other
   *          the {@link ConnectionWrapper} to copy
   * @throws NamingException
   *           If an error occurs
   */
  public ConnectionWrapper(ConnectionWrapper other) throws NamingException
  {
    this(other.hostPort, other.connectionType, other.bindDn.toString(), other.bindPwd, other.connectTimeout,
        other.trustManager, other.keyManager);
  }
  /**
   * Creates a connection wrapper.
   *
   * @param hostPort
@@ -155,6 +179,7 @@
      int connectTimeout, TrustManager trustManager, KeyManager keyManager) throws NamingException
  {
    this.hostPort = hostPort;
    this.connectionType = connectionType;
    this.bindDn = DN.valueOf(bindDn);
    this.bindPwd = bindPwd;
    this.connectTimeout = connectTimeout;
@@ -162,7 +187,7 @@
    this.keyManager = keyManager;
    final Options options = toOptions(connectionType, bindDn, bindPwd, connectTimeout, trustManager, keyManager);
    ldapContext = createAdministrativeContext(options, bindDn, bindPwd);
    ldapContext = createAdministrativeContext(options);
    connectionFactory = new LDAPConnectionFactory(hostPort.getHost(), hostPort.getPort(), options);
    connection = buildConnection();
  }
@@ -222,19 +247,38 @@
  }
  /**
   * Returns the LDAP URL used by the InitialLdapContext.
   * Returns the LDAP URL used by this connection.
   *
   * @return the LDAP URL used by the InitialLdapContext.
   * @return the LDAP URL used by this connection.
   */
  public String getLdapUrl()
  {
    return ConnectionUtils.getLdapUrl(ldapContext);
  }
  private InitialLdapContext createAdministrativeContext(Options options, String bindDn, String bindPwd)
      throws NamingException
  /**
   * Returns whether this connection uses SSL.
   *
   * @return {@code true} if this connection uses SSL {@code false} otherwise.
   */
  public boolean isSSL()
  {
    final InitialLdapContext ctx = createAdministrativeContext0(options, bindDn, bindPwd);
    return ConnectionUtils.isSSL(ldapContext);
  }
  /**
   * Returns whether this connection uses StartTLS.
   *
   * @return {@code true} if this connection uses StartTLS {@code false} otherwise.
   */
  public boolean isStartTLS()
  {
    return ConnectionUtils.isStartTLS(ldapContext);
  }
  private InitialLdapContext createAdministrativeContext(Options options) throws NamingException
  {
    final InitialLdapContext ctx = createAdministrativeContext0(options);
    if (!connectedAsAdministrativeUser(ctx))
    {
      throw new NoPermissionException(ERR_NOT_ADMINISTRATIVE_USER.get().toString());
@@ -242,24 +286,21 @@
    return ctx;
  }
  private InitialLdapContext createAdministrativeContext0(Options options, String bindDn, String bindPwd)
      throws NamingException
  private InitialLdapContext createAdministrativeContext0(Options options) throws NamingException
  {
    SSLContext sslContext = options.get(SSL_CONTEXT);
    boolean useSSL = sslContext != null;
    boolean useStartTLS = options.get(SSL_USE_STARTTLS);
    boolean useSSL = options.get(SSL_CONTEXT) != null;
    final String ldapUrl = getLDAPUrl(getHostPort(), useSSL);
    if (useSSL)
    final String bindDnStr = bindDn.toString();
    switch (connectionType)
    {
      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);
    case LDAPS:
      return createLdapsContext(ldapUrl, bindDnStr, bindPwd, connectTimeout, null, trustManager, keyManager);
    case START_TLS:
      return createStartTLSContext(ldapUrl, bindDnStr, bindPwd, connectTimeout, null, trustManager, keyManager, null);
    case LDAP:
      return createLdapContext(ldapUrl, bindDnStr, bindPwd, connectTimeout, null);
    default:
      throw new RuntimeException("Not implemented for connection type: " + connectionType);
    }
  }
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java
@@ -19,8 +19,6 @@
import java.util.Collections;
import java.util.Set;
import javax.naming.ldap.InitialLdapContext;
/**
 * A simple class that is used to be able to specify which URL and connection
 * type to use when we connect to a server.
@@ -95,20 +93,19 @@
  /**
   * Commodity method that returns a PreferredConnection object with the
   * information on a given InitialLdapContext.
   * information on a given connection.
   * @param conn the connection we retrieve the information from.
   * @return a preferred connection object.
   */
  private static PreferredConnection getPreferredConnection(ConnectionWrapper conn)
  {
    InitialLdapContext ctx = conn.getLdapContext();
    String ldapUrl = ConnectionUtils.getLdapUrl(ctx);
    String ldapUrl = conn.getLdapUrl();
    PreferredConnection.Type type;
    if (ConnectionUtils.isStartTLS(ctx))
    if (conn.isStartTLS())
    {
      type = PreferredConnection.Type.START_TLS;
    }
    else if (ConnectionUtils.isSSL(ctx))
    else if (conn.isSSL())
    {
      type = PreferredConnection.Type.LDAPS;
    }
@@ -121,7 +118,7 @@
  /**
   * Commodity method that generates a list of preferred connection (of just
   * one) with the information on a given InitialLdapContext.
   * one) with the information on a given connection.
   * @param conn the connection we retrieve the information from.
   * @return a list containing the preferred connection object.
   */
opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java
@@ -148,7 +148,7 @@
    try (ConnectionWrapper conn = createConnectionWrapper())
    {
      connCreated = true;
      serverDescriptor = ServerDescriptor.createStandalone(conn.getLdapContext(), filter);
      serverDescriptor = ServerDescriptor.createStandalone(conn, filter);
      serverDescriptor.setAdsProperties(serverProperties);
      serverDescriptor.updateAdsPropertiesWithServerProperties();
    }
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/BrowserController.java
@@ -16,6 +16,9 @@
 */
package org.opends.guitools.controlpanel.browser;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.server.util.ServerConstants.*;
import java.awt.Font;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@@ -34,7 +37,6 @@
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.ManageReferralControl;
import javax.naming.ldap.SortControl;
import javax.naming.ldap.SortKey;
@@ -66,9 +68,6 @@
import org.opends.server.types.HostPort;
import org.opends.server.types.LDAPURL;
import static org.opends.admin.ads.util.ConnectionUtils.isSSL;
import static org.opends.server.util.ServerConstants.*;
/**
 * This is the main class of the LDAP entry browser.  It is in charge of
 * updating a tree that is passed as parameter.  Every instance of
@@ -108,8 +107,7 @@
  private String displayAttribute;
  private final boolean showAttributeName;
  private ConnectionWrapper connConfig;
  private InitialLdapContext ctxConfiguration;
  private InitialLdapContext ctxUserData;
  private ConnectionWrapper connUserData;
  private boolean followReferrals;
  private boolean sorted;
  private boolean showContainerOnly;
@@ -178,22 +176,22 @@
   * @param server the server descriptor.
   * @param connConfiguration the connection to be used to retrieve the data in
   * the configuration base DNs.
   * @param ctxUserData the connection to be used to retrieve the data in the
   * @param connUserData the connection to be used to retrieve the data in the
   * user base DNs.
   * @throws NamingException if an error occurs.
   */
  public void setConnections(
      ServerDescriptor server,
      ConnectionWrapper connConfiguration,
      InitialLdapContext ctxUserData) throws NamingException {
      ConnectionWrapper connUserData) throws NamingException {
    String rootNodeName;
    if (connConfiguration != null)
    {
      this.connConfig = connConfiguration;
      this.ctxUserData = ctxUserData;
      this.connUserData = connUserData;
      connConfig.getLdapContext().setRequestControls(getConfigurationRequestControls());
      this.ctxUserData.setRequestControls(getRequestControls());
      connUserData.getLdapContext().setRequestControls(getRequestControls());
      rootNodeName = new HostPort(server.getHostname(), connConfig.getHostPort().getPort()).toString();
    }
    else {
@@ -208,16 +206,16 @@
   * Return the connection for accessing the directory configuration.
   * @return the connection for accessing the directory configuration.
   */
  public InitialLdapContext getConfigurationConnection() {
    return connConfig.getLdapContext();
  public ConnectionWrapper getConfigurationConnection() {
    return connConfig;
  }
  /**
   * Return the connection for accessing the directory user data.
   * @return the connection for accessing the directory user data.
   */
  public InitialLdapContext getUserDataConnection() {
    return ctxUserData;
  public ConnectionWrapper getUserDataConnection() {
    return connUserData;
  }
@@ -418,7 +416,7 @@
    stopRefresh();
    removeAllChildNodes(rootNode, true /* Keep suffixes */);
    connConfig.getLdapContext().setRequestControls(getConfigurationRequestControls());
    ctxUserData.setRequestControls(getRequestControls());
    connUserData.getLdapContext().setRequestControls(getRequestControls());
    connectionPool.setRequestControls(getRequestControls());
    startRefresh(null);
  }
@@ -446,7 +444,7 @@
    removeAllChildNodes(rootNode, true /* Keep suffixes */);
    this.sorted = sorted;
    connConfig.getLdapContext().setRequestControls(getConfigurationRequestControls());
    ctxUserData.setRequestControls(getRequestControls());
    connUserData.getLdapContext().setRequestControls(getRequestControls());
    connectionPool.setRequestControls(getRequestControls());
    startRefresh(null);
  }
@@ -922,7 +920,7 @@
   * @throws NamingException if there is an error retrieving the connection.
   * @return the LDAP connection to reading the base entry of a node.
   */
  InitialLdapContext findConnectionForLocalEntry(BasicNode node)
  ConnectionWrapper findConnectionForLocalEntry(BasicNode node)
  throws NamingException {
    return findConnectionForLocalEntry(node, isConfigurationNode(node));
  }
@@ -934,11 +932,11 @@
   * @throws NamingException if there is an error retrieving the connection.
   * @return the LDAP connection to reading the base entry of a node.
   */
  private InitialLdapContext findConnectionForLocalEntry(BasicNode node,
  private ConnectionWrapper findConnectionForLocalEntry(BasicNode node,
      boolean isConfigurationNode) throws NamingException
  {
    if (node == rootNode) {
      return connConfig.getLdapContext();
      return connConfig;
    }
    final BasicNode parent = (BasicNode) node.getParent();
@@ -946,7 +944,7 @@
    {
      return findConnectionForDisplayedEntry(parent, isConfigurationNode);
    }
    return isConfigurationNode ? connConfig.getLdapContext() : ctxUserData;
    return isConfigurationNode ? connConfig : connUserData;
  }
  /**
@@ -987,7 +985,7 @@
   * @return the LDAP connection to search the displayed entry.
   * @throws NamingException if there is an error retrieving the connection.
   */
  public InitialLdapContext findConnectionForDisplayedEntry(BasicNode node)
  public ConnectionWrapper findConnectionForDisplayedEntry(BasicNode node)
  throws NamingException {
    return findConnectionForDisplayedEntry(node, isConfigurationNode(node));
  }
@@ -1001,7 +999,7 @@
   * @return the LDAP connection to search the displayed entry.
   * @throws NamingException if there is an error retrieving the connection.
   */
  private InitialLdapContext findConnectionForDisplayedEntry(BasicNode node,
  private ConnectionWrapper findConnectionForDisplayedEntry(BasicNode node,
      boolean isConfigurationNode) throws NamingException {
    if (followReferrals && node.getRemoteUrl() != null)
    {
@@ -1015,13 +1013,13 @@
  /**
   * Release a connection returned by selectConnectionForChildEntries() or
   * selectConnectionForBaseEntry().
   * @param ctx the connection to be released.
   * @param conn the connection to be released.
   */
  void releaseLDAPConnection(InitialLdapContext ctx) {
    if (ctx != connConfig.getLdapContext() && ctx != this.ctxUserData)
  void releaseLDAPConnection(ConnectionWrapper conn) {
    if (conn != connConfig && conn != connUserData)
    {
      // Thus it comes from the connection pool
      connectionPool.releaseConnection(ctx);
      connectionPool.releaseConnection(conn);
    }
  }
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/LDAPConnectionPool.java
@@ -16,26 +16,26 @@
 */
package org.opends.guitools.controlpanel.browser;
import static org.opends.admin.ads.util.PreferredConnection.Type.*;
import java.util.ArrayList;
import java.util.HashMap;
import javax.naming.NamingException;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.net.ssl.KeyManager;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.SearchScope;
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.event.ReferralAuthenticationListener;
import org.opends.server.types.HostPort;
import org.opends.server.types.LDAPURL;
import com.forgerock.opendj.cli.CliConstants;
import static org.opends.admin.ads.util.ConnectionUtils.*;
/**
 * An LDAPConnectionPool is a pool of LDAPConnection.
 * <BR><BR>
@@ -77,22 +77,21 @@
  /**
   * Returns <CODE>true</CODE> if the connection passed is registered in the
   * connection pool, <CODE>false</CODE> otherwise.
   * @param ctx the connection.
   * @param conn the connection.
   * @return <CODE>true</CODE> if the connection passed is registered in the
   * connection pool, <CODE>false</CODE> otherwise.
   */
  public boolean isConnectionRegistered(InitialLdapContext ctx) {
  public boolean isConnectionRegistered(ConnectionWrapper conn) {
    for (String key : connectionTable.keySet())
    {
      ConnectionRecord cr = connectionTable.get(key);
      HostPort hostPort = getHostPort(ctx);
      HostPort crHostPort = getHostPort(cr.ctx);
      if (cr.ctx != null
          && hostPort.equals(crHostPort)
          && getBindDN(cr.ctx).equals(getBindDN(ctx))
          && getBindPassword(cr.ctx).equals(getBindPassword(ctx))
          && isSSL(cr.ctx) == isSSL(ctx)
          && isStartTLS(cr.ctx) == isStartTLS(ctx)) {
      if (cr.conn != null
          && conn.getHostPort().equals(cr.conn.getHostPort())
          && cr.conn.getBindDn().equals(conn.getBindDn())
          && cr.conn.getBindPassword().equals(conn.getBindPassword())
          && cr.conn.isSSL() == conn.isSSL()
          && cr.conn.isStartTLS() == conn.isStartTLS())
      {
        return true;
      }
    }
@@ -101,14 +100,14 @@
  /**
   * Registers a connection in this connection pool.
   * @param ctx the connection to be registered.
   * @param conn the connection to be registered.
   */
  public void registerConnection(InitialLdapContext ctx) {
    registerAuth(ctx);
    LDAPURL url = makeLDAPUrl(ctx);
  public void registerConnection(ConnectionWrapper conn) {
    registerAuth(conn);
    LDAPURL url = makeLDAPUrl(conn);
    String key = makeKeyFromLDAPUrl(url);
    ConnectionRecord cr = new ConnectionRecord();
    cr.ctx = ctx;
    cr.conn = conn;
    cr.counter = 1;
    cr.disconnectAfterUse = false;
    connectionTable.put(key, cr);
@@ -116,13 +115,16 @@
  /**
   * Unregisters a connection from this connection pool.
   * @param ctx the connection to be unregistered.
   * @throws NamingException if there is a problem unregistering the connection.
   *
   * @param conn
   *          the connection to be unregistered.
   * @throws NamingException
   *           if there is a problem unregistering the connection.
   */
  public void unregisterConnection(InitialLdapContext ctx)
  public void unregisterConnection(ConnectionWrapper conn)
  throws NamingException
  {
    LDAPURL url = makeLDAPUrl(ctx);
    LDAPURL url = makeLDAPUrl(conn);
    unRegisterAuth(url);
    String key = makeKeyFromLDAPUrl(url);
    connectionTable.remove(key);
@@ -154,7 +156,7 @@
   * @return a connection to the provided LDAP URL.
   * @throws NamingException if there was an error connecting.
   */
  public InitialLdapContext getConnection(LDAPURL ldapUrl)
  public ConnectionWrapper getConnection(LDAPURL ldapUrl)
  throws NamingException {
    String key = makeKeyFromLDAPUrl(ldapUrl);
    ConnectionRecord cr;
@@ -163,7 +165,7 @@
      cr = connectionTable.get(key);
      if (cr == null) {
        cr = new ConnectionRecord();
        cr.ctx = null;
        cr.conn = null;
        cr.counter = 1;
        cr.disconnectAfterUse = false;
        connectionTable.put(key, cr);
@@ -175,7 +177,7 @@
    synchronized(cr) {
      try {
        if (cr.ctx == null) {
        if (cr.conn == null) {
          boolean registerAuth = false;
          AuthRecord authRecord = authTable.get(key);
          if (authRecord == null)
@@ -184,8 +186,8 @@
            authRecord = authTable.values().iterator().next();
            registerAuth = true;
          }
          cr.ctx = createLDAPConnection(ldapUrl, authRecord);
          cr.ctx.setRequestControls(requestControls);
          cr.conn = createLDAPConnection(ldapUrl, authRecord);
          cr.conn.getLdapContext().setRequestControls(requestControls);
          if (registerAuth)
          {
            authTable.put(key, authRecord);
@@ -203,7 +205,7 @@
      }
    }
    return cr.ctx;
    return cr.conn;
  }
  /**
@@ -218,28 +220,28 @@
    requestControls = ctls;
    for (ConnectionRecord cr : connectionTable.values())
    {
      if (cr.ctx != null)
      if (cr.conn != null)
      {
        cr.ctx.setRequestControls(requestControls);
        cr.conn.getLdapContext().setRequestControls(requestControls);
      }
    }
  }
  /**
   * Release an LDAPConnection created by getConnection().
   * The connection should be considered as virtually disconnected
   * and not be used anymore.
   * @param ctx the connection to be released.
   * Release an LDAPConnection created by getConnection(). The connection should be considered as
   * virtually disconnected and not be used anymore.
   *
   * @param conn
   *          the connection to be released.
   */
  public synchronized void releaseConnection(InitialLdapContext ctx) {
  public synchronized void releaseConnection(ConnectionWrapper conn) {
    String targetKey = null;
    ConnectionRecord targetRecord = null;
    synchronized(this) {
      for (String key : connectionTable.keySet()) {
        ConnectionRecord cr = connectionTable.get(key);
        if (cr.ctx == ctx) {
        if (cr.conn == conn) {
          targetKey = key;
          targetRecord = cr;
          if (targetKey != null)
@@ -279,7 +281,7 @@
   * provided authentication (for testing purposes).
   * @throws NamingException if an error occurs connecting.
   */
  private void registerAuth(LDAPURL ldapUrl, String dn, String pw,
  private void registerAuth(LDAPURL ldapUrl, DN dn, String pw,
      boolean connect) throws NamingException {
    String key = makeKeyFromLDAPUrl(ldapUrl);
@@ -288,8 +290,7 @@
    ar.password = pw;
    if (connect) {
      InitialLdapContext ctx = createLDAPConnection(ldapUrl, ar);
      ctx.close();
      createLDAPConnection(ldapUrl, ar).close();
    }
    synchronized(this) {
@@ -313,13 +314,12 @@
   * Register authentication data from an existing connection.
   * This routine recreates the LDAP URL corresponding to
   * the connection and passes it to registerAuth(LDAPURL).
   * @param ctx the connection that we retrieve the authentication information
   * from.
   * @param conn the connection that we retrieve the authentication information from.
   */
  private void registerAuth(InitialLdapContext ctx) {
    LDAPURL url = makeLDAPUrl(ctx);
  private void registerAuth(ConnectionWrapper conn) {
    LDAPURL url = makeLDAPUrl(conn);
    try {
      registerAuth(url, getBindDN(ctx), getBindPassword(ctx), false);
      registerAuth(url, conn.getBindDn(), conn.getBindPassword(), false);
    }
    catch (NamingException x) {
      throw new RuntimeException("Bug");
@@ -331,8 +331,7 @@
   * Unregister authentication data.
   * If for the given url there's a connection, try to bind as anonymous.
   * If unbind fails throw NamingException.
   * @param ldapUrl the url associated with the authentication to be
   * unregistered.
   * @param ldapUrl the url associated with the authentication to be unregistered.
   * @throws NamingException if the unbind fails.
   */
  private void unRegisterAuth(LDAPURL ldapUrl) throws NamingException {
@@ -351,14 +350,7 @@
  {
    String key = makeKeyFromRecord(cr);
    connectionTable.remove(key);
    try
    {
      cr.ctx.close();
    }
    catch (NamingException x)
    {
      // Bizarre. However it's not really a problem here.
    }
    cr.conn.close();
  }
  /** Notifies the listeners that a referral authentication change happened. */
@@ -387,8 +379,8 @@
   * @return the key to be used in Maps for the provided connection record.
   */
  private static String makeKeyFromRecord(ConnectionRecord rec) {
    String protocol = ConnectionUtils.isSSL(rec.ctx) ? "LDAPS" : "LDAP";
    return protocol + ":" + getHostPort(rec.ctx);
    String protocol = rec.conn.isSSL() ? "LDAPS" : "LDAP";
    return protocol + ":" + rec.conn.getHostPort();
  }
  /**
@@ -399,21 +391,12 @@
   * @return a connection.
   * @throws NamingException if an error occurs when connecting.
   */
  private InitialLdapContext createLDAPConnection(LDAPURL ldapUrl,
      AuthRecord ar) throws NamingException
  private ConnectionWrapper createLDAPConnection(LDAPURL ldapUrl, AuthRecord ar) throws NamingException
  {
    // Take the base DN out of the URL and only keep the protocol, host and port
    ldapUrl = new LDAPURL(ldapUrl.getScheme(), ldapUrl.getHost(),
          ldapUrl.getPort(), (DN)null, null, null, null, null);
    if (isSecureLDAPUrl(ldapUrl))
    {
      return ConnectionUtils.createLdapsContext(ldapUrl.toString(), ar.dn,
          ar.password, getConnectTimeout(), null,
          getTrustManager(), getKeyManager());
    }
    return ConnectionUtils.createLdapContext(ldapUrl.toString(), ar.dn,
        ar.password, getConnectTimeout(), null);
    final HostPort hostPort = new HostPort(ldapUrl.getHost(), ldapUrl.getPort());
    final Type connectiontype = isSecureLDAPUrl(ldapUrl) ? LDAPS : LDAP;
    return new ConnectionWrapper(hostPort, connectiontype, ar.dn.toString(), ar.password,
        getConnectTimeout(), getTrustManager(), getKeyManager());
  }
  /**
@@ -474,8 +457,8 @@
    return !LDAPURL.DEFAULT_SCHEME.equalsIgnoreCase(url.getScheme());
  }
  private LDAPURL makeLDAPUrl(InitialLdapContext ctx) {
    return makeLDAPUrl(ConnectionUtils.getHostPort(ctx), "", isSSL(ctx));
  private LDAPURL makeLDAPUrl(ConnectionWrapper conn) {
    return makeLDAPUrl(conn.getHostPort(), "", conn.isSSL());
  }
  /**
@@ -521,13 +504,13 @@
/** A structure representing authentication data. */
class AuthRecord {
  String dn;
  DN dn;
  String password;
}
/** A structure representing an active connection. */
class ConnectionRecord {
  InitialLdapContext ctx;
  ConnectionWrapper conn;
  int counter;
  boolean disconnectAfterUse;
}
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/NodeRefresher.java
@@ -16,8 +16,6 @@
 */
package org.opends.guitools.controlpanel.browser;
import static org.opends.admin.ads.util.ConnectionUtils.getHostPort;
import static org.opends.admin.ads.util.ConnectionUtils.isSSL;
import static org.opends.messages.AdminToolMessages.*;
import java.util.ArrayList;
@@ -31,7 +29,6 @@
import javax.naming.SizeLimitExceededException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreeNode;
@@ -41,6 +38,7 @@
import org.forgerock.opendj.ldap.RDN;
import org.forgerock.opendj.ldap.SearchScope;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.ui.nodes.BasicNode;
import org.opends.messages.AdminToolMessages;
import org.opends.server.schema.SchemaConstants;
@@ -304,18 +302,23 @@
  /**
   * Performs the search in the case the user specified a custom filter.
   * @param node the parent node we perform the search from.
   * @param ctx the connection to be used.
   * @throws NamingException if a problem occurred.
   *
   * @param node
   *          the parent node we perform the search from.
   * @param conn
   *          the connection to be used.
   * @throws NamingException
   *           if a problem occurred.
   */
  private void searchForCustomFilter(BasicNode node, InitialLdapContext ctx)
  private void searchForCustomFilter(BasicNode node, ConnectionWrapper conn)
  throws NamingException
  {
    SearchControls ctls = controller.getBasicSearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(new String[] { SchemaConstants.NO_ATTRIBUTES });
    ctls.setCountLimit(1);
    NamingEnumeration<SearchResult> s = ctx.search(new LdapName(node.getDN()),
    NamingEnumeration<SearchResult> s =
        conn.getLdapContext().search(new LdapName(node.getDN()),
              controller.getFilter(),
              ctls);
    try
@@ -347,17 +350,17 @@
  /**
   * Performs the search in the case the user specified a custom filter.
   * @param dn the parent DN we perform the search from.
   * @param ctx the connection to be used.
   * @param conn the connection to be used.
   * @throws NamingException if a problem occurred.
   */
  private void searchForCustomFilter(String dn, InitialLdapContext ctx)
  private void searchForCustomFilter(String dn, ConnectionWrapper conn)
  throws NamingException
  {
    SearchControls ctls = controller.getBasicSearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(new String[]{});
    ctls.setCountLimit(1);
    NamingEnumeration<SearchResult> s = ctx.search(new LdapName(dn),
    NamingEnumeration<SearchResult> s = conn.getLdapContext().search(new LdapName(dn),
              controller.getFilter(),
              ctls);
    try
@@ -389,15 +392,15 @@
  /** Read the local entry associated to the current node. */
  private void runReadLocalEntry() throws SearchAbandonException {
    BasicNode node = getNode();
    InitialLdapContext ctx = null;
    ConnectionWrapper conn = null;
    try {
      ctx = controller.findConnectionForLocalEntry(node);
      conn = controller.findConnectionForLocalEntry(node);
      if (ctx != null) {
      if (conn != null) {
        if (useCustomFilter())
        {
          // Check that the entry verifies the filter
          searchForCustomFilter(node, ctx);
          searchForCustomFilter(node, conn);
        }
        SearchControls ctls = controller.getBasicSearchControls();
@@ -405,7 +408,7 @@
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
        NamingEnumeration<SearchResult> s =
                ctx.search(new LdapName(node.getDN()),
            conn.getLdapContext().search(new LdapName(node.getDN()),
                controller.getObjectSearchFilter(),
                ctls);
        try
@@ -433,8 +436,8 @@
        throwAbandonIfNeeded(x);
    }
    finally {
      if (ctx != null) {
        controller.releaseLDAPConnection(ctx);
      if (conn != null) {
        controller.releaseLDAPConnection(conn);
      }
    }
  }
@@ -483,19 +486,19 @@
    int i = 0;
    while (i < referral.length && entry == null)
    {
      InitialLdapContext ctx = null;
      ConnectionWrapper conn = null;
      try {
        url = LDAPURL.decode(referral[i], false);
        if (url.getHost() == null)
        {
          // Use the local server connection.
          ctx = controller.getUserDataConnection();
          HostPort hostPort = getHostPort(ctx);
          conn = controller.getUserDataConnection();
          HostPort hostPort = conn.getHostPort();
          url.setHost(hostPort.getHost());
          url.setPort(hostPort.getPort());
          url.setScheme(isSSL(ctx) ? "ldaps" : "ldap");
          url.setScheme(conn.isSSL() ? "ldaps" : "ldap");
        }
        ctx = connectionPool.getConnection(url);
        conn = connectionPool.getConnection(url);
        remoteDn = url.getRawBaseDN();
        if (remoteDn == null || "".equals(remoteDn))
        {
@@ -515,7 +518,7 @@
        if (useCustomFilter() && url.getScope() == SearchScope.BASE_OBJECT)
        {
          // Check that the entry verifies the filter
          searchForCustomFilter(remoteDn, ctx);
          searchForCustomFilter(remoteDn, conn);
        }
        int scope = getJNDIScope(url);
@@ -525,7 +528,7 @@
        ctls.setReturningAttributes(controller.getAttrsForBlackSearch());
        ctls.setSearchScope(scope);
        ctls.setCountLimit(1);
        NamingEnumeration<SearchResult> sr = ctx.search(remoteDn,
        NamingEnumeration<SearchResult> sr = conn.getLdapContext().search(remoteDn,
            filter,
            ctls);
        try
@@ -573,8 +576,8 @@
        lastExceptionArg = referral[i];
      }
      finally {
        if (ctx != null) {
          connectionPool.releaseConnection(ctx);
        if (conn != null) {
          connectionPool.releaseConnection(conn);
        }
      }
      i = i + 1;
@@ -645,7 +648,7 @@
   */
  private void runDetectChildrenManually() throws SearchAbandonException {
    BasicNode parentNode = getNode();
    InitialLdapContext ctx = null;
    ConnectionWrapper conn = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
@@ -664,8 +667,8 @@
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
      }
      // Send an LDAP search
      ctx = controller.findConnectionForDisplayedEntry(parentNode);
      searchResults = ctx.search(
      conn = controller.findConnectionForDisplayedEntry(parentNode);
      searchResults = conn.getLdapContext().search(
          new LdapName(controller.findBaseDNForChildEntries(parentNode)),
          controller.getChildSearchFilter(),
          ctls);
@@ -689,8 +692,8 @@
      throwAbandonIfNeeded(x);
    }
    finally {
      if (ctx != null) {
        controller.releaseLDAPConnection(ctx);
      if (conn != null) {
        controller.releaseLDAPConnection(conn);
      }
      if (searchResults != null)
      {
@@ -729,7 +732,7 @@
   * @throws SearchAbandonException if an error occurs.
   */
  private void runSearchChildren() throws SearchAbandonException {
    InitialLdapContext ctx = null;
    ConnectionWrapper conn = null;
    BasicNode parentNode = getNode();
    parentNode.setSizeLimitReached(false);
@@ -745,7 +748,7 @@
        ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      }
      ctls.setReturningAttributes(controller.getAttrsForRedSearch());
      ctx = controller.findConnectionForDisplayedEntry(parentNode);
      conn = controller.findConnectionForDisplayedEntry(parentNode);
      String parentDn = controller.findBaseDNForChildEntries(parentNode);
      int parentComponents;
      try
@@ -758,7 +761,7 @@
        throw new RuntimeException("Error decoding dn: "+parentDn+" . "+t,
            t);
      }
      NamingEnumeration<SearchResult> entries = ctx.search(
      NamingEnumeration<SearchResult> entries = conn.getLdapContext().search(
            new LdapName(parentDn),
                controller.getChildSearchFilter(),
                ctls);
@@ -838,8 +841,7 @@
              }
              if (mustAddParent)
              {
                SearchResult parentResult = searchManuallyEntry(ctx,
                    parentToAddDN.toString());
                SearchResult parentResult = searchManuallyEntry(conn, parentToAddDN.toString());
                childEntries.add(parentResult);
              }
            }
@@ -874,9 +876,9 @@
      throwAbandonIfNeeded(x);
    }
    finally {
      if (ctx != null)
      if (conn != null)
      {
        controller.releaseLDAPConnection(ctx);
        controller.releaseLDAPConnection(conn);
      }
    }
  }
@@ -904,18 +906,18 @@
  /**
   * Returns the entry for the given dn.
   * The code assumes that the request controls are set in the connection.
   * @param ctx the connection to be used.
   * @param conn the connection to be used.
   * @param dn the DN of the entry to be searched.
   * @throws NamingException if an error occurs.
   */
  private SearchResult searchManuallyEntry(InitialLdapContext ctx, String dn)
  private SearchResult searchManuallyEntry(ConnectionWrapper conn, String dn)
  throws NamingException
  {
    // Send an LDAP search
    SearchControls ctls = controller.getBasicSearchControls();
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
    ctls.setReturningAttributes(controller.getAttrsForRedSearch());
    NamingEnumeration<SearchResult> entries = ctx.search(
    NamingEnumeration<SearchResult> entries = conn.getLdapContext().search(
          new LdapName(dn),
              controller.getObjectSearchFilter(),
              ctls);
@@ -1118,10 +1120,10 @@
      if (dn2.isSuperiorOrEqualTo(dn1))
      {
        HostPort urlHostPort = new HostPort(url.getHost(), url.getPort());
        checkSucceeded = urlHostPort.equals(getHostPort(controller.getConfigurationConnection()));
        checkSucceeded = urlHostPort.equals(controller.getConfigurationConnection().getHostPort());
        if (checkSucceeded)
        {
          checkSucceeded = urlHostPort.equals(getHostPort(controller.getUserDataConnection()));
          checkSucceeded = urlHostPort.equals(controller.getUserDataConnection().getHostPort());
        }
      }
    }
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java
@@ -24,6 +24,7 @@
import static org.opends.server.tools.ConfigureWindowsService.*;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
import java.util.Collections;
@@ -34,14 +35,12 @@
import java.util.SortedSet;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.config.ConfigurationFramework;
import org.forgerock.opendj.config.server.ConfigException;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.browser.IconPool;
import org.opends.guitools.controlpanel.browser.LDAPConnectionPool;
@@ -82,7 +81,7 @@
  private final Set<Task> tasks = new HashSet<>();
  private ConnectionWrapper connWrapper;
  private InitialLdapContext userDataCtx;
  private ConnectionWrapper userDataConn;
  private final LDAPConnectionPool connectionPool = new LDAPConnectionPool();
  /** Used by the browsers. */
  private final IconPool iconPool = new IconPool();
@@ -319,36 +318,31 @@
  /**
   * Sets the dir context to be used by the ControlPanelInfo to retrieve
   * user data.
   * @param ctx the connection.
   * @param conn the connection.
   * @throws NamingException if there is a problem updating the connection pool.
   */
  public void setUserDataDirContext(InitialLdapContext ctx)
  throws NamingException
  public void setUserDataDirContext(ConnectionWrapper conn) throws NamingException
  {
    if (userDataCtx != null)
    if (userDataConn != null)
    {
      unregisterConnection(connectionPool, ctx);
      unregisterConnection(connectionPool, conn);
    }
    this.userDataCtx = ctx;
    if (ctx != null)
    this.userDataConn = conn;
    if (conn != null)
    {
      InitialLdapContext cloneLdc =
        ConnectionUtils.cloneInitialLdapContext(userDataCtx,
            getConnectTimeout(),
            getTrustManager(), null);
      connectionPool.registerConnection(cloneLdc);
      ConnectionWrapper cloneConn = cloneConnectionWrapper(userDataConn, getConnectTimeout(), getTrustManager(), null);
      connectionPool.registerConnection(cloneConn);
    }
  }
  /**
   * Returns the dir context to be used by the ControlPanelInfo to retrieve
   * user data.
   * @return the dir context to be used by the ControlPanelInfo to retrieve
   * user data.
   * Returns the connection to be used by the ControlPanelInfo to retrieve user data.
   *
   * @return the connection to be used by the ControlPanelInfo to retrieve user data.
   */
  public InitialLdapContext getUserDataDirContext()
  public ConnectionWrapper getUserDataDirContext()
  {
    return userDataCtx;
    return userDataConn;
  }
  /**
@@ -436,11 +430,11 @@
      {
        StaticUtils.close(connWrapper);
        connWrapper = null;
        if (userDataCtx != null)
        if (userDataConn != null)
        {
          unregisterConnection(connectionPool, null);
          StaticUtils.close(userDataCtx);
          userDataCtx = null;
          StaticUtils.close(userDataConn);
          userDataConn = null;
        }
      }
      if (isLocal)
@@ -474,7 +468,7 @@
                getConnectTimeout(), getTrustManager());
          }
        }
        catch (ConfigReadException | NamingException cre)
        catch (ConfigReadException | NamingException | IOException ignored)
        {
          // Ignore: we will ask the user for credentials.
        }
@@ -497,7 +491,7 @@
        Utilities.initializeConfigurationFramework();
        reader = newRemoteConfigReader();
        boolean connectionWorks = checkConnections(connWrapper, userDataCtx);
        boolean connectionWorks = checkConnections(connWrapper, userDataConn);
        if (!connectionWorks)
        {
          if (isLocal)
@@ -511,9 +505,9 @@
          }
          StaticUtils.close(connWrapper);
          this.connWrapper = null;
          unregisterConnection(connectionPool, connWrapper.getLdapContext());
          StaticUtils.close(userDataCtx);
          userDataCtx = null;
          unregisterConnection(connectionPool, connWrapper);
          StaticUtils.close(userDataConn);
          userDataConn = null;
        }
      }
@@ -610,13 +604,13 @@
    return status;
  }
  private void unregisterConnection(LDAPConnectionPool connectionPool, InitialLdapContext userDataCtx)
  private void unregisterConnection(LDAPConnectionPool connectionPool, ConnectionWrapper userDataConn)
  {
    if (connectionPool.isConnectionRegistered(userDataCtx))
    if (connectionPool.isConnectionRegistered(userDataConn))
    {
      try
      {
        connectionPool.unregisterConnection(userDataCtx);
        connectionPool.unregisterConnection(userDataConn);
      }
      catch (Throwable t)
      {
@@ -1194,7 +1188,7 @@
    return adminPort1 == adminPort2;
  }
  private boolean checkConnections(ConnectionWrapper conn, InitialLdapContext userCtx)
  private boolean checkConnections(ConnectionWrapper conn, ConnectionWrapper userConn)
  {
    // Check the connection
    int nMaxErrors = 5;
@@ -1203,9 +1197,9 @@
      try
      {
        Utilities.ping(conn);
        if (userCtx != null)
        if (userConn != null)
        {
          Utilities.pingDirContext(userCtx);
          Utilities.ping(userConn);
        }
        return true;
      }
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/DeleteEntryTask.java
@@ -34,11 +34,13 @@
import javax.naming.directory.SearchResult;
import javax.naming.ldap.BasicControl;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreePath;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.DN;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.browser.BrowserController;
import org.opends.guitools.controlpanel.datamodel.BackendDescriptor;
import org.opends.guitools.controlpanel.datamodel.BaseDNDescriptor;
@@ -49,9 +51,7 @@
import org.opends.guitools.controlpanel.ui.nodes.BasicNode;
import org.opends.guitools.controlpanel.ui.nodes.BrowserNodeInfo;
import org.opends.guitools.controlpanel.util.Utilities;
import org.forgerock.i18n.LocalizableMessage;
import org.opends.server.schema.SchemaConstants;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.DirectoryException;
import org.opends.server.util.ServerConstants;
@@ -195,16 +195,15 @@
          }
          if (!isDnDeleted)
          {
            InitialLdapContext ctx =
              controller.findConnectionForDisplayedEntry(node);
            ConnectionWrapper conn = controller.findConnectionForDisplayedEntry(node);
            useAdminCtx = controller.isConfigurationNode(node);
            if (node.hasSubOrdinates())
            {
              deleteSubtreeWithControl(ctx, dn, path, toNotify);
              deleteSubtreeWithControl(conn, dn, path, toNotify);
            }
            else
            {
              deleteSubtreeRecursively(ctx, dn, path, toNotify);
              deleteSubtreeRecursively(conn, dn, path, toNotify);
            }
            alreadyDeleted.add(dn);
          }
@@ -282,7 +281,7 @@
    }
  }
  private void deleteSubtreeRecursively(InitialLdapContext ctx, DN dnToRemove,
  private void deleteSubtreeRecursively(ConnectionWrapper conn, DN dnToRemove,
      TreePath path, ArrayList<BrowserNodeInfo> toNotify)
  throws NamingException, DirectoryException
  {
@@ -324,7 +323,7 @@
      ctls.setReturningAttributes(
          new String[] { SchemaConstants.NO_ATTRIBUTES });
      NamingEnumeration<SearchResult> entryDNs =
        ctx.search(Utilities.getJNDIName(dnToRemove.toString()), filter, ctls);
          conn.getLdapContext().search(Utilities.getJNDIName(dnToRemove.toString()), filter, ctls);
      DN entryDNFound = dnToRemove;
      try
@@ -337,7 +336,7 @@
            CustomSearchResult res =
              new CustomSearchResult(sr, dnToRemove.toString());
            entryDNFound = DN.valueOf(res.getDN());
            deleteSubtreeRecursively(ctx, entryDNFound, null, toNotify);
            deleteSubtreeRecursively(conn, entryDNFound, null, toNotify);
          }
        }
      }
@@ -352,7 +351,7 @@
    try
    {
      ctx.destroySubcontext(Utilities.getJNDIName(dnToRemove.toString()));
      conn.getLdapContext().destroySubcontext(Utilities.getJNDIName(dnToRemove.toString()));
      if (path != null)
      {
        toNotify.add(controller.getNodeInfoFromPath(path));
@@ -392,7 +391,7 @@
    }
  }
  private void deleteSubtreeWithControl(InitialLdapContext ctx, DN dn,
  private void deleteSubtreeWithControl(ConnectionWrapper conn, DN dn,
      TreePath path, ArrayList<BrowserNodeInfo> toNotify)
  throws NamingException
  {
@@ -419,22 +418,22 @@
    //  Use a copy of the dir context since we are using an specific
    // control to delete the subtree and this can cause
    // synchronization problems when the tree is refreshed.
    InitialLdapContext ctx1 = null;
    ConnectionWrapper conn1 = null;
    try
    {
      ctx1 = ConnectionUtils.cloneInitialLdapContext(ctx,
      conn1 = ConnectionUtils.cloneConnectionWrapper(conn,
          getInfo().getConnectTimeout(),
          getInfo().getTrustManager(), null);
      Control[] ctls = {
          new BasicControl(ServerConstants.OID_SUBTREE_DELETE_CONTROL)};
      ctx1.setRequestControls(ctls);
      ctx1.destroySubcontext(Utilities.getJNDIName(dn.toString()));
      conn1.getLdapContext().setRequestControls(ctls);
      conn1.getLdapContext().destroySubcontext(Utilities.getJNDIName(dn.toString()));
    }
    finally
    {
      try
      {
        ctx1.close();
        conn1.close();
      }
      catch (Throwable th)
      {
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ModifyEntryTask.java
@@ -32,7 +32,6 @@
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.ldap.InitialLdapContext;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreePath;
@@ -43,6 +42,7 @@
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.RDN;
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.browser.BrowserController;
import org.opends.guitools.controlpanel.datamodel.BackendDescriptor;
import org.opends.guitools.controlpanel.datamodel.BaseDNDescriptor;
@@ -205,7 +205,7 @@
    try
    {
      BasicNode node = (BasicNode)treePath.getLastPathComponent();
      InitialLdapContext ctx = controller.findConnectionForDisplayedEntry(node);
      ConnectionWrapper conn = controller.findConnectionForDisplayedEntry(node);
      useAdminCtx = controller.isConfigurationNode(node);
      if (!mustRename)
      {
@@ -228,7 +228,7 @@
            }
          });
          ctx.modifyAttributes(Utilities.getJNDIName(oldEntry.getDN()), mods);
          conn.getLdapContext().modifyAttributes(Utilities.getJNDIName(oldEntry.getDN()), mods);
          SwingUtilities.invokeLater(new Runnable()
          {
@@ -248,7 +248,7 @@
      }
      else
      {
        modifyAndRename(ctx, oldDn, oldEntry, newEntry, modifications);
        modifyAndRename(conn, oldDn, oldEntry, newEntry, modifications);
      }
      state = State.FINISHED_SUCCESSFULLY;
    }
@@ -314,7 +314,7 @@
  /**
   * Modifies and renames the entry.
   * @param ctx the connection to the server.
   * @param conn the connection to the server.
   * @param oldDN the oldDN of the entry.
   * @param originalEntry the original entry.
   * @param newEntry the new entry.
@@ -323,7 +323,7 @@
   * @throws CannotRenameException if we cannot perform the modification.
   * @throws NamingException if an error performing the modification occurs.
   */
  private void modifyAndRename(DirContext ctx, final DN oldDN,
  private void modifyAndRename(ConnectionWrapper conn, final DN oldDN,
  CustomSearchResult originalEntry, final Entry newEntry,
  final ArrayList<ModificationItem> originalMods)
  throws CannotRenameException, NamingException
@@ -353,7 +353,7 @@
      }
    });
    ctx.rename(Utilities.getJNDIName(oldDn.toString()),
    conn.getLdapContext().rename(Utilities.getJNDIName(oldDn.toString()),
        Utilities.getJNDIName(newEntry.getName().toString()));
    final TreePath[] newPath = {null};
@@ -392,7 +392,7 @@
        }
      });
      ctx.modifyAttributes(Utilities.getJNDIName(newEntry.getName().toString()), mods);
      conn.getLdapContext().modifyAttributes(Utilities.getJNDIName(newEntry.getName().toString()), mods);
      SwingUtilities.invokeLater(new Runnable()
      {
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/NewEntryTask.java
@@ -28,12 +28,13 @@
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.ldap.InitialLdapContext;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreePath;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.browser.BrowserController;
import org.opends.guitools.controlpanel.datamodel.BackendDescriptor;
import org.opends.guitools.controlpanel.datamodel.BaseDNDescriptor;
@@ -44,7 +45,6 @@
import org.opends.guitools.controlpanel.ui.nodes.BrowserNodeInfo;
import org.opends.guitools.controlpanel.util.Utilities;
import org.opends.server.config.ConfigConstants;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.Entry;
/** The task launched when we must create an entry. */
@@ -157,16 +157,16 @@
    try
    {
      InitialLdapContext ctx;
      ConnectionWrapper conn;
      if (parentNode != null)
      {
        ctx = controller.findConnectionForDisplayedEntry(parentNode);
        conn = controller.findConnectionForDisplayedEntry(parentNode);
        useAdminCtx = controller.isConfigurationNode(parentNode);
      }
      else
      {
        ctx = getInfo().getConnection().getLdapContext();
        conn = getInfo().getConnection();
        useAdminCtx = true;
      }
      BasicAttributes attrs = new BasicAttributes();
@@ -206,7 +206,7 @@
        }
      });
      ctx.createSubcontext(Utilities.getJNDIName(newEntry.getName().toString()),
      conn.getLdapContext().createSubcontext(Utilities.getJNDIName(newEntry.getName().toString()),
          attrs);
      SwingUtilities.invokeLater(new Runnable()
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java
@@ -29,9 +29,11 @@
import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.DN;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.browser.BrowserController;
import org.opends.guitools.controlpanel.datamodel.BackendDescriptor;
import org.opends.guitools.controlpanel.datamodel.BaseDNDescriptor;
@@ -39,10 +41,8 @@
import org.opends.guitools.controlpanel.ui.ProgressDialog;
import org.opends.guitools.controlpanel.ui.nodes.BasicNode;
import org.opends.guitools.controlpanel.util.Utilities;
import org.forgerock.i18n.LocalizableMessage;
import org.opends.server.config.ConfigConstants;
import org.opends.server.tools.LDAPPasswordModify;
import org.forgerock.opendj.ldap.DN;
/** The task called when we want to reset the password of the user. */
public class ResetUserPasswordTask extends Task
@@ -85,11 +85,10 @@
    try
    {
      InitialLdapContext ctx =
        controller.findConnectionForDisplayedEntry(node);
      if (ctx != null && isBoundAs(dn, ctx))
      ConnectionWrapper conn = controller.findConnectionForDisplayedEntry(node);
      if (conn != null && isBoundAs(dn, conn))
      {
        currentPassword = ConnectionUtils.getBindPassword(ctx).toCharArray();
        currentPassword = conn.getBindPassword().toCharArray();
      }
    }
    catch (Throwable t)
@@ -202,7 +201,7 @@
              String.valueOf(newPassword));
          if (getInfo().getUserDataDirContext() != null)
          {
            getInfo().getUserDataDirContext().addToEnvironment(
            getInfo().getUserDataDirContext().getLdapContext().addToEnvironment(
                Context.SECURITY_CREDENTIALS,
                String.valueOf(newPassword));
          }
@@ -223,17 +222,16 @@
   * particular DN (we might be binding using a value specified in
   * ds-cfg-alternate-bind-dn).
   * @param dn the DN.
   * @param ctx the connection that we are using to modify the password.
   * @param conn the connection that we are using to modify the password.
   * @return <CODE>true</CODE> if we are bound using the provided entry.
   */
  private boolean isBoundAs(DN dn, InitialLdapContext ctx)
  private boolean isBoundAs(DN dn, ConnectionWrapper conn)
  {
    boolean isBoundAs = false;
    DN bindDN = DN.rootDN();
    try
    {
      String b = ConnectionUtils.getBindDN(ctx);
      bindDN = DN.valueOf(b);
      bindDN = conn.getBindDn();
      isBoundAs = dn.equals(bindDN);
    }
    catch (Throwable t)
@@ -251,7 +249,7 @@
        String attrName = ConfigConstants.ATTR_ROOTDN_ALTERNATE_BIND_DN;
        ctls.setReturningAttributes(new String[] {attrName});
        NamingEnumeration<SearchResult> entries =
          ctx.search(Utilities.getJNDIName(dn.toString()), filter, ctls);
            conn.getLdapContext().search(Utilities.getJNDIName(dn.toString()), filter, ctls);
        try
        {
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/Task.java
@@ -34,12 +34,11 @@
import javax.naming.directory.Attribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.ldap.InitialLdapContext;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.datamodel.ControlPanelInfo;
import org.opends.guitools.controlpanel.datamodel.ServerDescriptor;
import org.opends.guitools.controlpanel.event.ConfigurationElementCreatedEvent;
@@ -699,29 +698,23 @@
  protected List<String> getConnectionCommandLineArguments(
      boolean useAdminConnector, boolean addConnectionTypeParameters)
  {
    ArrayList<String> args = new ArrayList<>();
    InitialLdapContext ctx;
    ConnectionWrapper conn = useAdminConnector
        ? getInfo().getConnection()
        : getInfo().getUserDataDirContext();
    if (useAdminConnector)
    List<String> args = new ArrayList<>();
    if (isServerRunning() && conn != null)
    {
      ctx = getInfo().getConnection().getLdapContext();
    }
    else
    {
      ctx = getInfo().getUserDataDirContext();
    }
    if (isServerRunning() && ctx != null)
    {
      HostPort hostPort = ConnectionUtils.getHostPort(ctx);
      HostPort hostPort = conn.getHostPort();
      String hostName = localHostName;
      if (hostName == null || !getInfo().getServerDescriptor().isLocal())
      {
        hostName = hostPort.getHost();
      }
      boolean isSSL = ConnectionUtils.isSSL(ctx);
      boolean isStartTLS = ConnectionUtils.isStartTLS(ctx);
      String bindDN = ConnectionUtils.getBindDN(ctx);
      String bindPwd = ConnectionUtils.getBindPassword(ctx);
      boolean isSSL = conn.isSSL();
      boolean isStartTLS = conn.isStartTLS();
      String bindDN = conn.getBindDn().toString();
      String bindPwd = conn.getBindPassword();
      args.add("--hostName");
      args.add(hostName);
      args.add("--port");
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/AbstractBrowseEntriesPanel.java
@@ -32,6 +32,7 @@
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URI;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
@@ -45,7 +46,6 @@
import java.util.TreeSet;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
@@ -147,7 +147,7 @@
  private JLabel lNumberOfEntries;
  private JLabel lNoMatchFound;
  private InitialLdapContext createdUserDataCtx;
  private ConnectionWrapper createdUserDataConn;
  /** The tree pane contained in this panel. */
  protected TreePanel treePane;
  /** The browser controller used to update the LDAP entry tree. */
@@ -1190,16 +1190,16 @@
        try
        {
          ConnectionWrapper conn = getInfo().getConnection();
          InitialLdapContext ctx1 = controller.getConfigurationConnection();
          boolean setConnection = conn.getLdapContext() != ctx1;
          ConnectionWrapper conn1 = controller.getConfigurationConnection();
          boolean setConnection = conn != conn1;
          updateNumSubordinateHacker(desc);
          if (setConnection)
          {
            if (getInfo().getUserDataDirContext() == null)
            {
              InitialLdapContext ctxUserData =
              ConnectionWrapper connUserData =
                  createUserDataDirContext(conn.getBindDn().toString(), conn.getBindPassword());
              getInfo().setUserDataDirContext(ctxUserData);
              getInfo().setUserDataDirContext(connUserData);
            }
            final NamingException[] fNe = { null };
            Runnable runnable = new Runnable()
@@ -1240,16 +1240,16 @@
          }
          displayNodes = true;
        }
        catch (NamingException ne)
        catch (IOException | NamingException e)
        {
          errorTitle = INFO_CTRL_PANEL_ERROR_CONNECT_BROWSE_DETAILS.get();
          errorDetails = INFO_CTRL_PANEL_ERROR_CONNECT_BROWSE_SUMMARY.get(ne);
          errorDetails = INFO_CTRL_PANEL_ERROR_CONNECT_BROWSE_SUMMARY.get(e);
          displayErrorPane = true;
        }
        catch (ConfigReadException cre)
        catch (ConfigReadException e)
        {
          errorTitle = INFO_CTRL_PANEL_ERROR_CONNECT_BROWSE_DETAILS.get();
          errorDetails = INFO_CTRL_PANEL_ERROR_CONNECT_BROWSE_SUMMARY.get(cre.getMessageObject());
          errorDetails = INFO_CTRL_PANEL_ERROR_CONNECT_BROWSE_SUMMARY.get(e.getMessageObject());
          displayErrorPane = true;
        }
      }
@@ -1412,13 +1412,13 @@
   * @throws ConfigReadException
   *           if an error occurs reading the configuration.
   */
  private InitialLdapContext createUserDataDirContext(final String bindDN, final String bindPassword)
      throws NamingException, ConfigReadException
  private ConnectionWrapper createUserDataDirContext(final String bindDN, final String bindPassword)
      throws NamingException, IOException, ConfigReadException
  {
    createdUserDataCtx = null;
    createdUserDataConn = null;
    try
    {
      createdUserDataCtx = Utilities.getUserDataDirContext(getInfo(), bindDN, bindPassword);
      createdUserDataConn = Utilities.getUserDataDirContext(getInfo(), bindDN, bindPassword);
    }
    catch (NamingException ne)
    {
@@ -1469,6 +1469,7 @@
        {
          final ConfigReadException[] fcre = { null };
          final NamingException[] fne = { null };
          final IOException[] fioe = { null };
          try
          {
            SwingUtilities.invokeAndWait(new Runnable()
@@ -1488,6 +1489,10 @@
                {
                  fne[0] = ne;
                }
                catch (IOException ioe)
                {
                  fioe[0] = ioe;
                }
              }
            });
          }
@@ -1503,10 +1508,14 @@
          {
            throw fne[0];
          }
          if (fioe[0] != null)
          {
            throw fioe[0];
        }
      }
    }
    return createdUserDataCtx;
    }
    return createdUserDataConn;
  }
  /**
@@ -1521,7 +1530,7 @@
   *          the bind password.
   */
  private void handleCertificateException(UserDataCertificateException ce, String bindDN, String bindPassword)
      throws NamingException, ConfigReadException
      throws NamingException, IOException, ConfigReadException
  {
    CertificateDialog dlg = new CertificateDialog(null, ce);
    dlg.pack();
@@ -1537,7 +1546,7 @@
      {
        logger.info(LocalizableMessage.raw("Accepting certificate presented by host " + host));
        getInfo().getTrustManager().acceptCertificate(chain, authType, host);
        createdUserDataCtx = createUserDataDirContext(bindDN, bindPassword);
        createdUserDataConn = createUserDataDirContext(bindDN, bindPassword);
      }
      else
      {
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/BrowseEntriesPanel.java
@@ -44,7 +44,6 @@
import javax.naming.InterruptedNamingException;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
@@ -66,6 +65,7 @@
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.forgerock.opendj.ldap.schema.ObjectClass;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.browser.NodeRefresher;
import org.opends.guitools.controlpanel.datamodel.ControlPanelInfo;
import org.opends.guitools.controlpanel.datamodel.CustomSearchResult;
@@ -528,9 +528,8 @@
      {
        try
        {
          InitialLdapContext ctx =
            controller.findConnectionForDisplayedEntry(node);
          LDAPEntryReader reader = new LDAPEntryReader(dn, ctx);
          ConnectionWrapper conn = controller.findConnectionForDisplayedEntry(node);
          LDAPEntryReader reader = new LDAPEntryReader(dn, conn);
          reader.addEntryReadListener(entryPane);
          // Required to update the browser controller properly if the entry is
          // deleted.
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/DuplicateEntryPanel.java
@@ -28,7 +28,6 @@
import java.util.ArrayList;
import java.util.List;
import javax.naming.ldap.InitialLdapContext;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
@@ -39,6 +38,7 @@
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.LocalizedIllegalArgumentException;
import org.forgerock.opendj.ldap.DN;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.browser.BrowserController;
import org.opends.guitools.controlpanel.datamodel.CustomSearchResult;
import org.opends.guitools.controlpanel.ui.nodes.BasicNode;
@@ -445,9 +445,8 @@
      @Override
      public CustomSearchResult processBackgroundTask() throws Throwable
      {
        InitialLdapContext ctx =
          controller.findConnectionForDisplayedEntry(node);
        LDAPEntryReader reader = new LDAPEntryReader(node.getDN(), ctx);
        ConnectionWrapper conn = controller.findConnectionForDisplayedEntry(node);
        LDAPEntryReader reader = new LDAPEntryReader(node.getDN(), conn);
        sleepIfRequired(700, t1);
        return reader.processBackgroundTask();
      }
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/LDAPEntryReader.java
@@ -23,8 +23,8 @@
import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.datamodel.CustomSearchResult;
import org.opends.guitools.controlpanel.event.EntryReadErrorEvent;
import org.opends.guitools.controlpanel.event.EntryReadEvent;
@@ -38,7 +38,7 @@
public class LDAPEntryReader extends BackgroundTask<CustomSearchResult>
{
  private final String dn;
  private final InitialLdapContext ctx;
  private final ConnectionWrapper conn;
  private final Set<EntryReadListener> listeners = new HashSet<>();
  private boolean isOver;
  private boolean notifyListeners;
@@ -46,12 +46,12 @@
  /**
   * Constructor of the entry reader.
   * @param dn the DN of the entry.
   * @param ctx the connection to the server.
   * @param conn the connection to the server.
   */
  public LDAPEntryReader(String dn, InitialLdapContext ctx)
  public LDAPEntryReader(String dn, ConnectionWrapper conn)
  {
    this.dn = dn;
    this.ctx = ctx;
    this.conn = conn;
    this.notifyListeners = true;
  }
@@ -69,7 +69,7 @@
      controls.setSearchScope(SearchControls.OBJECT_SCOPE);
      final String filter = "(|(objectclass=*)(objectclass=ldapsubentry))";
      en = ctx.search(Utilities.getJNDIName(dn), filter, controls);
      en = conn.getLdapContext().search(Utilities.getJNDIName(dn), filter, controls);
      SearchResult sr = null;
      while (en.hasMore())
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java
@@ -23,10 +23,10 @@
import static org.forgerock.opendj.ldap.DereferenceAliasesPolicy.*;
import static org.forgerock.opendj.ldap.SearchScope.*;
import static org.forgerock.opendj.ldap.requests.Requests.*;
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.*;
import static org.opends.server.schema.SchemaConstants.*;
import static org.opends.server.util.SchemaUtils.*;
import java.awt.Color;
@@ -58,11 +58,7 @@
import javax.naming.CompositeName;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NamingEnumeration;
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 javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
@@ -111,6 +107,7 @@
import org.forgerock.opendj.ldap.schema.SchemaBuilder;
import org.forgerock.opendj.ldap.schema.SchemaElement;
import org.forgerock.opendj.ldap.schema.Syntax;
import org.forgerock.opendj.ldif.ConnectionEntryReader;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.ControlPanel;
import org.opends.guitools.controlpanel.browser.IconPool;
@@ -2141,7 +2138,7 @@
  }
  /**
   * Returns the InitialLdapContext to connect to the administration connector
   * Returns the connection to connect to the administration connector
   * of the server using the information in the ControlCenterInfo object (which
   * provides the host and administration connector port to be used) and some
   * LDAP credentials.
@@ -2150,13 +2147,15 @@
   * @param controlInfo the object which provides the connection parameters.
   * @param bindDN the base DN to be used to bind.
   * @param pwd the password to be used to bind.
   * @return the InitialLdapContext connected to the server.
   * @return the connection to the server.
   * @throws NamingException if there was a problem connecting to the server
   * or the provided credentials do not have enough rights.
   * @throws IOException if there was a problem connecting to the server
   * or the provided credentials do not have enough rights.
   * @throws ConfigReadException if there is an error reading the configuration.
   */
  public static ConnectionWrapper getAdminDirContext(ControlPanelInfo controlInfo, String bindDN, String pwd)
      throws NamingException, ConfigReadException
      throws NamingException, IOException, ConfigReadException
  {
    String usedUrl = controlInfo.getAdminConnectorURL();
    if (usedUrl == null)
@@ -2168,115 +2167,87 @@
    // Search for the config to check that it is the directory manager.
    ConnectionWrapper conn = new ConnectionWrapper(
        usedUrl, LDAPS, bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
    checkCanReadConfig(conn.getLdapContext());
    checkCanReadConfig(conn);
    return conn;
  }
  /**
   * Returns the InitialLdapContext to connect to the server using the
   * Returns the connection to connect to the server using the
   * information in the ControlCenterInfo object (which provides the host, port
   * and protocol to be used) and some LDAP credentials.  It also tests that
   * the provided credentials have enough rights to read the configuration.
   * @param controlInfo the object which provides the connection parameters.
   * @param bindDN the base DN to be used to bind.
   * @param pwd the password to be used to bind.
   * @return the InitialLdapContext connected to the server.
   * @return the connection to the server.
   * @throws NamingException if there was a problem connecting to the server
   * or the provided credentials do not have enough rights.
   * @throws IOException if there was a problem connecting to the server
   * or the provided credentials do not have enough rights.
   * @throws ConfigReadException if there is an error reading the configuration.
   */
  public static InitialLdapContext getUserDataDirContext(
      ControlPanelInfo controlInfo,
      String bindDN, String pwd) throws NamingException, ConfigReadException
  public static ConnectionWrapper getUserDataDirContext(ControlPanelInfo controlInfo,
      String bindDN, String pwd) throws NamingException, IOException, ConfigReadException
  {
    InitialLdapContext ctx;
    String usedUrl;
    ConnectionWrapper conn;
    if (controlInfo.connectUsingStartTLS())
    {
      usedUrl = controlInfo.getStartTLSURL();
      String usedUrl = controlInfo.getStartTLSURL();
      if (usedUrl == null)
      {
        throw new ConfigReadException(
            ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
      }
      ctx = Utils.createStartTLSContext(usedUrl,
          bindDN, pwd, controlInfo.getConnectTimeout(), null,
          controlInfo.getTrustManager(), null);
      conn = new ConnectionWrapper(usedUrl, START_TLS,
          bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
    }
    else if (controlInfo.connectUsingLDAPS())
    {
      usedUrl = controlInfo.getLDAPSURL();
      String usedUrl = controlInfo.getLDAPSURL();
      if (usedUrl == null)
      {
        throw new ConfigReadException(
            ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
      }
      ctx = createLdapsContext(usedUrl,
          bindDN, pwd, controlInfo.getConnectTimeout(), null,
          controlInfo.getTrustManager(), null);
      conn = new ConnectionWrapper(usedUrl, LDAPS,
          bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
    }
    else
    {
      usedUrl = controlInfo.getLDAPURL();
      String usedUrl = controlInfo.getLDAPURL();
      if (usedUrl == null)
      {
        throw new ConfigReadException(
            ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
      }
      ctx = createLdapContext(usedUrl,
          bindDN, pwd, controlInfo.getConnectTimeout(), null);
      conn = new ConnectionWrapper(usedUrl, LDAP,
          bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
    }
    checkCanReadConfig(ctx);
    return ctx;
    checkCanReadConfig(conn);
    return conn;
  }
  /**
   * Checks that the provided connection can read cn=config.
   * @param ctx the connection to be tested.
   * @throws NamingException if an error occurs while reading cn=config.
   *
   * @param conn
   *          the connection to be tested.
   * @throws IOException
   *           if an error occurs while reading cn=config.
   */
  private static void checkCanReadConfig(InitialLdapContext ctx)
  throws NamingException
  private static void checkCanReadConfig(ConnectionWrapper conn) throws IOException
  {
    // Search for the config to check that it is the directory manager.
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.OBJECT_SCOPE);
    searchControls.setReturningAttributes(new String[] { SchemaConstants.NO_ATTRIBUTES });
    NamingEnumeration<SearchResult> sr =
      ctx.search("cn=config", "objectclass=*", searchControls);
    try
    SearchRequest request = newSearchRequest("cn=config", BASE_OBJECT, "objectclass=*", NO_ATTRIBUTES);
    try (ConnectionEntryReader entryReader = conn.getConnection().search(request))
    {
      while (sr.hasMore())
      while (entryReader.hasNext())
      {
        sr.next();
        entryReader.readEntry();
      }
    }
    finally
    {
      sr.close();
    }
  }
  /**
   * Ping the specified InitialLdapContext.
   * This method sends a search request on the root entry of the DIT
   * and forward the corresponding exception (if any).
   * @param ctx the InitialLdapContext to be "pinged".
   * @throws NamingException if the ping could not be performed.
   */
  public static void pingDirContext(InitialLdapContext ctx)
  throws NamingException {
    SearchControls sc = new SearchControls(
        SearchControls.OBJECT_SCOPE,
        0, // count limit
        0, // time limit
        new String[0], // No attributes
        false, // Don't return bound object
        false // Don't dereference link
    );
    ctx.search("", "objectClass=*", sc);
  }
  /**
@@ -2290,7 +2261,7 @@
   */
  public static void ping(ConnectionWrapper connWrapper) throws NamingException
  {
    SearchRequest request = newSearchRequest("", BASE_OBJECT, "objectClass=*", "1.1")
    SearchRequest request = newSearchRequest("", BASE_OBJECT, "objectClass=*", NO_ATTRIBUTES)
        .setSizeLimit(0)
        .setTimeLimit(0)
        .setDereferenceAliasesPolicy(NEVER);
opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java
@@ -1901,8 +1901,7 @@
  }
  /**
   * This method updates the replication in the remote server using the
   * provided InitialLdapContext.
   * This method updates the replication in the remote server using the provided connection.
   * It also tries to delete the server registration entry from the remote ADS
   * servers if the serverADSProperties object passed is not null.
   * @param connWrapper the connection to the remote server where we want to remove
opendj-server-legacy/src/main/java/org/opends/quicksetup/Application.java
@@ -14,7 +14,6 @@
 * Copyright 2008-2010 Sun Microsystems, Inc.
 * Portions Copyright 2012-2016 ForgeRock AS.
 */
package org.opends.quicksetup;
import static com.forgerock.opendj.cli.Utils.*;
@@ -601,7 +600,7 @@
   * Use {@code 0} to express no timeout.
   * @param cnx the ordered list of preferred connections to connect to the
   * server.
   * @return the InitialLdapContext to the remote server.
   * @return the connection to the remote server.
   * @throws ApplicationException if something goes wrong.
   */
  protected ConnectionWrapper getRemoteConnection(ServerDescriptor server, DN dn, String pwd, int timeout,
opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java
@@ -61,7 +61,6 @@
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.Rdn;
import javax.swing.JPanel;
@@ -2061,7 +2060,7 @@
          knownReplicationServerIds,
          knownServerIds);
      localTimeMeasureTime = System.currentTimeMillis();
      localTime = Utils.getServerClock(conn.getLdapContext());
      localTime = Utils.getServerClock(conn);
      localServerDisplay = conn.getHostPort();
    }
    catch (NamingException ne)
@@ -2154,7 +2153,7 @@
              conn, remoteReplicationServers, replicationPort, enableSecureReplication,
              knownReplicationServerIds, knownServerIds);
          long remoteTimeMeasureTime = System.currentTimeMillis();
          long remoteTime = Utils.getServerClock(conn.getLdapContext());
          long remoteTime = Utils.getServerClock(conn);
          if (localTime != -1
              && remoteTime != -1
              && Math.abs(localTime - remoteTime - localTimeMeasureTime + remoteTimeMeasureTime) >
@@ -2472,7 +2471,7 @@
        filter.setSearchMonitoringInformation(false);
        filter.addBaseDNToSearch(ADSContext.getAdministrationSuffixDN());
        filter.addBaseDNToSearch(Constants.SCHEMA_DN);
        ServerDescriptor s = createStandalone(remoteConn.getLdapContext(), filter);
        ServerDescriptor s = createStandalone(remoteConn, filter);
        for (ReplicaDescriptor replica : s.getReplicas())
        {
          String dn = replica.getSuffix().getDN();
@@ -2541,7 +2540,7 @@
            TopologyCacheFilter filter = new TopologyCacheFilter();
            filter.setSearchMonitoringInformation(false);
            filter.addBaseDNToSearch(dn);
            ServerDescriptor s = createStandalone(remoteConn.getLdapContext(), filter);
            ServerDescriptor s = createStandalone(remoteConn, filter);
            for (ReplicaDescriptor r : s.getReplicas())
            {
              if (areDnsEqual(r.getSuffix().getDN(), dn))
@@ -2578,7 +2577,7 @@
            logger.info(LocalizableMessage.raw("Calling initializeSuffix with base DN: " + dn));
            logger.info(LocalizableMessage.raw("Try number: " + (6 - nTries)));
            logger.info(LocalizableMessage.raw("replicationId of source replica: " + replicationId));
            initializeSuffix(conn.getLdapContext(), replicationId, dn, !isADS && !isSchema, hostPort);
            initializeSuffix(conn, replicationId, dn, !isADS && !isSchema, hostPort);
            initDone = true;
          }
          catch (PeerNotFoundException pnfe)
@@ -2654,7 +2653,7 @@
          TopologyCacheFilter filter = new TopologyCacheFilter();
          filter.setSearchMonitoringInformation(false);
          filter.setSearchBaseDNInformation(false);
          ServerDescriptor server = createStandalone(remoteConn.getLdapContext(), filter);
          ServerDescriptor server = createStandalone(remoteConn, filter);
          server.updateAdsPropertiesWithServerProperties();
          adsContext.registerServer(server.getAdsProperties());
          createdRemoteAds = true;
@@ -2682,7 +2681,7 @@
      TopologyCacheFilter filter = new TopologyCacheFilter();
      filter.setSearchMonitoringInformation(false);
      filter.setSearchBaseDNInformation(false);
      ServerDescriptor server = createStandalone(localConn.getLdapContext(), filter);
      ServerDescriptor server = createStandalone(localConn, filter);
      server.updateAdsPropertiesWithServerProperties();
      if (0 == adsContext.registerOrUpdateServer(server.getAdsProperties()))
      {
@@ -2697,7 +2696,7 @@
      }
      if (isRemoteServer)
      {
        seedAdsTrustStore(localConn.getLdapContext(), adsContext.getTrustedCertificates());
        seedAdsTrustStore(localConn, adsContext.getTrustedCertificates());
      }
      if (isVerbose())
      {
@@ -3475,7 +3474,7 @@
      }
      else
      {
        updateUserDataWithSuffixesInServer(conn.getLdapContext());
        updateUserDataWithSuffixesInServer(conn);
      }
    }
    catch (UserDataException ude)
@@ -3952,9 +3951,9 @@
  /**
   * Update the UserInstallData object with the contents of the server to which
   * we are connected with the provided InitialLdapContext.
   * we are connected with the provided connection.
   */
  private void updateUserDataWithSuffixesInServer(InitialLdapContext ctx) throws NamingException
  private void updateUserDataWithSuffixesInServer(ConnectionWrapper conn) throws NamingException
  {
    SuffixesToReplicateOptions suf = getUserData().getSuffixesToReplicateOptions();
    SuffixesToReplicateOptions.Type type;
@@ -3968,7 +3967,7 @@
      type = SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
    }
    ServerDescriptor s = createStandalone(ctx, new TopologyCacheFilter());
    ServerDescriptor s = createStandalone(conn, new TopologyCacheFilter());
    Set<ReplicaDescriptor> replicas = s.getReplicas();
    for (ReplicaDescriptor replica : replicas)
    {
@@ -4108,7 +4107,7 @@
   *
   * @param server
   *          the object describing the server.
   * @return the InitialLdapContext to the remote server.
   * @return the connection to the remote server.
   * @throws ApplicationException
   *           if something goes wrong.
   */
@@ -4148,7 +4147,7 @@
   * Initializes a suffix with the contents of a replica that has a given
   * replication id.
   *
   * @param ctx
   * @param conn
   *          the connection to the server whose suffix we want to initialize.
   * @param replicaId
   *          the replication ID of the replica we want to use to initialize the
@@ -4165,7 +4164,7 @@
   * @throws PeerNotFoundException
   *           if the replication mechanism cannot find a peer.
   */
  public void initializeSuffix(InitialLdapContext ctx, int replicaId, String suffixDn, boolean displayProgress,
  public void initializeSuffix(ConnectionWrapper conn, int replicaId, String suffixDn, boolean displayProgress,
      HostPort sourceServerDisplay) throws ApplicationException, PeerNotFoundException
  {
    boolean taskCreated = false;
@@ -4189,7 +4188,7 @@
      attrs.put("ds-task-id", id);
      try
      {
        DirContext dirCtx = ctx.createSubcontext(dn, attrs);
        DirContext dirCtx = conn.getLdapContext().createSubcontext(dn, attrs);
        taskCreated = true;
        logger.info(LocalizableMessage.raw("created task entry: " + attrs));
        dirCtx.close();
@@ -4236,7 +4235,7 @@
      }
      try
      {
        NamingEnumeration<SearchResult> res = ctx.search(dn, filter, searchControls);
        NamingEnumeration<SearchResult> res = conn.getLdapContext().search(dn, filter, searchControls);
        SearchResult sr = null;
        try
        {
@@ -4405,7 +4404,7 @@
            .get(sourceServerDisplay), ne), ne);
      }
    }
    resetGenerationId(ctx, suffixDn, sourceServerDisplay);
    resetGenerationId(conn, suffixDn, sourceServerDisplay);
  }
  /**
@@ -4425,7 +4424,7 @@
    return getUserData().getHostName() + ":" + getUserData().getReplicationOptions().getReplicationPort();
  }
  private void resetGenerationId(InitialLdapContext ctx, String suffixDn, HostPort sourceServerDisplay)
  private void resetGenerationId(ConnectionWrapper conn, String suffixDn, HostPort sourceServerDisplay)
      throws ApplicationException
  {
    boolean taskCreated = false;
@@ -4448,7 +4447,7 @@
      attrs.put("ds-task-id", id);
      try
      {
        DirContext dirCtx = ctx.createSubcontext(dn, attrs);
        DirContext dirCtx = conn.getLdapContext().createSubcontext(dn, attrs);
        taskCreated = true;
        logger.info(LocalizableMessage.raw("created task entry: " + attrs));
        dirCtx.close();
@@ -4475,7 +4474,7 @@
      StaticUtils.sleep(500);
      try
      {
        NamingEnumeration<SearchResult> res = ctx.search(dn, filter, searchControls);
        NamingEnumeration<SearchResult> res = conn.getLdapContext().search(dn, filter, searchControls);
        SearchResult sr = null;
        try
        {
opendj-server-legacy/src/main/java/org/opends/quicksetup/util/ServerController.java
@@ -20,18 +20,23 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
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.quicksetup.*;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.admin.ads.util.PreferredConnection.Type;
import org.opends.quicksetup.Application;
import org.opends.quicksetup.ApplicationException;
import org.opends.quicksetup.Configuration;
import org.opends.quicksetup.Installation;
import org.opends.quicksetup.ReturnCode;
import org.opends.quicksetup.installer.InstallerHelper;
import org.opends.server.util.SetupUtils;
import org.opends.server.util.StaticUtils;
import com.forgerock.opendj.cli.CliConstants;
@@ -39,8 +44,8 @@
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.QuickSetupMessages.*;
import static org.opends.server.util.CollectionUtils.*;
/** Class used to manipulate an OpenDS server. */
public class ServerController {
@@ -298,13 +303,13 @@
  /**
   * This methods starts the server.
   * @param verify boolean indicating whether this method will attempt to
   * @param verifyCanConnect boolean indicating whether this method will attempt to
   * connect to the server after starting to verify that it is listening.
   * @param suppressOutput indicating that ouput to standard output streams
   * from the server should be suppressed.
   * @throws org.opends.quicksetup.ApplicationException if something goes wrong.
   */
  private void startServer(boolean verify, boolean suppressOutput)
  private void startServer(boolean verifyCanConnect, boolean suppressOutput)
  throws ApplicationException
  {
    if (suppressOutput && !StandardOutputSuppressor.isSuppressed()) {
@@ -324,16 +329,45 @@
        mb.append(application.getLineBreak());
        application.notifyListeners(mb.toMessage());
      }
      try
      {
        startServerViaAnotherProcess();
        if (verifyCanConnect)
        {
          verifyCanConnect();
        }
      } catch (IOException | InterruptedException ioe)
      {
        throw new ApplicationException(
            ReturnCode.START_ERROR,
            getThrowableMsg(INFO_ERROR_STARTING_SERVER.get(), ioe), ioe);
      }
    } finally {
      if (suppressOutput)
      {
        if (StandardOutputSuppressor.isSuppressed())
        {
          StandardOutputSuppressor.unsuppress();
        }
        if (application != null)
        {
          application.setNotifyListeners(true);
        }
      }
    }
  }
  private void startServerViaAnotherProcess() throws IOException, InterruptedException, ApplicationException
  {
      logger.info(LocalizableMessage.raw("starting server"));
      ArrayList<String> argList = new ArrayList<>();
      argList.add(Utils.getScriptPath(
          Utils.getPath(installation.getServerStartCommandFile())));
      argList.add("--timeout");
      argList.add("0");
      String[] args = new String[argList.size()];
      argList.toArray(args);
      ProcessBuilder pb = new ProcessBuilder(args);
    List<String> argList = newArrayList(
        Utils.getScriptPath(Utils.getPath(installation.getServerStartCommandFile())),
        "--timeout", "0");
    ProcessBuilder pb = new ProcessBuilder(argList.toArray(new String[argList.size()]));
      pb.directory(installation.getBinariesDirectory());
      Map<String, String> env = pb.environment();
      env.put(SetupUtils.OPENDJ_JAVA_HOME, System.getProperty("java.home"));
@@ -344,15 +378,12 @@
      // when it starts.  Since we're just calling the start-ds script
      // it will figure out the correct classpath for the server.
      env.remove("CLASSPATH");
      try
      {
        String startedId = getStartedId();
        Process process = pb.start();
        BufferedReader err =
          new BufferedReader(new InputStreamReader(process.getErrorStream()));
        BufferedReader out =
          new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StartReader errReader = new StartReader(err, startedId, true);
        StartReader outputReader = new StartReader(out, startedId, false);
@@ -363,9 +394,7 @@
        if (returnValue != 0)
        {
          throw new ApplicationException(ReturnCode.START_ERROR,
              INFO_ERROR_STARTING_SERVER_CODE.get(returnValue),
              null);
      throw new ApplicationException(ReturnCode.START_ERROR, INFO_ERROR_STARTING_SERVER_CODE.get(returnValue), null);
        }
        if (outputReader.isFinished())
        {
@@ -393,7 +422,10 @@
          // minds later or add the ability to return exceptions
          // in the output only instead of throwing...
          throw ex;
        } else if (verify)
    }
  }
  private void verifyCanConnect() throws IOException, ApplicationException
        {
          /*
           * There are no exceptions from the readers and they are marked as
@@ -422,9 +454,47 @@
            userPw = null;
          }
          InitialLdapContext ctx = null;
          for (int i=0; i<50 && !connected; i++)
          {
      String hostName = getHostName(i);
      String ldapUrl = "ldaps://"+hostName+":" + port;
      try
      {
        int timeout = CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT;
        if (application != null && application.getUserData() != null)
        {
          timeout = application.getUserData().getConnectTimeout();
        }
        try (ConnectionWrapper conn = new ConnectionWrapper(ldapUrl, Type.LDAPS, userDn, userPw, timeout, null))
        {
          return;
        }
      }
      catch (NamingException ne)
      {
        logger.warn(LocalizableMessage.raw("Could not connect to server: "+ne, ne));
      }
      try
      {
        // not connected yet
        Thread.sleep(3000);
      }
      catch (Throwable t)
      {
        // do nothing
      }
    }
    // Could not connect
    final LocalizableMessage msg = isWindows()
        ? INFO_ERROR_STARTING_SERVER_IN_WINDOWS.get(port)
        : INFO_ERROR_STARTING_SERVER_IN_UNIX.get(port);
    throw new ApplicationException(ReturnCode.START_ERROR, msg, null);
  }
  private String getHostName(int i)
  {
            String hostName = null;
            if (application != null)
            {
@@ -452,65 +522,7 @@
            }
            hostName = getHostNameForLdapUrl(hostName);
            String ldapUrl = "ldaps://"+hostName+":" + port;
            try
            {
              int timeout = CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT;
              if (application != null && application.getUserData() != null)
              {
                timeout = application.getUserData().getConnectTimeout();
              }
              ctx = createLdapsContext(ldapUrl, userDn, userPw, timeout,
                  null, null, null);
              connected = true;
            }
            catch (NamingException ne)
            {
              logger.warn(LocalizableMessage.raw("Could not connect to server: "+ne, ne));
            }
            finally
            {
              StaticUtils.close(ctx);
            }
            if (!connected)
            {
              try
              {
                Thread.sleep(3000);
              }
              catch (Throwable t)
              {
                 // do nothing
              }
            }
          }
          if (!connected)
          {
            final LocalizableMessage msg = isWindows()
                ? INFO_ERROR_STARTING_SERVER_IN_WINDOWS.get(port)
                : INFO_ERROR_STARTING_SERVER_IN_UNIX.get(port);
            throw new ApplicationException(ReturnCode.START_ERROR, msg, null);
          }
        }
      } catch (IOException | InterruptedException ioe)
      {
        throw new ApplicationException(
            ReturnCode.START_ERROR,
            getThrowableMsg(INFO_ERROR_STARTING_SERVER.get(), ioe), ioe);
      }
    } finally {
      if (suppressOutput)
      {
        if (StandardOutputSuppressor.isSuppressed())
        {
          StandardOutputSuppressor.unsuppress();
        }
        if (application != null)
        {
          application.setNotifyListeners(true);
        }
      }
    }
    return hostName;
  }
  /**
opendj-server-legacy/src/main/java/org/opends/quicksetup/util/Utils.java
@@ -76,6 +76,7 @@
import org.opends.admin.ads.SuffixDescriptor;
import org.opends.admin.ads.TopologyCacheException;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.quicksetup.Constants;
import org.opends.quicksetup.Installation;
import org.opends.quicksetup.SecurityOptions;
@@ -956,11 +957,11 @@
  /**
   * Returns the current time of a server in milliseconds.
   *
   * @param ctx
   * @param conn
   *          the connection to the server.
   * @return the current time of a server in milliseconds.
   */
  public static long getServerClock(InitialLdapContext ctx)
  public static long getServerClock(ConnectionWrapper conn)
  {
    long time = -1;
    SearchControls ctls = new SearchControls();
@@ -971,7 +972,7 @@
    try
    {
      LdapName jndiName = new LdapName("cn=monitor");
      NamingEnumeration<?> listeners = ctx.search(jndiName, filter, ctls);
      NamingEnumeration<?> listeners = conn.getLdapContext().search(jndiName, filter, ctls);
      try
      {
opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java
@@ -3593,11 +3593,11 @@
  private Type getConnectionType(final ConnectionWrapper conn)
  {
    if (isSSL(conn.getLdapContext()))
    if (conn.isSSL())
    {
      return LDAPS;
    }
    else if (isStartTLS(conn.getLdapContext()))
    else if (conn.isStartTLS())
    {
      return START_TLS;
    }
@@ -3696,8 +3696,8 @@
    {
      TopologyCacheFilter filter = new TopologyCacheFilter();
      filter.setSearchMonitoringInformation(false);
      ServerDescriptor server1 = ServerDescriptor.createStandalone(conn1.getLdapContext(), filter);
      ServerDescriptor server2 = ServerDescriptor.createStandalone(conn2.getLdapContext(), filter);
      ServerDescriptor server1 = ServerDescriptor.createStandalone(conn1, filter);
      ServerDescriptor server2 = ServerDescriptor.createStandalone(conn2, filter);
      for (ReplicaDescriptor rep1 : server1.getReplicas())
      {
@@ -3814,7 +3814,7 @@
    filter.setSearchMonitoringInformation(false);
    try
    {
      ServerDescriptor server = ServerDescriptor.createStandalone(conn.getLdapContext(), filter);
      ServerDescriptor server = ServerDescriptor.createStandalone(conn, filter);
      suffixes.addAll(server.getReplicas());
    }
    catch (Throwable t)
@@ -3975,8 +3975,8 @@
  private void printSuccessfullyEnabled(ConnectionWrapper conn1, ConnectionWrapper conn2)
  {
    long time1 = getServerClock(conn1.getLdapContext());
    long time2 = getServerClock(conn2.getLdapContext());
    long time1 = getServerClock(conn1);
    long time2 = getServerClock(conn2);
    if (time1 != -1
        && time2 != -1
        && Math.abs(time1 - time2) > Installer.THRESHOLD_CLOCK_DIFFERENCE_WARNING * 60 * 1000)
@@ -5196,7 +5196,7 @@
    {
      try
      {
        ServerDescriptor.seedAdsTrustStore(connDestination.getLdapContext(), adsCtxSource.getTrustedCertificates());
        ServerDescriptor.seedAdsTrustStore(connDestination, adsCtxSource.getTrustedCertificates());
      }
      catch (Throwable t)
      {
@@ -5491,7 +5491,7 @@
  {
    try
    {
      return ServerDescriptor.createStandalone(conn.getLdapContext(), filter);
      return ServerDescriptor.createStandalone(conn, filter);
    }
    catch (NamingException ne)
    {
@@ -6974,7 +6974,7 @@
      TopologyCacheFilter filter = new TopologyCacheFilter();
      filter.setSearchMonitoringInformation(false);
      filter.addBaseDNToSearch(baseDN);
      ServerDescriptor source = ServerDescriptor.createStandalone(connSource.getLdapContext(), filter);
      ServerDescriptor source = ServerDescriptor.createStandalone(connSource, filter);
      for (ReplicaDescriptor replica : source.getReplicas())
      {
        if (areDnsEqual(replica.getSuffix().getDN(), baseDN))
@@ -7019,7 +7019,7 @@
      try
      {
        installer.initializeSuffix(
            connDestination.getLdapContext(), replicationId, baseDN, displayProgress, connSource.getHostPort());
            connDestination, replicationId, baseDN, displayProgress, connSource.getHostPort());
        initDone = true;
      }
      catch (PeerNotFoundException pnfe)
@@ -9062,7 +9062,7 @@
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error loading topology cache in "
          + getLdapUrl(conn.getLdapContext()) + ": " + t, t));
          + conn.getLdapUrl() + ": " + t, t));
    }
    return null;
  }
@@ -9382,7 +9382,7 @@
                server.getHostPort(true)+" with certificates of "+ adsCtxSource.getHostPort()));
            try (ConnectionWrapper conn = getConnection(cacheDestination, server))
            {
              ServerDescriptor.seedAdsTrustStore(conn.getLdapContext(), adsCtxSource.getTrustedCertificates());
              ServerDescriptor.seedAdsTrustStore(conn, adsCtxSource.getTrustedCertificates());
            }
          }
        }
opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java
@@ -325,17 +325,17 @@
          if (!controlInfo.getServerDescriptor().getExceptions().isEmpty()) {
            return ReturnCode.ERROR_INITIALIZING_SERVER.get();
          }
        } catch (NamingException ne) {
        } catch (NamingException |IOException e) {
          // This should not happen but this is useful information to
          // diagnose the error.
          println();
          println(INFO_ERROR_READING_SERVER_CONFIGURATION.get(ne));
          println(INFO_ERROR_READING_SERVER_CONFIGURATION.get(e));
          return ReturnCode.ERROR_INITIALIZING_SERVER.get();
        } catch (ConfigReadException cre) {
        } catch (ConfigReadException e) {
          // This should not happen but this is useful information to
          // diagnose the error.
          println();
          println(cre.getMessageObject());
          println(e.getMessageObject());
          return ReturnCode.ERROR_INITIALIZING_SERVER.get();
        }
      } else {