From 609077ed606e3b094e303f298e8dca10567bc3e2 Mon Sep 17 00:00:00 2001
From: Jean-Noël Rouvignac <jean-noel.rouvignac@forgerock.com>
Date: Fri, 05 Aug 2016 18:42:07 +0000
Subject: [PATCH] Partial OPENDJ-2625 Convert all code that uses JNDI to use the SDK instead

---
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java         |   50 -
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LoginPanel.java                 |   23 
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/LDAPConnectionPool.java    |   35 
 opendj-server-legacy/src/main/java/org/opends/quicksetup/Application.java                              |   15 
 opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java    |   35 
 opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java                         |  110 ++-
 opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java                             |   31 -
 opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionUtils.java                      |  386 ------------
 opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java             |   72 -
 opendj-cli/src/main/java/com/forgerock/opendj/cli/Utils.java                                           |   51 -
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/AbstractBrowseEntriesPanel.java |   51 -
 opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java       |   60 -
 opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/ui/LoginDialog.java                 |   41 
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/NodeRefresher.java         |   43 
 opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java                      |   85 +-
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java    |  186 ++---
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ErrorSearchingEntryPanel.java   |   31 
 opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java                    |  148 ----
 opendj-server-legacy/src/main/java/org/opends/quicksetup/util/ServerController.java                    |   29 
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java                |   30 
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/BrowserController.java     |   68 -
 opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/AuthenticationData.java             |   18 
 opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java                       |   19 
 opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCacheException.java                    |   46 
 opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java                  |   36 
 opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java                    |   60 -
 opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCache.java                             |   10 
 opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallUserData.java              |   52 +
 28 files changed, 524 insertions(+), 1,297 deletions(-)

diff --git a/opendj-cli/src/main/java/com/forgerock/opendj/cli/Utils.java b/opendj-cli/src/main/java/com/forgerock/opendj/cli/Utils.java
index 8c0aedd..1e1db17 100644
--- a/opendj-cli/src/main/java/com/forgerock/opendj/cli/Utils.java
+++ b/opendj-cli/src/main/java/com/forgerock/opendj/cli/Utils.java
@@ -36,11 +36,6 @@
 import java.util.StringTokenizer;
 import java.util.TimeZone;
 
-import javax.naming.AuthenticationException;
-import javax.naming.CommunicationException;
-import javax.naming.NamingException;
-import javax.naming.NamingSecurityException;
-import javax.naming.NoPermissionException;
 import javax.net.ssl.SSLHandshakeException;
 
 import org.forgerock.i18n.LocalizableMessage;
@@ -433,40 +428,6 @@
     }
 
     /**
-     * Returns a message object for the given NamingException.
-     *
-     * @param ne
-     *            The NamingException.
-     * @param hostPort
-     *            The hostPort representation of the server we were contacting when the NamingException occurred.
-     * @return A message object for the given NamingException.
-     */
-    public static LocalizableMessage getMessageForException(NamingException ne, String hostPort) {
-        String arg;
-        if (ne.getLocalizedMessage() != null) {
-            arg = ne.getLocalizedMessage();
-        } else if (ne.getExplanation() != null) {
-            arg = ne.getExplanation();
-        } else {
-            arg = ne.toString(true);
-        }
-
-        if (Utils.isCertificateException(ne)) {
-            return INFO_ERROR_READING_CONFIG_LDAP_CERTIFICATE_SERVER.get(hostPort, arg);
-        } else if (ne instanceof AuthenticationException) {
-            return INFO_CANNOT_CONNECT_TO_REMOTE_AUTHENTICATION.get(hostPort, arg);
-        } else if (ne instanceof NoPermissionException) {
-            return INFO_CANNOT_CONNECT_TO_REMOTE_PERMISSIONS.get(hostPort, arg);
-        } else if (ne instanceof NamingSecurityException) {
-            return INFO_CANNOT_CONNECT_TO_REMOTE_PERMISSIONS.get(hostPort, arg);
-        } else if (ne instanceof CommunicationException) {
-            return ERR_CANNOT_CONNECT_TO_REMOTE_COMMUNICATION.get(hostPort, arg);
-        } else {
-            return INFO_CANNOT_CONNECT_TO_REMOTE_GENERIC.get(hostPort, arg);
-        }
-    }
-
-    /**
      * Returns a message object for the given IOException.
      *
      * @param e
@@ -639,13 +600,13 @@
     }
 
     /**
-     * Repeats the given {@link char} n times.
+     * Repeats the given {@code char} n times.
      *
      * @param charToRepeat
-     *      The {@link char} to repeat.
+     *      The {code char} to repeat.
      * @param length
      *      The repetition count.
-     * @return The given {@link char} n times.
+     * @return The given {code char} n times.
      */
     public static String repeat(final char charToRepeat, final int length) {
         final char[] str = new char[length];
@@ -654,11 +615,11 @@
     }
 
     /**
-     * Return a {@link ValidationCallback<Integer>} which can be used to validate a port number.
+     * Return a {code ValidationCallback<Integer>} which can be used to validate a port number.
      *
      * @param defaultPort
      *        The default value to suggest to the user.
-     * @return a {@link ValidationCallback<Integer>} which can be used to validate a port number.
+     * @return a {code ValidationCallback<Integer>} which can be used to validate a port number.
      */
     public static ValidationCallback<Integer> portValidationCallback(final int defaultPort) {
         return new ValidationCallback<Integer>() {
@@ -707,7 +668,7 @@
      * if both provided {@link Argument} are presents in the command line arguments.
      *
      * @param errors
-     *         The {@link Collection<LocalizableMessage>} to use to add the conflict error (if occurs).
+     *         The {@code Collection<LocalizableMessage>} to use to add the conflict error (if occurs).
      * @param arg1
      *         The first {@link Argument} which should not be present if {@literal arg2} is.
      * @param arg2
diff --git a/opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCache.java b/opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCache.java
index c69aecf..085480d 100644
--- a/opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCache.java
+++ b/opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCache.java
@@ -30,8 +30,6 @@
 import java.util.Map;
 import java.util.Set;
 
-import javax.naming.NamingException;
-
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.ldap.DN;
@@ -205,7 +203,7 @@
           {
             updateReplicas(server, candidateReplicas, updatedReplicas);
           }
-          catch (NamingException | IOException e)
+          catch (IOException e)
           {
             server.setLastException(new TopologyCacheException(
                 TopologyCacheException.Type.GENERIC_READING_SERVER, e));
@@ -457,7 +455,7 @@
   private void updateReplicas(ServerDescriptor replicationServer,
                               Collection<ReplicaDescriptor> candidateReplicas,
                               Collection<ReplicaDescriptor> updatedReplicas)
-      throws NamingException, IOException
+      throws IOException
   {
     ServerLoader loader = getServerLoader(replicationServer.getAdsProperties());
     // only replicas have "server-id", but not replication servers
@@ -505,7 +503,7 @@
     }
   }
 
-  private void setMissingChanges(ReplicaDescriptor replica, SearchResultEntry sr) throws NamingException
+  private void setMissingChanges(ReplicaDescriptor replica, SearchResultEntry sr)
   {
     Integer value = asInteger(sr, "missing-changes");
     if (value != null)
@@ -522,7 +520,7 @@
     }
   }
 
-  private void setAgeOfOldestMissingChange(ReplicaDescriptor replica, SearchResultEntry sr) throws NamingException
+  private void setAgeOfOldestMissingChange(ReplicaDescriptor replica, SearchResultEntry sr)
   {
     String s = firstValueAsString(sr, "approx-older-change-not-synchronized-millis");
     if (s != null)
diff --git a/opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCacheException.java b/opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCacheException.java
index 8a3d7ee..5294922 100644
--- a/opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCacheException.java
+++ b/opendj-server-legacy/src/main/java/org/opends/admin/ads/TopologyCacheException.java
@@ -16,9 +16,9 @@
  */
 package org.opends.admin.ads;
 
-import javax.naming.NamingException;
-
+import org.forgerock.opendj.ldap.LdapException;
 import org.opends.admin.ads.util.ApplicationTrustManager;
+import org.opends.server.types.HostPort;
 import org.opends.server.types.OpenDsException;
 
 /**
@@ -29,7 +29,7 @@
 
   private static final long serialVersionUID = 1709535837273360382L;
   private final Type type;
-  private final String ldapUrl;
+  private final HostPort ldapHostPort;
   private final ApplicationTrustManager trustManager;
 
   /** Error type. */
@@ -60,7 +60,7 @@
   {
     super(ace);
     type = Type.GENERIC_READING_ADS;
-    ldapUrl = null;
+    ldapHostPort = null;
     trustManager = null;
   }
 
@@ -73,26 +73,24 @@
   {
     super(t);
     this.type = type;
-    this.ldapUrl = null;
+    this.ldapHostPort = null;
     this.trustManager = null;
   }
 
   /**
-   * Constructor for the exception that must be generated when a
-   * NamingException occurs.
+   * Constructor for the exception that must be generated when a LdapException occurs.
    * @param type the type of this exception.
-   * @param ne the NamingException that generated this exception.
-   * @param trustManager the ApplicationTrustManager used when the
-   * NamingException occurred.
-   * @param ldapUrl the LDAP URL of the server we where connected to (or trying
-   * to connect) when the NamingException was generated.
+   * @param e the LdapException that generated this exception.
+   * @param trustManager the ApplicationTrustManager used when the LdapException occurred.
+   * @param ldapHostPort the LDAP HostPort of the server we where connected to (or trying
+   * to connect) when the LdapException was generated.
    */
-  public TopologyCacheException(Type type, NamingException ne,
-      ApplicationTrustManager trustManager, String ldapUrl)
+  public TopologyCacheException(Type type, LdapException e,
+      ApplicationTrustManager trustManager, HostPort ldapHostPort)
   {
-    super(ne);
+    super(e);
     this.type = type;
-    this.ldapUrl = ldapUrl;
+    this.ldapHostPort = ldapHostPort;
     this.trustManager = trustManager;
   }
 
@@ -106,26 +104,14 @@
   }
 
   /**
-   * Returns the LDAP URL of the server we where connected to (or trying
-   * to connect) when this exception was generated.
-   * @return the LDAP URL of the server we where connected to (or trying
-   * to connect) when this exception was generated.
-   */
-  public String getLdapUrl()
-  {
-    return ldapUrl;
-  }
-
-  /**
    * Returns the host port representation of the server we where connected to
    * (or trying to connect) when this exception was generated.
    * @return the host port representation of the server we where connected to
    * (or trying to connect) when this exception was generated.
    */
-  public String getHostPort()
+  public HostPort getHostPort()
   {
-    int index = ldapUrl.indexOf("//");
-    return ldapUrl.substring(index + 2);
+    return ldapHostPort;
   }
 
   /**
diff --git a/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionUtils.java b/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionUtils.java
index df1f9c0..2326c9f 100644
--- a/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionUtils.java
+++ b/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionUtils.java
@@ -16,32 +16,12 @@
  */
 package org.opends.admin.ads.util;
 
-import java.io.IOException;
-import java.net.ConnectException;
 import java.util.Collections;
-import java.util.Hashtable;
 import java.util.Set;
 
-import javax.naming.CommunicationException;
-import javax.naming.Context;
-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.StartTlsRequest;
-import javax.naming.ldap.StartTlsResponse;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.TrustManager;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.ldap.DN;
 import org.forgerock.opendj.ldap.Entry;
 import org.forgerock.opendj.ldap.responses.SearchResultEntry;
-import org.opends.server.replication.plugin.EntryHistorical;
-import org.opends.server.schema.SchemaConstants;
 import org.opends.server.types.HostPort;
 
 import com.forgerock.opendj.cli.Utils;
@@ -49,379 +29,15 @@
 /**
  * Class providing some utilities to create LDAP connections using JNDI and
  * to manage entries retrieved using JNDI.
- *
  */
 public class ConnectionUtils
 {
-  private static final String STARTTLS_PROPERTY =
-    "org.opends.connectionutils.isstarttls";
-
-  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
-
-  /**
-   * Private constructor: this class cannot be instantiated.
-   */
+  /** Private constructor: this class cannot be instantiated. */
   private ConnectionUtils()
   {
   }
 
   /**
-   * Creates a clear LDAP connection and returns the corresponding LdapContext.
-   * This methods uses the specified parameters to create a JNDI environment
-   * hashtable and creates an InitialLdapContext instance.
-   *
-   * @param ldapURL
-   *          the target LDAP URL
-   * @param dn
-   *          passed as Context.SECURITY_PRINCIPAL if not null
-   * @param pwd
-   *          passed as Context.SECURITY_CREDENTIALS if not null
-   * @param timeout
-   *          passed as com.sun.jndi.ldap.connect.timeout if > 0
-   * @param env
-   *          null or additional environment properties
-   *
-   * @throws NamingException
-   *           the exception thrown when instantiating InitialLdapContext
-   *
-   * @return the created InitialLdapContext.
-   * @see javax.naming.Context
-   * @see javax.naming.ldap.InitialLdapContext
-   */
-  static InitialLdapContext createLdapContext(String ldapURL, String dn,
-      String pwd, int timeout, Hashtable<String, String> env)
-      throws NamingException
-  {
-    env = newEnvironmentFrom(ldapURL, env);
-    if (timeout >= 1)
-    {
-      env.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(timeout));
-    }
-    if (dn != null && pwd != null)
-    {
-      env.put(Context.SECURITY_PRINCIPAL, dn);
-      env.put(Context.SECURITY_CREDENTIALS, pwd);
-    }
-
-    /* Contains the DirContext and the Exception if any */
-    final Object[] pair = { null, null };
-    final Hashtable<String, String> fEnv = env;
-    Thread t = new Thread(new Runnable()
-    {
-      @Override
-      public void run()
-      {
-        try
-        {
-          pair[0] = new InitialLdapContext(fEnv, null);
-        } catch (NamingException ne)
-        {
-          pair[1] = ne;
-        } catch (Throwable t)
-        {
-          t.printStackTrace();
-          pair[1] = t;
-        }
-      }
-    });
-    t.setDaemon(true);
-    return getInitialLdapContext(t, pair, timeout);
-  }
-
-  /**
-   * Creates an LDAPS connection and returns the corresponding LdapContext.
-   * This method uses the TrusteSocketFactory class so that the specified
-   * trust manager gets called during the SSL handshake. If trust manager is
-   * null, certificates are not verified during SSL handshake.
-   *
-   * @param ldapsURL      the target *LDAPS* URL.
-   * @param dn            passed as Context.SECURITY_PRINCIPAL if not null.
-   * @param pwd           passed as Context.SECURITY_CREDENTIALS if not null.
-   * @param timeout       passed as com.sun.jndi.ldap.connect.timeout if > 0.
-   * @param env           null or additional environment properties.
-   * @param trustManager  null or the trust manager to be invoked during SSL
-   * negotiation.
-   * @param keyManager    null or the key manager to be invoked during SSL
-   * negotiation.
-   * @return the established connection with the given parameters.
-   *
-   * @throws NamingException the exception thrown when instantiating
-   * InitialLdapContext.
-   *
-   * @see javax.naming.Context
-   * @see javax.naming.ldap.InitialLdapContext
-   * @see TrustedSocketFactory
-   */
-  static InitialLdapContext createLdapsContext(String ldapsURL,
-      String dn, String pwd, int timeout, Hashtable<String, String> env,
-      TrustManager trustManager, final KeyManager keyManager) throws NamingException {
-    final Hashtable<String, String> newEnv = newEnvironmentFrom(ldapsURL, env);
-    newEnv.put("java.naming.ldap.factory.socket", TrustedSocketFactory.class.getName());
-
-    if (dn != null && pwd != null)
-    {
-      newEnv.put(Context.SECURITY_PRINCIPAL, dn);
-      newEnv.put(Context.SECURITY_CREDENTIALS, pwd);
-    }
-
-    if (trustManager == null)
-    {
-      trustManager = new BlindTrustManager();
-    }
-
-    /* Contains the DirContext and the Exception if any */
-    final Object[] pair = { null, null };
-    final TrustManager fTrustManager = trustManager;
-    Thread t = new Thread(new Runnable() {
-      @Override
-      public void run() {
-        try {
-          TrustedSocketFactory.setCurrentThreadTrustManager(fTrustManager, keyManager);
-          pair[0] = new InitialLdapContext(newEnv, null);
-        } catch (NamingException | RuntimeException ne) {
-          pair[1] = ne;
-        }
-      }
-    });
-    t.setDaemon(true);
-    return getInitialLdapContext(t, pair, timeout);
-  }
-
-  /**
-   * Creates an LDAP+StartTLS connection and returns the corresponding
-   * LdapContext.
-   * This method first creates an LdapContext with anonymous bind. Then it
-   * requests a StartTlsRequest extended operation. The StartTlsResponse is
-   * setup with the specified hostname verifier. Negotiation is done using a
-   * TrustSocketFactory so that the specified TrustManager gets called during
-   * the SSL handshake.
-   * If trust manager is null, certificates are not checked during SSL
-   * handshake.
-   *
-   * @param ldapURL       the target *LDAP* URL.
-   * @param dn            passed as Context.SECURITY_PRINCIPAL if not null.
-   * @param pwd           passed as Context.SECURITY_CREDENTIALS if not null.
-   * @param timeout       passed as com.sun.jndi.ldap.connect.timeout if > 0.
-   * @param env           null or additional environment properties.
-   * @param trustManager  null or the trust manager to be invoked during SSL
-   * negotiation.
-   * @param keyManager    null or the key manager to be invoked during SSL
-   * negotiation.
-   * @param verifier      null or the hostname verifier to be setup in the
-   * StartTlsResponse.
-   * @return the established connection with the given parameters.
-   *
-   * @throws NamingException the exception thrown when instantiating
-   * InitialLdapContext.
-   *
-   * @see javax.naming.Context
-   * @see javax.naming.ldap.InitialLdapContext
-   * @see javax.naming.ldap.StartTlsRequest
-   * @see javax.naming.ldap.StartTlsResponse
-   * @see TrustedSocketFactory
-   */
-  static InitialLdapContext createStartTLSContext(String ldapURL,
-      final String dn, final String pwd, int timeout, Hashtable<String, String> env,
-      TrustManager trustManager, final KeyManager keyManager,
-      HostnameVerifier verifier)
-  throws NamingException
-  {
-    if (trustManager == null)
-    {
-      trustManager = new BlindTrustManager();
-    }
-    if (verifier == null) {
-      verifier = new BlindHostnameVerifier();
-    }
-
-    final Hashtable<String, String> newEnv = newEnvironmentFrom(ldapURL, env);
-    newEnv.put(Context.SECURITY_AUTHENTICATION, "none");
-
-    /* Contains the DirContext and the Exception if any */
-    final Object[] pair = { null, null };
-    final TrustManager fTrustManager = trustManager;
-    final HostnameVerifier fVerifier = verifier;
-
-    Thread t = new Thread(new Runnable() {
-      @Override
-      public void run() {
-        try {
-          InitialLdapContext result = new InitialLdapContext(newEnv, null);
-
-          StartTlsResponse tls = (StartTlsResponse) result.extendedOperation(new StartTlsRequest());
-          tls.setHostnameVerifier(fVerifier);
-          try
-          {
-            tls.negotiate(new TrustedSocketFactory(fTrustManager, keyManager));
-          }
-          catch(IOException x) {
-            NamingException xx = new CommunicationException(
-                "Failed to negotiate Start TLS operation");
-            xx.initCause(x);
-            result.close();
-            throw xx;
-          }
-
-          result.addToEnvironment(STARTTLS_PROPERTY, "true");
-          if (dn != null)
-          {
-            result.addToEnvironment(Context.SECURITY_AUTHENTICATION , "simple");
-            result.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
-            if (pwd != null)
-            {
-              result.addToEnvironment(Context.SECURITY_CREDENTIALS, pwd);
-            }
-            result.reconnect(null);
-          }
-          pair[0] = result;
-        } catch (NamingException | RuntimeException ne)
-        {
-          pair[1] = ne;
-        }
-      }
-    });
-    t.setDaemon(true);
-    return getInitialLdapContext(t, pair, timeout);
-  }
-
-  private static Hashtable<String, String> copy(Hashtable<String, String> env) {
-    return env != null ? new Hashtable<>(env) : new Hashtable<String, String>();
-  }
-
-  private static Hashtable<String, String> newEnvironmentFrom(String ldapURL, Hashtable<String, String> env)
-  {
-    final Hashtable<String, String> copy = copy(env);
-    copy.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
-    copy.put("java.naming.ldap.attributes.binary", EntryHistorical.HISTORICAL_ATTRIBUTE_NAME);
-    copy.put(Context.PROVIDER_URL, ldapURL);
-    return copy;
-  }
-
-  /**
-   * Method used to know if we are connected as administrator in a server with a
-   * given InitialLdapContext.
-   * @param ctx the context.
-   * @return {@code true} if we are connected and read the configuration
-   * and {@code false} otherwise.
-   */
-  static boolean connectedAsAdministrativeUser(InitialLdapContext ctx)
-  {
-    try
-    {
-      // 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
-      {
-        while (sr.hasMore())
-        {
-          sr.next();
-        }
-      }
-      finally
-      {
-        try
-        {
-          sr.close();
-        }
-        catch(Exception ex)
-        {
-          logger.warn(LocalizableMessage.raw(
-              "Unexpected error closing enumeration on cn=Config entry", ex));
-        }
-      }
-      return true;
-    } catch (NamingException ne)
-    {
-      // Nothing to do.
-      return false;
-    } catch (Throwable t)
-    {
-      throw new IllegalStateException("Unexpected throwable.", t);
-    }
-  }
-
-  /**
-   * This is just a commodity method used to try to get an InitialLdapContext.
-   * @param t the Thread to be used to create the InitialLdapContext.
-   * @param pair an Object[] array that contains the InitialLdapContext and the
-   * Throwable if any occurred.
-   * @param timeout the timeout in milliseconds.  If we do not get to create the
-   * connection before the timeout a CommunicationException will be thrown.
-   * @return the created InitialLdapContext
-   * @throws NamingException if something goes wrong during the creation.
-   */
-  private static InitialLdapContext getInitialLdapContext(Thread t,
-      Object[] pair, int timeout) throws NamingException
-  {
-    try
-    {
-      if (timeout > 0)
-      {
-        t.start();
-        t.join(timeout);
-      } else
-      {
-        t.run();
-      }
-    } catch (InterruptedException x)
-    {
-      // This might happen for problems in sockets
-      // so it does not necessarily imply a bug
-    }
-
-    if (timeout > 0 && t.isAlive())
-    {
-      t.interrupt();
-      try
-      {
-        t.join(2000);
-      } catch (InterruptedException x)
-      {
-        // This might happen for problems in sockets
-        // so it does not necessarily imply a bug
-      }
-      throw connectionTimedOut();
-    }
-
-    Object connection = pair[0];
-    Object ex = pair[1];
-    if (connection == null && ex == null)
-    {
-      throw connectionTimedOut();
-    }
-
-    if (ex != null)
-    {
-      if (ex instanceof NamingException)
-      {
-        throw (NamingException) ex;
-      }
-      else if (ex instanceof RuntimeException)
-      {
-        throw (RuntimeException) ex;
-      }
-      else if (ex instanceof Throwable)
-      {
-        throw new IllegalStateException("Unexpected throwable occurred", (Throwable) ex);
-      }
-    }
-    return (InitialLdapContext) connection;
-  }
-
-  private static NamingException connectionTimedOut()
-  {
-    NamingException xx = new CommunicationException("Connection timed out");
-    xx.initCause(new ConnectException("Connection timed out"));
-    return xx;
-  }
-
-  /**
    * Returns the LDAP URL for the provided parameters.
    * @param hostPort the host name and LDAP port.
    * @param useLdaps whether to use LDAPS.
diff --git a/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java b/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java
index d0d0cb1..ce9447c 100644
--- a/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java
+++ b/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionWrapper.java
@@ -17,28 +17,20 @@
 
 import static org.forgerock.opendj.config.client.ldap.LDAPManagementContext.*;
 import static org.forgerock.opendj.ldap.LDAPConnectionFactory.*;
+import static org.forgerock.opendj.ldap.LdapException.*;
+import static org.forgerock.opendj.ldap.ResultCode.*;
 import static org.forgerock.opendj.ldap.requests.Requests.*;
 import static org.forgerock.util.time.Duration.*;
-import static org.opends.admin.ads.util.ConnectionUtils.*;
 import static org.opends.admin.ads.util.PreferredConnection.Type.*;
-import static org.opends.messages.AdminToolMessages.*;
 
 import java.io.Closeable;
-import java.net.URI;
-import java.net.URISyntaxException;
 import java.security.GeneralSecurityException;
 import java.util.concurrent.TimeUnit;
 
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.NoPermissionException;
-import javax.naming.ldap.InitialLdapContext;
 import javax.net.ssl.KeyManager;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManager;
 
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.config.LDAPProfile;
 import org.forgerock.opendj.ldap.Connection;
 import org.forgerock.opendj.ldap.DN;
@@ -63,11 +55,8 @@
  */
 public class ConnectionWrapper implements Closeable
 {
-  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
-
   private final LDAPConnectionFactory connectionFactory;
   private final Connection connection;
-  private final InitialLdapContext ldapContext;
   private final HostPort hostPort;
   private DN bindDn;
   private String bindPwd;
@@ -79,52 +68,6 @@
   /**
    * Creates a connection wrapper.
    *
-   * @param ldapUrl
-   *          the ldap URL containing the host name and port number to connect to
-   * @param connectionType
-   *          the type of connection (LDAP, LDAPS, START_TLS)
-   * @param bindDn
-   *          the bind DN
-   * @param bindPwd
-   *          the bind password
-   * @param connectTimeout
-   *          connect timeout to use for the connection
-   * @param trustManager
-   *          trust manager to use for a secure connection
-   * @throws NamingException
-   *           If an error occurs
-   */
-  public ConnectionWrapper(String ldapUrl, Type connectionType, DN bindDn, String bindPwd, int connectTimeout,
-      TrustManager trustManager) throws NamingException
-  {
-    this(toHostPort(ldapUrl), connectionType, bindDn, bindPwd, connectTimeout, trustManager, null);
-  }
-
-  /**
-   * 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
-    {
-      URI uri = new URI(ldapUrl);
-      return new HostPort(uri.getHost(), uri.getPort());
-    }
-    catch (URISyntaxException e)
-    {
-      throw new NamingException(e.getLocalizedMessage() + ". LDAP URL was: \"" + ldapUrl + "\"");
-    }
-  }
-
-  /**
-   * Creates a connection wrapper.
-   *
    * @param hostPort
    *          the host name and port number to connect to
    * @param connectionType
@@ -137,11 +80,11 @@
    *          connect timeout to use for the connection
    * @param trustManager
    *          trust manager to use for a secure connection
-   * @throws NamingException
+   * @throws LdapException
    *           If an error occurs
    */
   public ConnectionWrapper(HostPort hostPort, Type connectionType, DN bindDn, String bindPwd, int connectTimeout,
-      TrustManager trustManager) throws NamingException
+      TrustManager trustManager) throws LdapException
   {
     this(hostPort, connectionType, bindDn, bindPwd, connectTimeout, trustManager, null);
   }
@@ -151,10 +94,10 @@
    *
    * @param other
    *          the {@link ConnectionWrapper} to copy
-   * @throws NamingException
+   * @throws LdapException
    *           If an error occurs
    */
-  public ConnectionWrapper(ConnectionWrapper other) throws NamingException
+  public ConnectionWrapper(ConnectionWrapper other) throws LdapException
   {
     this(other.hostPort, other.connectionType, other.bindDn, other.bindPwd, other.connectTimeout,
         other.trustManager, other.keyManager);
@@ -177,11 +120,11 @@
    *          trust manager to use for a secure connection
    * @param keyManager
    *          key manager to use for a secure connection
-   * @throws NamingException
+   * @throws LdapException
    *           If an error occurs
    */
   public ConnectionWrapper(HostPort hostPort, PreferredConnection.Type connectionType, DN bindDn, String bindPwd,
-      int connectTimeout, TrustManager trustManager, KeyManager keyManager) throws NamingException
+      int connectTimeout, TrustManager trustManager, KeyManager keyManager) throws LdapException
   {
     this.hostPort = hostPort;
     this.connectionType = connectionType;
@@ -192,13 +135,12 @@
     this.keyManager = keyManager;
 
     final Options options = toOptions(connectionType, bindDn, bindPwd, connectTimeout, trustManager, keyManager);
-    ldapContext = createAdministrativeContext();
     connectionFactory = new LDAPConnectionFactory(hostPort.getHost(), hostPort.getPort(), options);
-    connection = buildConnection();
+    connection = connectionFactory.getConnection();
   }
 
   private static Options toOptions(Type connectionType, DN bindDn, String bindPwd, long connectTimeout,
-      TrustManager trustManager, KeyManager keyManager) throws NamingException
+      TrustManager trustManager, KeyManager keyManager) throws LdapException
   {
     final boolean isStartTls = START_TLS.equals(connectionType);
     final boolean isLdaps = LDAPS.equals(connectionType);
@@ -217,7 +159,7 @@
     return options;
   }
 
-  private static SSLContext getSSLContext(TrustManager trustManager, KeyManager keyManager) throws NamingException
+  private static SSLContext getSSLContext(TrustManager trustManager, KeyManager keyManager) throws LdapException
   {
     try
     {
@@ -228,7 +170,7 @@
     }
     catch (GeneralSecurityException e)
     {
-      throw new NamingException("Unable to perform SSL initialization:" + e.getMessage());
+      throw newLdapException(CLIENT_SIDE_PARAM_ERROR, "Unable to perform SSL initialization:" + e.getMessage());
     }
   }
 
@@ -259,21 +201,7 @@
    */
   public String getLdapUrl()
   {
-    return getEnvProperty(ldapContext, Context.PROVIDER_URL);
-  }
-
-  private static String getEnvProperty(InitialLdapContext ctx, String property)
-  {
-    try
-    {
-      return (String) ctx.getEnvironment().get(property);
-    }
-    catch (NamingException ne)
-    {
-      // This is really strange. Seems like a bug somewhere.
-      logger.warn(LocalizableMessage.raw("Naming exception getting environment of " + ctx, ne));
-      return null;
-    }
+    return (isLdaps() ? "ldaps" : "ldap") + "://" + getHostPort();
   }
 
   /**
@@ -296,45 +224,6 @@
     return getConnectionType() == START_TLS;
   }
 
-  private InitialLdapContext createAdministrativeContext() throws NamingException
-  {
-    final InitialLdapContext ctx = createAdministrativeContext0();
-    if (!connectedAsAdministrativeUser(ctx))
-    {
-      throw new NoPermissionException(ERR_NOT_ADMINISTRATIVE_USER.get().toString());
-    }
-    return ctx;
-  }
-
-  private InitialLdapContext createAdministrativeContext0() throws NamingException
-  {
-    final String ldapUrl = getLDAPUrl(getHostPort(), isLdaps());
-    final String bindDnStr = bindDn.toString();
-    switch (connectionType)
-    {
-    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);
-    }
-  }
-
-  private Connection buildConnection() throws NamingException
-  {
-    try
-    {
-      return connectionFactory.getConnection();
-    }
-    catch (LdapException e)
-    {
-      throw new NamingException("Unable to get a connection from connection factory:" + e.getMessage());
-    }
-  }
-
   /**
    * Returns the connection.
    *
@@ -356,16 +245,6 @@
   }
 
   /**
-   * Returns the ldap context (JNDI).
-   *
-   * @return the ldap context
-   */
-  public InitialLdapContext getLdapContext()
-  {
-    return ldapContext;
-  }
-
-  /**
    * Returns the host name and port number of this connection.
    *
    * @return the hostPort of this connection
@@ -389,7 +268,6 @@
   public void close()
   {
     StaticUtils.close(connectionFactory, connection);
-    StaticUtils.close(ldapContext);
   }
 
   @Override
diff --git a/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java b/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java
index 89a7466..93051d8 100644
--- a/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java
+++ b/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/PreferredConnection.java
@@ -16,9 +16,14 @@
  */
 package org.opends.admin.ads.util;
 
+import static org.opends.admin.ads.util.PreferredConnection.Type.*;
+
 import java.util.Collections;
+import java.util.Objects;
 import java.util.Set;
 
+import org.opends.server.types.HostPort;
+
 /**
  * A simple class that is used to be able to specify which URL and connection
  * type to use when we connect to a server.
@@ -36,18 +41,18 @@
     START_TLS
   }
 
-  private final String ldapUrl;
+  private final HostPort hostPort;
   private final Type type;
 
   /**
    * The constructor of the PreferredConnection.
-   * @param ldapUrl the LDAP URL to connect to the server.
+   * @param hostPort the host and port to connect to the server.
    * @param type the type of connection to be used to connect (required to
    * differentiate StartTLS and regular LDAP).
    */
-  public PreferredConnection(String ldapUrl, Type type)
+  public PreferredConnection(HostPort hostPort, Type type)
   {
-    this.ldapUrl = ldapUrl;
+    this.hostPort = hostPort;
     this.type = type;
   }
 
@@ -57,11 +62,22 @@
    */
   public String getLDAPURL()
   {
-    return ldapUrl;
+    return (type == LDAPS ? "ldaps" : "ldap") + "://" + hostPort;
+  }
+
+  /**
+   * Returns the host name and port number.
+   *
+   * @return the hostPort
+   */
+  public HostPort getHostPort()
+  {
+    return hostPort;
   }
 
   /**
    * Returns the type of the connection.
+   *
    * @return the type of the connection.
    */
   public Type getType()
@@ -72,7 +88,7 @@
   @Override
   public int hashCode()
   {
-    return (type + ldapUrl.toLowerCase()).hashCode();
+    return Objects.hash(type, hostPort);
   }
 
   @Override
@@ -85,8 +101,8 @@
     if (o instanceof PreferredConnection)
     {
       PreferredConnection p = (PreferredConnection)o;
-      return type == p.type
-          && ldapUrl.equalsIgnoreCase(p.getLDAPURL());
+      return Objects.equals(type, p.type)
+          && Objects.equals(hostPort, p.hostPort);
     }
     return false;
   }
@@ -94,7 +110,7 @@
   @Override
   public String toString()
   {
-    return type + ": " + ldapUrl;
+    return getLDAPURL();
   }
 
   /**
@@ -105,7 +121,7 @@
    */
   private static PreferredConnection getPreferredConnection(ConnectionWrapper conn)
   {
-    return new PreferredConnection(conn.getLdapUrl(), conn.getConnectionType());
+    return new PreferredConnection(conn.getHostPort(), conn.getConnectionType());
   }
 
   /**
diff --git a/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java b/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java
index 5af28a3..23d416d 100644
--- a/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java
+++ b/opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ServerLoader.java
@@ -16,26 +16,30 @@
  */
 package org.opends.admin.ads.util;
 
+import static org.forgerock.opendj.ldap.LdapException.*;
+import static org.forgerock.opendj.ldap.ResultCode.*;
 import static org.opends.admin.ads.util.PreferredConnection.Type.*;
 
+import java.net.URI;
+import java.net.URISyntaxException;
 import java.util.LinkedHashSet;
 import java.util.Map;
 import java.util.Set;
 
-import javax.naming.AuthenticationException;
-import javax.naming.NamingException;
-import javax.naming.NoPermissionException;
-import javax.naming.TimeLimitExceededException;
-
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.slf4j.LocalizedLogger;
+import org.forgerock.opendj.ldap.AuthenticationException;
+import org.forgerock.opendj.ldap.AuthorizationException;
 import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LdapException;
+import org.forgerock.opendj.ldap.ResultCode;
 import org.opends.admin.ads.ADSContext;
 import org.opends.admin.ads.ADSContext.ServerProperty;
 import org.opends.admin.ads.ServerDescriptor;
 import org.opends.admin.ads.TopologyCacheException;
 import org.opends.admin.ads.TopologyCacheException.Type;
 import org.opends.admin.ads.TopologyCacheFilter;
+import org.opends.server.types.HostPort;
 
 import com.forgerock.opendj.cli.Utils;
 
@@ -50,7 +54,7 @@
   private final Map<ServerProperty, Object> serverProperties;
   private boolean isOver;
   private boolean isInterrupted;
-  private String lastLdapUrl;
+  private HostPort lastLdapHostPort;
   private TopologyCacheException lastException;
   private ServerDescriptor serverDescriptor;
   private final ApplicationTrustManager trustManager;
@@ -123,20 +127,31 @@
     if (!isOver)
     {
       isInterrupted = true;
-      String ldapUrl = lastLdapUrl;
+      HostPort ldapUrl = lastLdapHostPort;
       if (ldapUrl == null)
       {
-        LinkedHashSet<PreferredConnection> urls = getLDAPURLsByPreference();
-        if (!urls.isEmpty())
+        try
         {
-          ldapUrl = urls.iterator().next().getLDAPURL();
+          LinkedHashSet<PreferredConnection> urls = getLDAPURLsByPreference();
+          if (!urls.isEmpty())
+          {
+            ldapUrl = urls.iterator().next().getHostPort();
+          }
+        }
+        catch (LdapException e)
+        {
+          lastException = new TopologyCacheException(
+              TopologyCacheException.Type.GENERIC_READING_SERVER,
+              newLdapException(ResultCode.CLIENT_SIDE_PARAM_ERROR,
+              e.getLocalizedMessage()), trustManager, ldapUrl);
         }
       }
+      final String diagnosticMsg = "Timeout reading server: " + ldapUrl;
       lastException = new TopologyCacheException(
           TopologyCacheException.Type.TIMEOUT,
-          new TimeLimitExceededException("Timeout reading server: "+ldapUrl),
+          newLdapException(ResultCode.TIME_LIMIT_EXCEEDED, diagnosticMsg),
           trustManager, ldapUrl);
-      logger.warn(LocalizableMessage.raw("Timeout reading server: "+ldapUrl));
+      logger.warn(LocalizableMessage.raw(diagnosticMsg));
     }
     super.interrupt();
   }
@@ -154,35 +169,35 @@
       serverDescriptor.setAdsProperties(serverProperties);
       serverDescriptor.updateAdsPropertiesWithServerProperties();
     }
-    catch (NoPermissionException e)
+    catch (AuthorizationException e)
     {
-      logger.warn(LocalizableMessage.raw("Permissions error reading server: " + lastLdapUrl, e));
+      logger.warn(LocalizableMessage.raw("Permissions error reading server: " + lastLdapHostPort, e));
       Type type = isAdministratorDn()
           ? TopologyCacheException.Type.NO_PERMISSIONS
           : TopologyCacheException.Type.NOT_GLOBAL_ADMINISTRATOR;
-      lastException = new TopologyCacheException(type, e, trustManager, lastLdapUrl);
+      lastException = new TopologyCacheException(type, e, trustManager, lastLdapHostPort);
     }
     catch (AuthenticationException e)
     {
-      logger.warn(LocalizableMessage.raw("Authentication exception: " + lastLdapUrl, e));
+      logger.warn(LocalizableMessage.raw("Authentication exception: " + lastLdapHostPort, e));
       Type type = isAdministratorDn()
           ? TopologyCacheException.Type.GENERIC_READING_SERVER
           : TopologyCacheException.Type.NOT_GLOBAL_ADMINISTRATOR;
-      lastException = new TopologyCacheException(type, e, trustManager, lastLdapUrl);
+      lastException = new TopologyCacheException(type, e, trustManager, lastLdapHostPort);
     }
-    catch (NamingException e)
+    catch (LdapException e)
     {
-      logger.warn(LocalizableMessage.raw("NamingException error reading server: " + lastLdapUrl, e));
+      logger.warn(LocalizableMessage.raw("LdapException error reading server: " + lastLdapHostPort, e));
       Type type = connCreated
           ? TopologyCacheException.Type.GENERIC_READING_SERVER
           : TopologyCacheException.Type.GENERIC_CREATING_CONNECTION;
-      lastException = new TopologyCacheException(type, e, trustManager, lastLdapUrl);
+      lastException = new TopologyCacheException(type, e, trustManager, lastLdapHostPort);
     }
     catch (Throwable t)
     {
       if (!isInterrupted)
       {
-        logger.warn(LocalizableMessage.raw("Generic error reading server: " + lastLdapUrl, t));
+        logger.warn(LocalizableMessage.raw("Generic error reading server: " + lastLdapHostPort, t));
         logger.warn(LocalizableMessage.raw("server Properties: " + serverProperties));
         lastException = new TopologyCacheException(TopologyCacheException.Type.BUG, t);
       }
@@ -197,10 +212,10 @@
    * Returns a Connection Wrapper.
    *
    * @return the connection wrapper
-   * @throws NamingException
+   * @throws LdapException
    *           If an error occurs.
    */
-  public ConnectionWrapper createConnectionWrapper() throws NamingException
+  public ConnectionWrapper createConnectionWrapper() throws LdapException
   {
     if (trustManager != null)
     {
@@ -213,15 +228,10 @@
     /* Try to connect to the server in a certain order of preference.  If an
      * URL fails, we will try with the others.
      */
-    for (PreferredConnection connection : getLDAPURLsByPreference())
+    for (PreferredConnection conn : getLDAPURLsByPreference())
     {
-      lastLdapUrl = connection.getLDAPURL();
-      ConnectionWrapper conn =
-          new ConnectionWrapper(lastLdapUrl, connection.getType(), dn, pwd, timeout, trustManager);
-      if (conn.getLdapContext() != null)
-      {
-        return conn;
-      }
+      lastLdapHostPort = conn.getHostPort();
+      return new ConnectionWrapper(conn.getHostPort(), conn.getType(), dn, pwd, timeout, trustManager);
     }
     return null;
   }
@@ -361,8 +371,9 @@
    * They are ordered so that the first URL is the preferred URL to be used.
    * @return the list of LDAP URLs that can be used to connect to the server.
    * They are ordered so that the first URL is the preferred URL to be used.
+   * @throws LdapException if a problem occurs decoding the ldapURLs
    */
-  private LinkedHashSet<PreferredConnection> getLDAPURLsByPreference()
+  private LinkedHashSet<PreferredConnection> getLDAPURLsByPreference() throws LdapException
   {
     LinkedHashSet<PreferredConnection> ldapUrls = new LinkedHashSet<>();
 
@@ -387,20 +398,47 @@
 
     if (adminConnectorUrl != null)
     {
-      ldapUrls.add(new PreferredConnection(adminConnectorUrl, LDAPS));
+      ldapUrls.add(newPreferredConnection(adminConnectorUrl, LDAPS));
     }
     if (ldapsUrl != null)
     {
-      ldapUrls.add(new PreferredConnection(ldapsUrl, LDAPS));
+      ldapUrls.add(newPreferredConnection(ldapsUrl, LDAPS));
     }
     if (startTLSUrl != null)
     {
-      ldapUrls.add(new PreferredConnection(startTLSUrl, START_TLS));
+      ldapUrls.add(newPreferredConnection(startTLSUrl, START_TLS));
     }
     if (ldapUrl != null)
     {
-      ldapUrls.add(new PreferredConnection(ldapUrl, LDAP));
+      ldapUrls.add(newPreferredConnection(ldapUrl, LDAP));
     }
     return ldapUrls;
   }
+
+  private PreferredConnection newPreferredConnection(String ldapUrl, PreferredConnection.Type type) throws LdapException
+  {
+    return new PreferredConnection(toHostPort(ldapUrl), type);
+  }
+
+  /**
+   * Converts an ldapUrl to a HostPort.
+   *
+   * @param ldapUrl
+   *          the ldapUrl to convert
+   * @return the host and port extracted from the ldapUrl
+   * @throws LdapException
+   *           if the ldapUrl is not a valid URL
+   */
+  public static HostPort toHostPort(String ldapUrl) throws LdapException
+  {
+    try
+    {
+      URI uri = new URI(ldapUrl);
+      return new HostPort(uri.getHost(), uri.getPort());
+    }
+    catch (URISyntaxException e)
+    {
+      throw newLdapException(CLIENT_SIDE_PARAM_ERROR, e.getLocalizedMessage() + ". LDAP URL was: \"" + ldapUrl + "\"");
+    }
+  }
 }
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/BrowserController.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/BrowserController.java
index 220fd83..e035dbb 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/BrowserController.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/BrowserController.java
@@ -24,17 +24,12 @@
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Enumeration;
-import java.util.LinkedList;
-import java.util.List;
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
-import javax.naming.NameNotFoundException;
-import javax.naming.NamingException;
-import javax.naming.directory.SearchControls;
 import javax.swing.Icon;
 import javax.swing.JTree;
 import javax.swing.SwingUtilities;
@@ -46,9 +41,10 @@
 
 import org.forgerock.opendj.ldap.DN;
 import org.forgerock.opendj.ldap.Entry;
+import org.forgerock.opendj.ldap.EntryNotFoundException;
 import org.forgerock.opendj.ldap.Filter;
+import org.forgerock.opendj.ldap.LdapException;
 import org.forgerock.opendj.ldap.SortKey;
-import org.forgerock.opendj.ldap.controls.Control;
 import org.forgerock.opendj.ldap.controls.ManageDsaITRequestControl;
 import org.forgerock.opendj.ldap.controls.ServerSideSortRequestControl;
 import org.forgerock.opendj.ldap.responses.SearchResultEntry;
@@ -861,10 +857,10 @@
   /**
    * Return the LDAP connection to reading the base entry of a node.
    * @param node the node for which we want the LDAP connection.
-   * @throws NamingException if there is an error retrieving the connection.
+   * @throws LdapException if there is an error retrieving the connection.
    * @return the LDAP connection to reading the base entry of a node.
    */
-  ConnectionWithControls findConnectionForLocalEntry(BasicNode node) throws NamingException {
+  ConnectionWithControls findConnectionForLocalEntry(BasicNode node) throws LdapException {
     return findConnectionForLocalEntry(node, isConfigurationNode(node));
   }
 
@@ -872,11 +868,11 @@
    * Return the LDAP connection to reading the base entry of a node.
    * @param node the node for which we want toe LDAP connection.
    * @param isConfigurationNode whether the node is a configuration node or not.
-   * @throws NamingException if there is an error retrieving the connection.
+   * @throws LdapException if there is an error retrieving the connection.
    * @return the LDAP connection to reading the base entry of a node.
    */
   private ConnectionWithControls findConnectionForLocalEntry(BasicNode node,
-      boolean isConfigurationNode) throws NamingException
+      boolean isConfigurationNode) throws LdapException
   {
     if (node == rootNode) {
       return connConfig;
@@ -893,8 +889,7 @@
   /**
    * Returns whether a given node is a configuration node or not.
    * @param node the node to analyze.
-   * @return {@code true} if the node is a configuration node and
-   * {@code false} otherwise.
+   * @return {@code true} if the node is a configuration node, {@code false} otherwise.
    */
   public boolean isConfigurationNode(BasicNode node)
   {
@@ -926,9 +921,9 @@
    * local or remote entry).
    * @param node the node for which we want toe LDAP connection.
    * @return the LDAP connection to search the displayed entry.
-   * @throws NamingException if there is an error retrieving the connection.
+   * @throws LdapException if there is an error retrieving the connection.
    */
-  public ConnectionWithControls findConnectionForDisplayedEntry(BasicNode node) throws NamingException {
+  public ConnectionWithControls findConnectionForDisplayedEntry(BasicNode node) throws LdapException {
     return findConnectionForDisplayedEntry(node, isConfigurationNode(node));
   }
 
@@ -938,10 +933,10 @@
    * @param node the node for which we want toe LDAP connection.
    * @param isConfigurationNode whether the node is a configuration node or not.
    * @return the LDAP connection to search the displayed entry.
-   * @throws NamingException if there is an error retrieving the connection.
+   * @throws LdapException if there is an error retrieving the connection.
    */
   private ConnectionWithControls findConnectionForDisplayedEntry(BasicNode node,
-      boolean isConfigurationNode) throws NamingException {
+      boolean isConfigurationNode) throws LdapException {
     if (isFollowReferrals() && node.getRemoteUrl() != null)
     {
       return connectionPool.getConnection(node.getRemoteUrl());
@@ -1078,34 +1073,6 @@
   }
 
   /**
-   * Returns the basic search controls.
-   * @return the basic search controls.
-   */
-  SearchControls getBasicSearchControls() {
-    SearchControls searchControls = new SearchControls();
-    searchControls.setCountLimit(maxChildren);
-    return searchControls;
-  }
-
-  /**
-   * Returns the request controls to search user data.
-   * @return the request controls to search user data.
-   */
-  private List<Control> getRequestControls()
-  {
-    List<Control> controls = new LinkedList<>();
-    if (sortControl != null)
-    {
-      controls.add(sortControl);
-    }
-    if (isFollowReferrals())
-    {
-      controls.add(followReferralsControl);
-    }
-    return controls;
-  }
-
-  /**
    * Callbacks invoked by task classes
    * =================================
    *
@@ -1145,11 +1112,10 @@
     }
 
     if (newState == NodeRefresher.State.FAILED) {
-      // In case of NameNotFoundException, we simply remove the node from the
-      // tree.
+      // In case of EntryNotFoundException, we simply remove the node from the tree.
       // Except when it's due a to referral resolution: we keep the node
       // in order the user can fix the referral.
-      if (isNameNotFoundException(task.getException())
+      if (task.getException() instanceof EntryNotFoundException
           && oldState != NodeRefresher.State.SOLVING_REFERRAL) {
         removeOneNode(node);
       }
@@ -1700,14 +1666,6 @@
   }
 
   /**
-   * Return {@code true} if x is a non {@code null} NameNotFoundException.
-   * @return {@code true} if x is a non {@code null} NameNotFoundException.
-   */
-  private boolean isNameNotFoundException(Object x) {
-    return x instanceof NameNotFoundException;
-  }
-
-  /**
    * Get the value of the numSubordinates attribute.
    * If numSubordinates is not present, returns 0.
    * @param entry the entry to analyze.
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/LDAPConnectionPool.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/LDAPConnectionPool.java
index 5e3a443..d31fa1a 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/LDAPConnectionPool.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/LDAPConnectionPool.java
@@ -21,10 +21,10 @@
 import java.util.ArrayList;
 import java.util.HashMap;
 
-import javax.naming.NamingException;
 import javax.net.ssl.KeyManager;
 
 import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LdapException;
 import org.forgerock.opendj.ldap.SearchScope;
 import org.forgerock.opendj.ldap.controls.ManageDsaITRequestControl;
 import org.forgerock.opendj.ldap.controls.ServerSideSortRequestControl;
@@ -123,11 +123,10 @@
    *
    * @param conn
    *          the connection to be unregistered.
-   * @throws NamingException
+   * @throws LdapException
    *           if there is a problem unregistering the connection.
    */
-  public void unregisterConnection(ConnectionWrapper conn)
-  throws NamingException
+  public void unregisterConnection(ConnectionWrapper conn) throws LdapException
   {
     LDAPURL url = makeLDAPUrl(conn);
     unRegisterAuth(url);
@@ -153,15 +152,14 @@
    * of the URL, getConnection() makes a new one and call connect().
    * If authentication data available for this protocol/host/port,
    * getConnection() call bind() on the new connection.
-   * If connect() or bind() failed, getConnection() forward the
-   * NamingException.
+   * If connect() or bind() failed, getConnection() forward the LdapException.
    * When getConnection() succeeds, the returned connection must
    * be passed to releaseConnection() after use.
    * @param ldapUrl the LDAP URL to which the connection must connect.
    * @return a connection to the provided LDAP URL.
-   * @throws NamingException if there was an error connecting.
+   * @throws LdapException if there was an error connecting.
    */
-  public ConnectionWithControls getConnection(LDAPURL ldapUrl) throws NamingException
+  public ConnectionWithControls getConnection(LDAPURL ldapUrl) throws LdapException
   {
     String key = makeKeyFromLDAPUrl(ldapUrl);
     ConnectionRecord cr;
@@ -198,7 +196,7 @@
           }
         }
       }
-      catch(NamingException x) {
+      catch (LdapException x) {
         synchronized (this) {
           cr.counter--;
           if (cr.counter == 0) {
@@ -280,17 +278,17 @@
    * specified in the LDAPURl, they are replaced by the new data.
    * If true is passed as 'connect' parameter, registerAuth() creates the
    * connection and attempts to connect() and bind() . If connect() or bind()
-   * fail, registerAuth() forwards the NamingException and does not register
+   * fail, registerAuth() forwards the LdapException and does not register
    * the authentication data.
    * @param ldapUrl the LDAP URL of the server.
    * @param dn the bind DN.
    * @param pw the password.
    * @param connect whether to connect or not to the server with the
    * provided authentication (for testing purposes).
-   * @throws NamingException if an error occurs connecting.
+   * @throws LdapException if an error occurs connecting.
    */
   private void registerAuth(LDAPURL ldapUrl, DN dn, String pw,
-      boolean connect) throws NamingException {
+      boolean connect) throws LdapException {
 
     String key = makeKeyFromLDAPUrl(ldapUrl);
     final AuthRecord ar = new AuthRecord();
@@ -314,7 +312,6 @@
       }
     }
     notifyListeners();
-
   }
 
 
@@ -329,7 +326,7 @@
     try {
       registerAuth(url, conn.getBindDn(), conn.getBindPassword(), false);
     }
-    catch (NamingException x) {
+    catch (LdapException x) {
       throw new RuntimeException("Bug");
     }
   }
@@ -338,11 +335,11 @@
   /**
    * Unregister authentication data.
    * If for the given url there's a connection, try to bind as anonymous.
-   * If unbind fails throw NamingException.
+   * If unbind fails throw LdapException.
    * @param ldapUrl the url associated with the authentication to be unregistered.
-   * @throws NamingException if the unbind fails.
+   * @throws LdapException if the unbind fails.
    */
-  private void unRegisterAuth(LDAPURL ldapUrl) throws NamingException {
+  private void unRegisterAuth(LDAPURL ldapUrl) throws LdapException {
     String key = makeKeyFromLDAPUrl(ldapUrl);
 
     authTable.remove(key);
@@ -396,9 +393,9 @@
    * @param ldapUrl the LDAP URL.
    * @param ar the authentication information.
    * @return a connection.
-   * @throws NamingException if an error occurs when connecting.
+   * @throws LdapException if an error occurs when connecting.
    */
-  private ConnectionWithControls createLDAPConnection(LDAPURL ldapUrl, AuthRecord ar) throws NamingException
+  private ConnectionWithControls createLDAPConnection(LDAPURL ldapUrl, AuthRecord ar) throws LdapException
   {
     final HostPort hostPort = new HostPort(ldapUrl.getHost(), ldapUrl.getPort());
     final Type connectiontype = isSecureLDAPUrl(ldapUrl) ? LDAPS : LDAP;
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/NodeRefresher.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/NodeRefresher.java
index 8dd1954..64b6d40 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/NodeRefresher.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/browser/NodeRefresher.java
@@ -28,9 +28,6 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.naming.InterruptedNamingException;
-import javax.naming.NameNotFoundException;
-import javax.naming.NamingException;
 import javax.swing.SwingUtilities;
 import javax.swing.tree.TreeNode;
 
@@ -266,9 +263,9 @@
         }
       }
     }
-    catch (NamingException ne)
+    catch (LdapException e)
     {
-      exception = ne;
+      exception = e;
       exceptionArg = null;
     }
     catch(SearchAbandonException x) {
@@ -396,7 +393,7 @@
           changeStateTo(State.FINISHED);
       }
     }
-    catch(IOException | NamingException x) {
+    catch (IOException x) {
       throwAbandonIfNeeded(x);
     }
     finally {
@@ -414,10 +411,9 @@
    * limiting the number of hops.
    * @throws SearchAbandonException if the hop count limit for referrals has
    * been exceeded.
-   * @throws NamingException if an error occurred searching the entry.
+   * @throws LdapException if an error occurred searching the entry.
    */
-  private void runSolveReferral()
-  throws SearchAbandonException, NamingException {
+  private void runSolveReferral() throws SearchAbandonException, LdapException {
     int hopCount = 0;
     String[] referral = getNode().getReferral();
     while (referral != null && hopCount < 10)
@@ -504,7 +500,7 @@
           }
           if (!found)
           {
-            throw new NameNotFoundException();
+            throw newLdapException(NO_SUCH_OBJECT);
           }
         }
         catch (LdapException e)
@@ -524,10 +520,7 @@
         }
         throwAbandonIfNeeded(null);
       }
-      catch (InterruptedNamingException x) {
-        throwAbandonIfNeeded(x);
-      }
-      catch (NamingException | IOException | LocalizedIllegalArgumentException | DirectoryException x)
+      catch (IOException | LocalizedIllegalArgumentException | DirectoryException x)
       {
         lastException = x;
         lastExceptionArg = referral[i];
@@ -584,10 +577,9 @@
   /**
    * Detects whether the entries has children or not.
    * @throws SearchAbandonException if the search was abandoned.
-   * @throws NamingException if an error during the search occurred.
+   * @throws LdapException if an error during the search occurred.
    */
-  private void runDetectChildren()
-  throws SearchAbandonException, NamingException {
+  private void runDetectChildren() throws SearchAbandonException, LdapException {
     if (controller.isShowContainerOnly() || !isNumSubOrdinatesUsable()) {
       runDetectChildrenManually();
     }
@@ -638,10 +630,6 @@
         throwAbandonIfNeeded(e);
       }
     }
-    catch (NamingException x)
-    {
-      throwAbandonIfNeeded(x);
-    }
     finally {
       if (conn != null) {
         controller.releaseLDAPConnection(conn);
@@ -655,7 +643,7 @@
    * is listed in in the hacker.
    * Note: *usable* means *usable for detecting children presence*.
    */
-  private boolean isNumSubOrdinatesUsable() throws NamingException {
+  private boolean isNumSubOrdinatesUsable() throws LdapException {
     SearchResultEntry entry = getDisplayedEntry();
     boolean hasSubOrdinates = BrowserController.getHasSubOrdinates(entry);
     if (!hasSubOrdinates)
@@ -749,7 +737,7 @@
         throwAbandonIfNeeded(e);
       }
     }
-    catch (NamingException | IOException e)
+    catch (IOException e)
     {
       throwAbandonIfNeeded(e);
     }
@@ -815,9 +803,9 @@
    * The code assumes that the request controls are set in the connection.
    * @param conn the connection to be used.
    * @param dn the DN of the entry to be searched.
-   * @throws NamingException if an error occurs.
+   * @throws LdapException if an error occurs.
    */
-  private SearchResultEntry searchManuallyEntry(ConnectionWithControls conn, DN dn) throws IOException
+  private SearchResultEntry searchManuallyEntry(ConnectionWithControls conn, DN dn) throws LdapException
   {
     SearchRequest request =
         newSearchRequest(dn, BASE_OBJECT, controller.getObjectSearchFilter(), controller.getAttrsForRedSearch())
@@ -854,7 +842,7 @@
    */
   private void throwAbandonIfNeeded(Exception x) throws SearchAbandonException {
     if (x != null) {
-      if (x instanceof InterruptedException || x instanceof InterruptedNamingException)
+      if (x instanceof InterruptedException)
       {
         throw new SearchAbandonException(State.INTERRUPTED, x, null);
       }
@@ -888,9 +876,8 @@
    * @param entry the search result.
    * @return {@code true} if the entry's objectClass contains 'referral'
    * and the attribute 'ref' is present and {@code false} otherwise.
-   * @throws NamingException if an error occurs.
    */
-  private static boolean isReferralEntry(SearchResultEntry entry) throws NamingException
+  private static boolean isReferralEntry(SearchResultEntry entry)
   {
     for (String value : asSetOfString(entry, "objectClass"))
     {
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java
index 231a345..95b557a 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java
@@ -16,10 +16,8 @@
  */
 package org.opends.guitools.controlpanel.datamodel;
 
-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.admin.ads.util.PreferredConnection.Type.*;
 import static org.opends.server.tools.ConfigureWindowsService.*;
 
@@ -34,13 +32,12 @@
 import java.util.Set;
 import java.util.SortedSet;
 
-import javax.naming.NamingException;
-
 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.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LdapException;
 import org.opends.admin.ads.util.ApplicationTrustManager;
 import org.opends.admin.ads.util.ConnectionWrapper;
 import org.opends.guitools.controlpanel.browser.IconPool;
@@ -63,6 +60,7 @@
 import org.opends.guitools.controlpanel.util.Utilities;
 import org.opends.quicksetup.util.UIKeyStore;
 import org.opends.quicksetup.util.Utils;
+import org.opends.server.types.HostPort;
 import org.opends.server.util.DynamicConstants;
 import org.opends.server.util.StaticUtils;
 
@@ -98,15 +96,14 @@
     ConnectionProtocolPolicy.USE_MOST_SECURE_AVAILABLE;
 
   private ServerDescriptor serverDesc;
-  private String ldapURL;
-  private String startTLSURL;
-  private String ldapsURL;
-  private String adminConnectorURL;
-  private String localAdminConnectorURL;
+  private HostPort ldapHostPort;
+  private HostPort startTlsHostPort;
+  private HostPort ldapsHostPort;
+  private HostPort adminConnectorHostPort;
+  private HostPort localAdminConnectorHostPort;
   private DN lastWorkingBindDN;
   private String lastWorkingBindPwd;
-  private String lastRemoteHostName;
-  private String lastRemoteAdministrationURL;
+  private HostPort lastRemoteHostPort;
 
   private boolean isLocal = true;
 
@@ -296,8 +293,7 @@
     {
       lastWorkingBindDN = connWrapper.getBindDn();
       lastWorkingBindPwd = connWrapper.getBindPassword();
-      lastRemoteHostName = connWrapper.getHostPort().getHost();
-      lastRemoteAdministrationURL = connWrapper.getLdapUrl();
+      lastRemoteHostPort = connWrapper.getHostPort();
     }
   }
 
@@ -313,12 +309,14 @@
   }
 
   /**
-   * Sets the dir context to be used by the ControlPanelInfo to retrieve
-   * user data.
-   * @param conn the connection.
-   * @throws NamingException if there is a problem updating the connection pool.
+   * Sets the connection to be used by the ControlPanelInfo to retrieve user data.
+   *
+   * @param conn
+   *          the connection.
+   * @throws LdapException
+   *           if there is a problem updating the connection pool.
    */
-  public void setUserDataDirContext(ConnectionWrapper conn) throws NamingException
+  public void setUserDataDirContext(ConnectionWrapper conn) throws LdapException
   {
     if (userDataConn != null)
     {
@@ -412,9 +410,9 @@
       desc.setInstancePath(Utils.getInstancePathFromInstallPath(installPath));
       desc.setWindowsServiceEnabled(isWindows() && serviceState() == SERVICE_STATE_ENABLED);
     }
-    else if (lastRemoteHostName != null)
+    else if (lastRemoteHostPort != null)
     {
-      desc.setHostname(lastRemoteHostName);
+      desc.setHostname(lastRemoteHostPort.getHost());
     }
 
     ConfigReader reader;
@@ -457,14 +455,14 @@
           {
             connWrapper = Utilities.getAdminDirContext(this, lastWorkingBindDN, lastWorkingBindPwd);
           }
-          else if (lastRemoteAdministrationURL != null)
+          else if (lastRemoteHostPort != null)
           {
             connWrapper = new ConnectionWrapper(
-                lastRemoteAdministrationURL, LDAPS, lastWorkingBindDN, lastWorkingBindPwd,
+                lastRemoteHostPort, LDAPS, lastWorkingBindDN, lastWorkingBindPwd,
                 getConnectTimeout(), getTrustManager());
           }
         }
-        catch (ConfigReadException | NamingException | IOException ignored)
+        catch (ConfigReadException | IOException ignored)
         {
           // Ignore: we will ask the user for credentials.
         }
@@ -549,14 +547,14 @@
     if (serverDesc == null || !serverDesc.equals(desc))
     {
       serverDesc = desc;
-      ldapURL = getURL(serverDesc, ConnectionHandlerDescriptor.Protocol.LDAP);
-      ldapsURL = getURL(serverDesc, ConnectionHandlerDescriptor.Protocol.LDAPS);
-      adminConnectorURL = getAdminConnectorURL(serverDesc);
+      ldapHostPort = getHostPort(serverDesc, ConnectionHandlerDescriptor.Protocol.LDAP);
+      ldapsHostPort = getHostPort(serverDesc, ConnectionHandlerDescriptor.Protocol.LDAPS);
+      adminConnectorHostPort = getAdminConnectorHostPort(serverDesc);
       if (serverDesc.isLocal())
       {
-        localAdminConnectorURL = adminConnectorURL;
+        localAdminConnectorHostPort = adminConnectorHostPort;
       }
-      startTLSURL = getURL(serverDesc, ConnectionHandlerDescriptor.Protocol.LDAP_STARTTLS);
+      startTlsHostPort = getHostPort(serverDesc, ConnectionHandlerDescriptor.Protocol.LDAP_STARTTLS);
       ConfigurationChangeEvent ev = new ConfigurationChangeEvent(this, desc);
       for (ConfigChangeListener listener : configListeners)
       {
@@ -816,80 +814,79 @@
   }
 
   /**
-   * Gets the LDAPS URL based in what is read in the configuration. It
-   * returns {@code null} if no LDAPS URL was found.
-   * @return the LDAPS URL to be used to connect to the server.
+   * Gets the LDAPS HostPort based in what is read in the configuration. It
+   * returns {@code null} if no LDAPS HostPort was found.
+   * @return the LDAPS HostPort to be used to connect to the server.
    */
-  public String getLDAPSURL()
+  public HostPort getLdapsHostPort()
   {
-    return ldapsURL;
+    return ldapsHostPort;
   }
 
   /**
-   * Gets the Administration Connector URL based in what is read in the
+   * Gets the Administration Connector HostPort based in what is read in the
    * configuration. It returns {@code null} if no Administration
-   * Connector URL was found.
-   * @return the Administration Connector URL to be used to connect
+   * Connector HostPort was found.
+   * @return the Administration Connector HostPort to be used to connect
    * to the server.
    */
-  public String getAdminConnectorURL()
+  public HostPort getAdminConnectorHostPort()
   {
     if (isLocal)
     {
-      // If the user set isLocal to true, we want to return the localAdminConnectorURL
+      // If the user set isLocal to true, we want to return the localAdminConnectorHostPort
       // (in particular if regenerateDescriptor has not been called).
-      return localAdminConnectorURL;
+      return localAdminConnectorHostPort;
     }
-    return adminConnectorURL;
+    return adminConnectorHostPort;
   }
 
   /**
-   * Gets the Administration Connector URL based in what is read in the local
+   * Gets the Administration Connector HostPort based in what is read in the local
    * configuration. It returns {@code null} if no Administration
-   * Connector URL was found.
-   * @return the Administration Connector URL to be used to connect
+   * Connector HostPort was found.
+   * @return the Administration Connector HostPort to be used to connect
    * to the local server.
    */
-  public String getLocalAdminConnectorURL()
+  public HostPort getLocalAdminConnectorHostPort()
   {
-    return localAdminConnectorURL;
+    return localAdminConnectorHostPort;
   }
 
   /**
-   * Gets the LDAP URL based in what is read in the configuration.
-   * It returns {@code null} if no LDAP URL was found.
-   * @return the LDAP URL to be used to connect to the server.
+   * Gets the LDAP HostPort based in what is read in the configuration.
+   * It returns {@code null} if no LDAP HostPort was found.
+   * @return the LDAP HostPort to be used to connect to the server.
    */
-  public String getLDAPURL()
+  public HostPort getLdapHostPort()
   {
-    return ldapURL;
+    return ldapHostPort;
   }
 
   /**
-   * Gets the Start TLS URL based in what is read in the configuration. It
-   * returns {@code null} if no Start TLS URL is found.
-   * @return the Start TLS URL to be used to connect to the server.
+   * Gets the Start TLS HostPort based in what is read in the configuration. It
+   * returns {@code null} if no Start TLS HostPort is found.
+   * @return the Start TLS HostPort to be used to connect to the server.
    */
-  public String getStartTLSURL()
+  public HostPort getStartTlsHostPort()
   {
-    return startTLSURL;
+    return startTlsHostPort;
   }
 
   /**
-   * Returns the LDAP URL to be used to connect to a given ServerDescriptor
-   * using a certain protocol. It returns {@code null} if URL for the
+   * Returns the HostPort to be used to connect to a given ServerDescriptor
+   * using a certain protocol. It returns {@code null} if HostPort for the
    * protocol is not found.
    * @param server the server descriptor.
    * @param protocol the protocol to be used.
-   * @return the LDAP URL to be used to connect to a given ServerDescriptor
+   * @return the HostPort to be used to connect to a given ServerDescriptor
    * using a certain protocol.
    */
-  private static String getURL(ServerDescriptor server,
-      ConnectionHandlerDescriptor.Protocol protocol)
+  private static HostPort getHostPort(ServerDescriptor server, ConnectionHandlerDescriptor.Protocol protocol)
   {
-    String sProtocol = toString(protocol);
+    toString(protocol);
 
-    String url = null;
+    HostPort hp = null;
     for (ConnectionHandlerDescriptor desc : server.getConnectionHandlers())
     {
       if (desc.getState() == ConnectionHandlerDescriptor.State.ENABLED
@@ -903,22 +900,22 @@
             SortedSet<InetAddress> addresses = desc.getAddresses();
             if (addresses.isEmpty())
             {
-              url = sProtocol +"://localhost:"+port;
+              hp = new HostPort("localhost", port);
             }
             else
             {
               InetAddress address = addresses.first();
-              url = sProtocol + "://" + getHostNameForLdapUrl(address.getHostAddress()) + ":" + port;
+              hp = new HostPort(address.getHostAddress(), port);
             }
           }
           else
           {
-            url = sProtocol + "://" + getHostNameForLdapUrl(server.getHostname()) + ":" + port;
+            hp = new HostPort(server.getHostname(), port);
           }
         }
       }
     }
-    return url;
+    return hp;
   }
 
   private static String toString(ConnectionHandlerDescriptor.Protocol protocol)
@@ -940,12 +937,12 @@
   }
 
   /**
-   * Returns the Administration Connector URL.
-   * It returns {@code null} if URL for the protocol is not found.
+   * Returns the Administration Connector HostPort.
+   * It returns {@code null} if HostPort for the protocol is not found.
    * @param server the server descriptor.
-   * @return the Administration Connector URL.
+   * @return the Administration Connector HostPort.
    */
-  private static String getAdminConnectorURL(ServerDescriptor server) {
+  private static HostPort getAdminConnectorHostPort(ServerDescriptor server) {
     ConnectionHandlerDescriptor desc = server.getAdminConnector();
     if (desc != null)
     {
@@ -954,12 +951,11 @@
         SortedSet<InetAddress> addresses = desc.getAddresses();
         if (!addresses.isEmpty())
         {
-          String hostAddr = addresses.first().getHostAddress();
-          return getLDAPUrl(hostAddr, port, true);
+          return new HostPort(addresses.first().getHostAddress(), port);
         }
         else
         {
-          return getLDAPUrl("localhost", port, true);
+          return new HostPort("localhost", port);
         }
       }
     }
@@ -973,7 +969,7 @@
    */
   public boolean connectUsingStartTLS()
   {
-    return startTLSURL != null && startTLSURL.equals(getURLToConnect());
+    return startTlsHostPort != null && startTlsHostPort.equals(getHostPortToConnect());
   }
 
   /**
@@ -982,49 +978,49 @@
    */
   public boolean connectUsingLDAPS()
   {
-    return ldapsURL != null && ldapsURL.equals(getURLToConnect());
+    return ldapsHostPort != null && ldapsHostPort.equals(getHostPortToConnect());
   }
 
   /**
-   * Returns the URL that must be used to connect to the server based on the
+   * Returns the HostPort that must be used to connect to the server based on the
    * available enabled connection handlers in the server and the connection
    * policy.
-   * @return the URL that must be used to connect to the server.
+   * @return the HostPort that must be used to connect to the server.
    */
-  public String getURLToConnect()
+  private HostPort getHostPortToConnect()
   {
     switch (getConnectionPolicy())
     {
     case USE_STARTTLS:
-      return startTLSURL;
+      return startTlsHostPort;
     case USE_LDAP:
-      return ldapURL;
+      return ldapHostPort;
     case USE_LDAPS:
-      return ldapsURL;
+      return ldapsHostPort;
     case USE_ADMIN:
-      return getAdminConnectorURL();
+      return getAdminConnectorHostPort();
     case USE_MOST_SECURE_AVAILABLE:
-      String url1 = ldapsURL;
-      if (url1 == null)
+      HostPort hp1 = ldapsHostPort;
+      if (hp1 == null)
       {
-        url1 = startTLSURL;
+        hp1 = startTlsHostPort;
       }
-      if (url1 == null)
+      if (hp1 == null)
       {
-        url1 = ldapURL;
+        hp1 = ldapHostPort;
       }
-      return url1;
+      return hp1;
     case USE_LESS_SECURE_AVAILABLE:
-      String url2 = ldapURL;
-      if (url2 == null)
+      HostPort hp2 = ldapHostPort;
+      if (hp2 == null)
       {
-        url2 = startTLSURL;
+        hp2 = startTlsHostPort;
       }
-      if (url2 == null)
+      if (hp2 == null)
       {
-        url2 = ldapsURL;
+        hp2 = ldapsHostPort;
       }
-      return url2;
+      return hp2;
     default:
       throw new RuntimeException("Unknown policy: "+getConnectionPolicy());
     }
@@ -1190,7 +1186,7 @@
         }
         return true;
       }
-      catch (NamingException ne)
+      catch (RuntimeException ignored)
       {
         try
         {
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/AbstractBrowseEntriesPanel.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/AbstractBrowseEntriesPanel.java
index e859501..e3cf390 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/AbstractBrowseEntriesPanel.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/AbstractBrowseEntriesPanel.java
@@ -34,7 +34,6 @@
 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;
 import java.util.Enumeration;
@@ -46,7 +45,6 @@
 import java.util.SortedSet;
 import java.util.TreeSet;
 
-import javax.naming.NamingException;
 import javax.swing.BorderFactory;
 import javax.swing.Box;
 import javax.swing.DefaultComboBoxModel;
@@ -74,6 +72,7 @@
 import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.ldap.DN;
 import org.forgerock.opendj.ldap.Filter;
+import org.forgerock.opendj.ldap.LdapException;
 import org.opends.admin.ads.util.ApplicationTrustManager;
 import org.opends.admin.ads.util.ConnectionWrapper;
 import org.opends.guitools.controlpanel.browser.BrowserController;
@@ -98,6 +97,7 @@
 import org.opends.quicksetup.UserDataCertificateException;
 import org.opends.quicksetup.ui.CertificateDialog;
 import org.opends.quicksetup.util.UIKeyStore;
+import org.opends.server.types.HostPort;
 import org.opends.server.util.ServerConstants;
 
 /**
@@ -1225,7 +1225,7 @@
           }
           displayNodes = true;
         }
-        catch (IOException | NamingException e)
+        catch (IOException e)
         {
           errorTitle = INFO_CTRL_PANEL_ERROR_CONNECT_BROWSE_DETAILS.get();
           errorDetails = INFO_CTRL_PANEL_ERROR_CONNECT_BROWSE_SUMMARY.get(e);
@@ -1379,33 +1379,31 @@
   }
 
   /**
-   * Creates the context to be used to retrieve user data for some given
-   * credentials.
+   * Creates the context to be used to retrieve user data for some given credentials.
    *
    * @param bindDN
    *          the bind DN.
    * @param bindPassword
    *          the bind password.
-   * @return the context to be used to retrieve user data for some given
-   *         credentials.
-   * @throws NamingException
+   * @return the context to be used to retrieve user data for some given credentials.
+   * @throws IOException
    *           if an error occurs connecting to the server.
    * @throws ConfigReadException
    *           if an error occurs reading the configuration.
    */
   private ConnectionWrapper createUserDataDirContext(final DN bindDN, final String bindPassword)
-      throws NamingException, IOException, ConfigReadException
+      throws IOException, ConfigReadException
   {
     createdUserDataConn = null;
     try
     {
       createdUserDataConn = Utilities.getUserDataDirContext(getInfo(), bindDN, bindPassword);
     }
-    catch (NamingException ne)
+    catch (LdapException e)
     {
-      if (!isCertificateException(ne))
+      if (!isCertificateException(e))
       {
-        throw ne;
+        throw e;
       }
 
       ApplicationTrustManager trustManager = getInfo().getTrustManager();
@@ -1424,22 +1422,11 @@
 
       if (excType != null)
       {
-        String h;
-        int p;
-        try
-        {
-          URI uri = new URI(getInfo().getAdminConnectorURL());
-          h = uri.getHost();
-          p = uri.getPort();
-        }
-        catch (Throwable t)
-        {
-          logger.warn(LocalizableMessage.raw("Error parsing ldap url of ldap url.", t));
-          h = INFO_NOT_AVAILABLE_LABEL.get().toString();
-          p = -1;
-        }
+        HostPort hp = getInfo().getAdminConnectorHostPort();
+        String h = hp.getHost();
+        int p = hp.getPort();
         final UserDataCertificateException udce = new UserDataCertificateException(
-            null, INFO_CERTIFICATE_EXCEPTION.get(h, p), ne, h, p, trustManager.getLastRefusedChain(),
+            null, INFO_CERTIFICATE_EXCEPTION.get(h, p), e, h, p, trustManager.getLastRefusedChain(),
             trustManager.getLastRefusedAuthType(), excType);
 
         handleCertificateExceptionInSwing(bindDN, bindPassword, udce);
@@ -1449,7 +1436,7 @@
   }
 
   private void handleCertificateExceptionInSwing(final DN bindDN, final String bindPassword,
-      final UserDataCertificateException udce) throws NamingException, IOException, ConfigReadException
+      final UserDataCertificateException udce) throws IOException, ConfigReadException
   {
     if (SwingUtilities.isEventDispatchThread())
     {
@@ -1458,7 +1445,7 @@
     else
     {
       final ConfigReadException[] fcre = { null };
-      final NamingException[] fne = { null };
+      final LdapException[] fne = { null };
       final IOException[] fioe = { null };
       try
       {
@@ -1475,9 +1462,9 @@
             {
               fcre[0] = cre;
             }
-            catch (NamingException ne)
+            catch (LdapException e)
             {
-              fne[0] = ne;
+              fne[0] = e;
             }
             catch (IOException ioe)
             {
@@ -1517,7 +1504,7 @@
    *          the bind password.
    */
   private void handleCertificateException(UserDataCertificateException ce, DN bindDN, String bindPassword)
-      throws NamingException, IOException, ConfigReadException
+      throws IOException, ConfigReadException
   {
     CertificateDialog dlg = new CertificateDialog(null, ce);
     dlg.pack();
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ErrorSearchingEntryPanel.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ErrorSearchingEntryPanel.java
index e362306..7ae063f 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ErrorSearchingEntryPanel.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ErrorSearchingEntryPanel.java
@@ -20,14 +20,12 @@
 import java.awt.GridBagConstraints;
 import java.awt.Insets;
 
-import javax.naming.NameNotFoundException;
-import javax.naming.NamingException;
-
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.LocalizableMessageBuilder;
 import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.EntryNotFoundException;
+import org.forgerock.opendj.ldap.LdapException;
 import org.opends.guitools.controlpanel.browser.BasicNodeError;
-import org.opends.guitools.controlpanel.browser.ReferralLimitExceededException;
 import org.opends.guitools.controlpanel.event.ConfigurationChangeEvent;
 import org.opends.quicksetup.util.Utils;
 import org.opends.server.types.LDAPURL;
@@ -35,6 +33,7 @@
 
 import static com.forgerock.opendj.cli.Utils.*;
 
+import static org.forgerock.opendj.ldap.ResultCode.*;
 import static org.opends.messages.AdminToolMessages.*;
 
 /** The panel that is displayed when there is an error searching an entry. */
@@ -124,10 +123,10 @@
     }
     details.append(INFO_CTRL_PANEL_ERROR_RESOLVING_REFERRAL_MSG.get(dn, sb));
     Exception ex = error.getException();
-    if (ex instanceof NamingException)
+    if (ex instanceof LdapException)
     {
       Object arg = error.getArg();
-      LocalizableMessage msg = getErrorMsg(ex, arg);
+      LocalizableMessage msg = getErrorMsg((LdapException) ex, arg);
       if (arg != null)
       {
         details.append("<br><br>").append(ERR_CTRL_PANEL_RESOLVING_REFERRAL_DETAILS.get(arg, msg));
@@ -151,24 +150,24 @@
         details.toMessage(), ColorAndFontConstants.defaultFont);
   }
 
-  private LocalizableMessage getErrorMsg(Exception ex, Object arg)
+  private LocalizableMessage getErrorMsg(LdapException ex, Object arg)
   {
     LocalizableMessage msg = getErrorMsg0(ex, arg);
     if (msg != null)
     {
       return msg;
     }
-    else if (ex instanceof ReferralLimitExceededException)
+    else if (CLIENT_SIDE_REFERRAL_LIMIT_EXCEEDED.equals(ex.getResult().getResultCode()))
     {
       return LocalizableMessage.raw(ex.getLocalizedMessage());
     }
     else
     {
-      return Utils.getMessageForException((NamingException) ex);
+      return Utils.getMessageForException(ex);
     }
   }
 
-  private LocalizableMessage getErrorMsg0(Exception ex, Object arg)
+  private LocalizableMessage getErrorMsg0(LdapException ex, Object arg)
   {
     if (arg == null)
     {
@@ -182,30 +181,30 @@
       if (url.getHost() != null)
       {
         String hostPort = url.getHost() + ":" + url.getPort();
-        if (ex instanceof ReferralLimitExceededException)
+        if (CLIENT_SIDE_REFERRAL_LIMIT_EXCEEDED.equals(ex.getResult().getResultCode()))
         {
           return LocalizableMessage.raw(ex.getLocalizedMessage());
         }
-        else if (ex instanceof NameNotFoundException)
+        else if (ex instanceof EntryNotFoundException)
         {
           return ERR_CTRL_PANEL_COULD_NOT_FIND_PROVIDED_ENTRY_IN_REFERRAL.get(arg, hostPort);
         }
         else
         {
-          return getMessageForException((NamingException) ex, hostPort);
+          return getMessageForException(ex, hostPort);
         }
       }
-      else if (ex instanceof ReferralLimitExceededException)
+      else if (CLIENT_SIDE_REFERRAL_LIMIT_EXCEEDED.equals(ex.getResult().getResultCode()))
       {
         return LocalizableMessage.raw(ex.getLocalizedMessage());
       }
-      else if (ex instanceof NameNotFoundException)
+      else if (ex instanceof EntryNotFoundException)
       {
         return ERR_CTRL_PANEL_COULD_NOT_FIND_PROVIDED_ENTRY_IN_REFERRAL_NO_HOST.get(arg);
       }
       else
       {
-        return Utils.getMessageForException((NamingException) ex);
+        return Utils.getMessageForException(ex);
       }
     }
     catch (Throwable t)
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java
index eca7d29..08a75f7 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LocalOrRemotePanel.java
@@ -22,13 +22,11 @@
 import java.awt.event.ActionListener;
 import java.io.File;
 import java.io.IOException;
-import java.net.URI;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.LinkedHashSet;
 
-import javax.naming.NamingException;
 import javax.swing.Box;
 import javax.swing.DefaultComboBoxModel;
 import javax.swing.JComboBox;
@@ -41,10 +39,10 @@
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LdapException;
 import org.forgerock.opendj.ldap.requests.SearchRequest;
 import org.forgerock.opendj.ldap.responses.SearchResultEntry;
 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.ControlPanelArgumentParser;
 import org.opends.guitools.controlpanel.datamodel.ConfigReadException;
@@ -87,7 +85,7 @@
   private JTextField dn;
   private JLabel pwdLabel;
   private JLabel dnLabel;
-  private String usedUrl;
+  private HostPort usedHostPort;
   private JLabel localInstallLabel;
   private JEditorPane localInstall;
   private JLabel localNotRunning;
@@ -542,14 +540,13 @@
             String bindPwd = String.valueOf(pwd.getPassword());
             if (isLocal)
             {
-              usedUrl = info.getAdminConnectorURL();
+              usedHostPort = info.getAdminConnectorHostPort();
               conn = Utilities.getAdminDirContext(info, bindDn, bindPwd);
             }
             else
             {
-              HostPort hostPort = new HostPort(hostName.getText().trim(), Integer.valueOf(port.getText().trim()));
-              usedUrl = ConnectionUtils.getLDAPUrl(hostPort, true);
-              conn = new ConnectionWrapper(hostPort, LDAPS, bindDn, bindPwd,
+              usedHostPort = getHostPort();
+              conn = new ConnectionWrapper(usedHostPort, LDAPS, bindDn, bindPwd,
                   info.getConnectTimeout(), info.getTrustManager());
               checkVersion(conn);
             }
@@ -576,6 +573,11 @@
           }
         }
 
+        private HostPort getHostPort()
+        {
+          return new HostPort(hostName.getText().trim(), Integer.valueOf(port.getText().trim()));
+        }
+
         @Override
         public void backgroundTaskCompleted(ConnectionWrapper conn, Throwable throwable)
         {
@@ -613,21 +615,8 @@
 
               if (excType != null)
               {
-                String h;
-                int p;
-                try
-                {
-                  URI uri = new URI(usedUrl);
-                  h = uri.getHost();
-                  p = uri.getPort();
-                }
-                catch (Throwable t)
-                {
-                  logger.warn(LocalizableMessage.raw(
-                      "Error parsing ldap url of ldap url.", t));
-                  h = INFO_NOT_AVAILABLE_LABEL.get().toString();
-                  p = -1;
-                }
+                String h = usedHostPort.getHost();
+                int p = usedHostPort.getPort();
                 ApplicationTrustManager trustMgr = info.getTrustManager();
                 UserDataCertificateException udce =
                   new UserDataCertificateException(null,
@@ -641,14 +630,13 @@
                 handleCertificateException = true;
               }
             }
-            else if (throwable instanceof NamingException)
+            else if (throwable instanceof LdapException)
             {
               boolean found = false;
               String providedDn = dn.getText();
               if (isLocal)
               {
-                Iterator<DN> it = info.getServerDescriptor().
-                getAdministrativeUsers().iterator();
+                Iterator<DN> it = info.getServerDescriptor().getAdministrativeUsers().iterator();
                 while (it.hasNext() && !found)
                 {
                   found = Utils.areDnsEqual(providedDn, it.next().toString());
@@ -659,18 +647,14 @@
                 }
                 else
                 {
-                  errors.add(Utils.getMessageForException(
-                      (NamingException)throwable));
+                  errors.add(Utils.getMessageForException((LdapException) throwable));
                 }
                 localServerErrorConnecting = true;
               }
               else
               {
-                HostPort hostPort = new HostPort(
-                    hostName.getText().trim(),
-                    Integer.valueOf(port.getText().trim()));
-                NamingException ne = (NamingException)throwable;
-                errors.add(getMessageForException(ne, hostPort.toString()));
+                LdapException ne = (LdapException) throwable;
+                errors.add(getMessageForException(ne, getHostPort().toString()));
                 setPrimaryInvalid(portLabel);
               }
               setPrimaryInvalid(dnLabel);
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LoginPanel.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LoginPanel.java
index 2a3bc99..a47b467 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LoginPanel.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/LoginPanel.java
@@ -18,7 +18,6 @@
 
 import java.awt.Component;
 import java.awt.GridBagConstraints;
-import java.net.URI;
 import java.security.cert.X509Certificate;
 import java.util.Iterator;
 import java.util.LinkedHashSet;
@@ -43,6 +42,7 @@
 import org.opends.quicksetup.ui.CertificateDialog;
 import org.opends.quicksetup.util.UIKeyStore;
 import org.opends.quicksetup.util.Utils;
+import org.opends.server.types.HostPort;
 import org.opends.server.util.StaticUtils;
 
 import static com.forgerock.opendj.cli.Utils.*;
@@ -58,7 +58,7 @@
   private JTextField dn;
   private JLabel pwdLabel;
   private JLabel dnLabel;
-  private String usedUrl;
+  private HostPort usedHostPort;
 
   private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
@@ -187,7 +187,7 @@
           try
           {
             ControlPanelInfo info = getInfo();
-            usedUrl = info.getAdminConnectorURL();
+            usedHostPort = info.getAdminConnectorHostPort();
             conn = Utilities.getAdminDirContext(info, DN.valueOf(dn.getText()), String.valueOf(pwd.getPassword()));
 
             org.forgerock.util.Utils.closeSilently(info.getConnection(), info.getUserDataDirContext());
@@ -251,21 +251,8 @@
 
               if (excType != null)
               {
-                String h;
-                int p;
-                try
-                {
-                  URI uri = new URI(usedUrl);
-                  h = uri.getHost();
-                  p = uri.getPort();
-                }
-                catch (Throwable t)
-                {
-                  logger.warn(LocalizableMessage.raw(
-                      "Error parsing ldap url of ldap url.", t));
-                  h = INFO_NOT_AVAILABLE_LABEL.get().toString();
-                  p = -1;
-                }
+                String h = usedHostPort.getHost();
+                int p = usedHostPort.getPort();
                 UserDataCertificateException udce =
                   new UserDataCertificateException(null,
                       INFO_CERTIFICATE_EXCEPTION.get(h, p),
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java
index 2099c45..160e745 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java
@@ -54,7 +54,6 @@
 import java.util.logging.Logger;
 import java.util.regex.Pattern;
 
-import javax.naming.NamingException;
 import javax.swing.BorderFactory;
 import javax.swing.DefaultComboBoxModel;
 import javax.swing.ImageIcon;
@@ -128,6 +127,7 @@
 import org.opends.server.core.LockFileManager;
 import org.opends.server.core.ServerContext;
 import org.opends.server.schema.SchemaConstants;
+import org.opends.server.types.HostPort;
 import org.opends.server.types.OpenDsException;
 import org.opends.server.types.Schema;
 import org.opends.server.util.SchemaUtils;
@@ -2115,16 +2115,14 @@
    * @param bindDN the base DN to be used to bind.
    * @param pwd the password to be used to bind.
    * @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, DN bindDN, String pwd)
-      throws NamingException, IOException, ConfigReadException
+      throws IOException, ConfigReadException
   {
-    return createConnection(controlInfo.getAdminConnectorURL(), LDAPS, bindDN, pwd, controlInfo);
+    return createConnection(controlInfo.getAdminConnectorHostPort(), LDAPS, bindDN, pwd, controlInfo);
   }
 
   /**
@@ -2136,38 +2134,36 @@
    * @param bindDN the base DN to be used to bind.
    * @param pwd the password to be used to bind.
    * @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 getUserDataDirContext(ControlPanelInfo controlInfo,
-      DN bindDN, String pwd) throws NamingException, IOException, ConfigReadException
+      DN bindDN, String pwd) throws IOException, ConfigReadException
   {
     if (controlInfo.connectUsingStartTLS())
     {
-      return createConnection(controlInfo.getStartTLSURL(), START_TLS, bindDN, pwd, controlInfo);
+      return createConnection(controlInfo.getStartTlsHostPort(), START_TLS, bindDN, pwd, controlInfo);
     }
     else if (controlInfo.connectUsingLDAPS())
     {
-      return createConnection(controlInfo.getLDAPSURL(), LDAPS, bindDN, pwd, controlInfo);
+      return createConnection(controlInfo.getLdapsHostPort(), LDAPS, bindDN, pwd, controlInfo);
     }
     else
     {
-      return createConnection(controlInfo.getLDAPURL(), LDAP, bindDN, pwd, controlInfo);
+      return createConnection(controlInfo.getLdapHostPort(), LDAP, bindDN, pwd, controlInfo);
     }
   }
 
-  private static ConnectionWrapper createConnection(String usedUrl, Type connectionType, DN bindDN, String bindPwd,
-      ControlPanelInfo controlInfo) throws NamingException, IOException, ConfigReadException
+  private static ConnectionWrapper createConnection(HostPort hostPort, Type connectionType, DN bindDN, String bindPwd,
+      ControlPanelInfo controlInfo) throws IOException, ConfigReadException
   {
-    if (usedUrl == null)
+    if (hostPort == null)
     {
       throw new ConfigReadException(ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
     }
 
-    ConnectionWrapper conn = new ConnectionWrapper(usedUrl, connectionType,
+    ConnectionWrapper conn = new ConnectionWrapper(hostPort, connectionType,
         bindDN, bindPwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
     checkCanReadConfig(conn);
     return conn;
@@ -2195,10 +2191,8 @@
    *
    * @param connWrapper
    *          the connection to be "pinged".
-   * @throws NamingException
-   *           if the ping could not be performed.
    */
-  public static void ping(ConnectionWrapper connWrapper) throws NamingException
+  public static void ping(ConnectionWrapper connWrapper)
   {
     SearchRequest request = newSearchRequest("", BASE_OBJECT, "objectClass=*", NO_ATTRIBUTES)
         .setSizeLimit(0)
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java
index a15feeb..e4898e1 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java
@@ -17,6 +17,7 @@
 package org.opends.guitools.uninstaller;
 
 import static org.forgerock.util.Utils.*;
+import static org.opends.admin.ads.ADSContext.getAdministratorDN;
 import static org.opends.admin.ads.util.PreferredConnection.Type.*;
 import static org.opends.messages.AdminToolMessages.*;
 import static org.opends.messages.QuickSetupMessages.*;
@@ -28,19 +29,17 @@
 import java.io.File;
 import java.io.FileReader;
 import java.io.IOException;
-import java.net.URI;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.Set;
 
-import javax.naming.NamingException;
 import javax.net.ssl.TrustManager;
 
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.LocalizableMessageBuilder;
 import org.forgerock.i18n.slf4j.LocalizedLogger;
-import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LdapException;
 import org.opends.admin.ads.ADSContext;
 import org.opends.admin.ads.ServerDescriptor;
 import org.opends.admin.ads.TopologyCache;
@@ -237,8 +236,8 @@
       info.setConnectTimeout(getConnectTimeout());
       info.regenerateDescriptor();
       info.setConnectionPolicy(ConnectionProtocolPolicy.USE_ADMIN);
-      String adminConnectorUrl = info.getAdminConnectorURL();
-      if (adminConnectorUrl == null)
+      HostPort adminConnectorHostPort = info.getAdminConnectorHostPort();
+      if (adminConnectorHostPort == null)
       {
         logger.warn(LocalizableMessage.raw(
         "Error retrieving a valid LDAP URL in conf file."));
@@ -248,7 +247,7 @@
           throw new ClientException(ReturnCode.APPLICATION_ERROR, msg);
         }
       }
-      userData.setLocalServerUrl(adminConnectorUrl);
+      userData.setLocalServer(adminConnectorHostPort, true);
       userData.setReferencedHostName(referencedHostName);
 
       /*
@@ -830,30 +829,23 @@
         userData.setAdminPwd(ci.getBindPassword());
 
         info.setConnectionPolicy(ConnectionProtocolPolicy.USE_ADMIN);
-        String adminConnectorUrl = info.getAdminConnectorURL();
-        if (adminConnectorUrl == null)
+        HostPort adminConnectorHostPort = info.getAdminConnectorHostPort();
+        if (adminConnectorHostPort == null)
         {
           logger.warn(LocalizableMessage.raw("Error retrieving a valid Administration Connector URL in conf file."));
           LocalizableMessage msg = ERR_COULD_NOT_FIND_VALID_LDAPURL.get();
           throw new ClientException(ReturnCode.APPLICATION_ERROR, msg);
         }
-        try
-        {
-          URI uri = new URI(adminConnectorUrl);
-          int port = uri.getPort();
-          portArg.clearValues();
-          portArg.addValue(String.valueOf(port));
-          ci.setPortNumber(port);
-        }
-        catch (Throwable t)
-        {
-          logger.error(LocalizableMessage.raw("Error parsing url: "+adminConnectorUrl));
-        }
+        int port = adminConnectorHostPort.getPort();
+        portArg.clearValues();
+        portArg.addValue(String.valueOf(port));
+        ci.setPortNumber(port);
+
         updateTrustManager(userData, ci);
 
         info.setConnectionPolicy(ConnectionProtocolPolicy.USE_ADMIN);
-        adminConnectorUrl = info.getAdminConnectorURL();
-        if (adminConnectorUrl == null)
+        adminConnectorHostPort = info.getAdminConnectorHostPort();
+        if (adminConnectorHostPort == null)
         {
           logger.warn(LocalizableMessage.raw(
          "Error retrieving a valid Administration Connector URL in conf file."));
@@ -861,7 +853,7 @@
           throw new ClientException(ReturnCode.APPLICATION_ERROR, msg);
         }
 
-        userData.setLocalServerUrl(adminConnectorUrl);
+        userData.setLocalServer(adminConnectorHostPort, true);
         couldConnect = true;
       }
       catch (ArgumentException e)
@@ -1085,25 +1077,10 @@
     {
       info.setTrustManager(userData.getTrustManager());
       info.setConnectTimeout(getConnectTimeout());
-      String host = "localhost";
-      int port = 389;
-      String adminUid = userData.getAdminUID();
-      String pwd = userData.getAdminPwd();
-      DN dn = ADSContext.getAdministratorDN(adminUid);
-
       info.setConnectionPolicy(ConnectionProtocolPolicy.USE_ADMIN);
-      String adminConnectorUrl = info.getAdminConnectorURL();
-      try
-      {
-        URI uri = new URI(adminConnectorUrl);
-        host = uri.getHost();
-        port = uri.getPort();
-      }
-      catch (Throwable t)
-      {
-        logger.error(LocalizableMessage.raw("Error parsing url: "+adminConnectorUrl));
-      }
-      conn = new ConnectionWrapper(new HostPort(host, port), connectionType, dn, pwd,
+      conn = new ConnectionWrapper(
+          info.getAdminConnectorHostPort(), connectionType,
+          getAdministratorDN(userData.getAdminUID()), userData.getAdminPwd(),
           getConnectTimeout(), userData.getTrustManager());
 
       ADSContext adsContext = new ADSContext(conn);
@@ -1126,18 +1103,17 @@
 
       exceptionOccurred = false;
     }
-    catch (NamingException ne)
+    catch (LdapException e)
     {
-      logger.warn(LocalizableMessage.raw("Error connecting to server: "+ne, ne));
-      if (isCertificateException(ne))
+      logger.warn(LocalizableMessage.raw("Error connecting to server: " + e, e));
+      if (isCertificateException(e))
       {
-        String details = ne.getMessage() != null ?
-            ne.getMessage() : ne.toString();
+        String details = e.getMessage() != null ? e.getMessage() : e.toString();
         exceptionMsg = INFO_ERROR_READING_CONFIG_LDAP_CERTIFICATE.get(details);
       }
       else
       {
-        exceptionMsg = getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(), ne);
+        exceptionMsg = getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(), e);
       }
     } catch (TopologyCacheException te)
     {
@@ -1261,7 +1237,7 @@
             println();
             stopProcessing = true;
             if (ci.promptForCertificateConfirmation(e.getCause(),
-                e.getTrustManager(), e.getLdapUrl(), logger))
+                e.getTrustManager(), e.getHostPort(), logger))
             {
               reloadTopologyCache = true;
               updateTrustManager(userData, ci);
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallUserData.java b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallUserData.java
index 7a4c681..043aa07 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallUserData.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallUserData.java
@@ -12,21 +12,19 @@
  * information: "Portions Copyright [year] [name of copyright owner]".
  *
  * Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2015 ForgeRock AS.
+ * Portions Copyright 2015-2016 ForgeRock AS.
  */
-
 package org.opends.guitools.uninstaller;
 
+import java.util.HashSet;
+import java.util.Set;
+
 import org.opends.admin.ads.ServerDescriptor;
 import org.opends.admin.ads.util.ApplicationTrustManager;
 import org.opends.quicksetup.UserData;
+import org.opends.server.types.HostPort;
 
-import java.util.Set;
-import java.util.HashSet;
-
-/**
- * UserData with specific properties for Uninstall.
- */
+/** UserData with specific properties for Uninstall. */
 public class UninstallUserData extends UserData {
 
   private Set<String> externalDbsToRemove = new HashSet<>();
@@ -41,8 +39,9 @@
   private ApplicationTrustManager trustManager = new ApplicationTrustManager(null);
   private String adminUID;
   private String adminPwd;
-  private String localServerUrl;
-  private HashSet<ServerDescriptor> remoteServers = new HashSet<>();
+  private HostPort localServerHostPort;
+  private boolean localServerSecure;
+  private Set<ServerDescriptor> remoteServers = new HashSet<>();
   private String replicationServer;
   private String referencedHostName;
 
@@ -312,20 +311,34 @@
   }
 
   /**
-   * Returns the LDAP URL that we used to connect to the local server.
-   * @return the LDAP URL that we used to connect to the local server.
+   * Returns the LDAP HostPort that we used to connect to the local server.
+   * @return the LDAP HostPort that we used to connect to the local server.
    */
-  public String getLocalServerUrl() {
-    return localServerUrl;
+  public HostPort getLocalServerHostPort() {
+    return localServerHostPort;
   }
 
   /**
-   * Sets the LDAP URL that we used to connect to the local server.
-   * @param localServerUrl the LDAP URL that we used to connect to the local
-   * server.
+   * Returns whether the LDAP connection to the local server uses LDAPS.
+   * @return whether the LDAP connection to the local server uses LDAPS
    */
-  public void setLocalServerUrl(String localServerUrl) {
-    this.localServerUrl = localServerUrl;
+  public boolean isLocalServerSecure()
+  {
+    return localServerSecure;
+  }
+
+  /**
+   * Sets the LDAP HostPort that we used to connect to the local server.
+   *
+   * @param hostPort
+   *          the LDAP HostPort that we used to connect to the local server.
+   * @param isSecure
+   *          whether the local server uses a secure connection
+   */
+  public void setLocalServer(HostPort hostPort, boolean isSecure)
+  {
+    this.localServerHostPort = hostPort;
+    this.localServerSecure = isSecure;
   }
 
   /**
@@ -349,5 +362,4 @@
     this.remoteServers.clear();
     this.remoteServers.addAll(remoteServers);
   }
-
 }
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java
index b669c91..cc648ec 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java
@@ -21,7 +21,6 @@
 import java.io.FileFilter;
 import java.io.PrintStream;
 import java.net.InetAddress;
-import java.net.URI;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -1468,8 +1467,8 @@
     {
       getUninstallUserData().setAdminUID(loginDialog.getAdministratorUid());
       getUninstallUserData().setAdminPwd(loginDialog.getAdministratorPwd());
-      final ConnectionWrapper connWrapper = loginDialog.getConnection();
-      getUninstallUserData().setLocalServerUrl(connWrapper.getLdapUrl());
+      final ConnectionWrapper conn = loginDialog.getConnection();
+      getUninstallUserData().setLocalServer(conn.getHostPort(), conn.isLdaps());
       getUninstallUserData().setReplicationServer(
           loginDialog.getHostName() + ":" +
           conf.getReplicationServerPort());
@@ -1481,7 +1480,7 @@
         public TopologyCache processBackgroundTask() throws Throwable
         {
           logger.info(LocalizableMessage.raw("Loading Topology Cache in askForAuthentication"));
-          ADSContext adsContext = new ADSContext(connWrapper);
+          ADSContext adsContext = new ADSContext(conn);
           TopologyCache cache = new TopologyCache(adsContext,
               getTrustManager(), getConnectTimeout());
           cache.getFilter().setSearchMonitoringInformation(false);
@@ -1586,21 +1585,9 @@
           UserDataCertificateException.Type excType = getCertificateExceptionType(cause);
           if (excType != null)
           {
-            String h;
-            int p;
-            try
-            {
-              URI uri = new URI(e.getLdapUrl());
-              h = uri.getHost();
-              p = uri.getPort();
-            }
-            catch (Throwable t)
-            {
-              logger.warn(LocalizableMessage.raw(
-                  "Error parsing ldap url of TopologyCacheException.", t));
-              h = INFO_NOT_AVAILABLE_LABEL.get().toString();
-              p = -1;
-            }
+            HostPort hp = e.getHostPort();
+            String h = hp.getHost();
+            int p = hp.getPort();
             UserDataCertificateException exc =
               new UserDataCertificateException(Step.REPLICATION_OPTIONS,
                 INFO_CERTIFICATE_EXCEPTION.get(h, p),
@@ -2044,21 +2031,14 @@
       // Compare the port of the URL we used.
       try
       {
-        String usedUrl = getUninstallUserData().getLocalServerUrl();
-        boolean isSecure = usedUrl.toLowerCase().startsWith("ldaps");
-        URI uri = new URI(usedUrl);
-        int port = uri.getPort();
-        ServerDescriptor.ServerProperty property;
-        if (isSecure)
-        {
-          property = ServerDescriptor.ServerProperty.ADMIN_PORT;
-        }
-        else
-        {
-          property = ServerDescriptor.ServerProperty.LDAP_PORT;
-        }
-        ArrayList<?> ports =
-          (ArrayList<?>)server.getServerProperties().get(property);
+        UninstallUserData uData = getUninstallUserData();
+        HostPort usedHostPort = uData.getLocalServerHostPort();
+        boolean isSecure = uData.isLocalServerSecure();
+        int port = usedHostPort.getPort();
+        ServerDescriptor.ServerProperty property = isSecure
+            ? ServerDescriptor.ServerProperty.ADMIN_PORT
+            : ServerDescriptor.ServerProperty.LDAP_PORT;
+        ArrayList<?> ports = (ArrayList<?>) server.getServerProperties().get(property);
         if (ports != null)
         {
           isServerToUninstall = ports.contains(port);
@@ -2066,15 +2046,9 @@
         else
         {
           // This occurs if the instance could not be loaded.
-          ADSContext.ServerProperty adsProperty;
-          if (isSecure)
-          {
-            adsProperty = ADSContext.ServerProperty.ADMIN_PORT;
-          }
-          else
-          {
-            adsProperty = ADSContext.ServerProperty.LDAP_PORT;
-          }
+          ADSContext.ServerProperty adsProperty = isSecure
+              ? ADSContext.ServerProperty.ADMIN_PORT
+              : ADSContext.ServerProperty.LDAP_PORT;
           String v = (String)server.getAdsProperties().get(adsProperty);
           if (v != null)
           {
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/ui/LoginDialog.java b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/ui/LoginDialog.java
index 1e10183..30f9a9d 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/ui/LoginDialog.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/ui/LoginDialog.java
@@ -14,7 +14,6 @@
  * Copyright 2008-2010 Sun Microsystems, Inc.
  * Portions Copyright 2014-2016 ForgeRock AS.
  */
-
 package org.opends.guitools.uninstaller.ui;
 
 import java.awt.Dimension;
@@ -22,11 +21,9 @@
 import java.awt.GridBagLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
-import java.net.URI;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 
-import javax.naming.NamingException;
 import javax.swing.Box;
 import javax.swing.JButton;
 import javax.swing.JDialog;
@@ -40,6 +37,7 @@
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LdapException;
 import org.opends.admin.ads.ADSContext;
 import org.opends.admin.ads.util.ApplicationTrustManager;
 import org.opends.admin.ads.util.ConnectionWrapper;
@@ -60,8 +58,10 @@
 import org.opends.quicksetup.util.BackgroundTask;
 import org.opends.quicksetup.util.UIKeyStore;
 import org.opends.quicksetup.util.Utils;
+import org.opends.server.types.HostPort;
 
 import static com.forgerock.opendj.cli.Utils.*;
+
 import static org.opends.messages.AdminToolMessages.*;
 import static org.opends.messages.QuickSetupMessages.*;
 
@@ -93,8 +93,7 @@
   private final int timeout;
 
   private ConnectionWrapper connWrapper;
-
-  private String usedUrl;
+  private HostPort usedHostPort;
 
   private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
@@ -369,7 +368,7 @@
     BackgroundTask<Boolean> worker = new BackgroundTask<Boolean>()
     {
       @Override
-      public Boolean processBackgroundTask() throws NamingException, ApplicationException
+      public Boolean processBackgroundTask() throws LdapException, ApplicationException
       {
         connWrapper = null;
         try
@@ -383,19 +382,20 @@
           DN dn = ADSContext.getAdministratorDN(tfUid.getText());
           String pwd = tfPwd.getText();
           info.setConnectionPolicy(ConnectionProtocolPolicy.USE_ADMIN);
-          usedUrl = info.getAdminConnectorURL();
-          if (usedUrl == null)
+          usedHostPort = info.getAdminConnectorHostPort();
+          if (usedHostPort == null)
           {
             throw new ApplicationException(ReturnCode.APPLICATION_ERROR,
                 ERR_COULD_NOT_FIND_VALID_LDAPURL.get(), null);
           }
           connWrapper = org.opends.guitools.controlpanel.util.Utilities.getAdminDirContext(info, dn, pwd);
           return true; // server is running
-        } catch (NamingException ne)
+        }
+        catch (LdapException e)
         {
           if (isServerRunning())
           {
-            throw ne;
+            throw e;
           }
           return false;
         } catch (ApplicationException | IllegalStateException e)
@@ -439,21 +439,8 @@
 
             if (excType != null)
             {
-              String h;
-              int p;
-              try
-              {
-                URI uri = new URI(usedUrl);
-                h = uri.getHost();
-                p = uri.getPort();
-              }
-              catch (Throwable t)
-              {
-                logger.warn(LocalizableMessage.raw(
-                    "Error parsing ldap url of ldap url.", t));
-                h = INFO_NOT_AVAILABLE_LABEL.get().toString();
-                p = -1;
-              }
+              String h = usedHostPort.getHost();
+              int p = usedHostPort.getPort();
               UserDataCertificateException udce =
               new UserDataCertificateException(Step.REPLICATION_OPTIONS,
                   INFO_CERTIFICATE_EXCEPTION.get(h, p),
@@ -464,7 +451,7 @@
               handleCertificateException(udce);
             }
           }
-          else if (throwable instanceof NamingException)
+          else if (throwable instanceof LdapException)
           {
             boolean uidInvalid = false;
             boolean pwdInvalid = false;
@@ -515,7 +502,7 @@
             {
               // Generic message
               displayError(
-                  Utils.getMessageForException((NamingException)throwable),
+                  Utils.getMessageForException((LdapException) throwable),
                   INFO_ERROR_TITLE.get());
             }
           }
diff --git a/opendj-server-legacy/src/main/java/org/opends/quicksetup/Application.java b/opendj-server-legacy/src/main/java/org/opends/quicksetup/Application.java
index c2c56a3..53bcf6a 100644
--- a/opendj-server-legacy/src/main/java/org/opends/quicksetup/Application.java
+++ b/opendj-server-legacy/src/main/java/org/opends/quicksetup/Application.java
@@ -25,13 +25,12 @@
 import java.util.Map;
 import java.util.Set;
 
-import javax.naming.NamingException;
-
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.LocalizableMessageBuilder;
 import org.forgerock.i18n.LocalizableMessageDescriptor.Arg2;
 import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LdapException;
 import org.opends.admin.ads.ADSContext;
 import org.opends.admin.ads.ServerDescriptor;
 import org.opends.admin.ads.TopologyCacheException;
@@ -613,20 +612,18 @@
     filter.setSearchBaseDNInformation(false);
     ServerLoader loader = new ServerLoader(adsProperties, dn, pwd, getTrustManager(), timeout, cnx, filter);
 
-    ConnectionWrapper connection;
     try
     {
-      connection = loader.createConnectionWrapper();
+      return loader.createConnectionWrapper();
     }
-    catch (NamingException ne)
+    catch (LdapException e)
     {
-      Arg2<Object, Object> arg2 = isCertificateException(ne)
+      Arg2<Object, Object> arg2 = isCertificateException(e)
           ? INFO_ERROR_READING_CONFIG_LDAP_CERTIFICATE_SERVER
           : INFO_CANNOT_CONNECT_TO_REMOTE_GENERIC;
-      LocalizableMessage msg = arg2.get(server.getHostPort(true), ne.toString(true));
-      throw new ApplicationException(ReturnCode.CONFIGURATION_ERROR, msg, ne);
+      LocalizableMessage msg = arg2.get(server.getHostPort(true), e.getLocalizedMessage());
+      throw new ApplicationException(ReturnCode.CONFIGURATION_ERROR, msg, e);
     }
-    return connection;
   }
 
   /**
diff --git a/opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/AuthenticationData.java b/opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/AuthenticationData.java
index 7f689c7..5414f5a 100644
--- a/opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/AuthenticationData.java
+++ b/opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/AuthenticationData.java
@@ -16,7 +16,10 @@
  */
 package org.opends.quicksetup.installer;
 
+import static org.opends.admin.ads.util.PreferredConnection.Type.*;
+
 import org.forgerock.opendj.ldap.DN;
+import org.opends.admin.ads.util.PreferredConnection.Type;
 import org.opends.server.types.HostPort;
 
 /**
@@ -30,7 +33,7 @@
   private HostPort hostPort = new HostPort(null, 0);
   private DN dn;
   private String pwd;
-  private boolean useSecureConnection;
+  private Type connectionType;
 
   /**
    * Sets the server LDAP port.
@@ -106,12 +109,11 @@
 
   /**
    * Returns whether to use a secure connection or not.
-   * @return <CODE>true</CODE> if we must use a secure connection and
-   * <CODE>false</CODE> otherwise.
+   * @return {@code true} if we must use a secure connection, {@code false} otherwise.
    */
   public boolean useSecureConnection()
   {
-    return useSecureConnection;
+    return connectionType == LDAPS;
   }
 
   /**
@@ -120,13 +122,11 @@
    */
   public void setUseSecureConnection(boolean useSecureConnection)
   {
-    this.useSecureConnection = useSecureConnection;
+    connectionType = useSecureConnection ? LDAPS : LDAP;
   }
 
-  String getLdapUrl()
+  Type getConnectionType()
   {
-    HostPort hostPort = getHostPort();
-    String scheme = useSecureConnection() ? "ldaps" : "ldap";
-    return scheme + "://" + hostPort.getHost() + ":" + hostPort.getPort();
+    return connectionType;
   }
 }
diff --git a/opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java b/opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java
index d5455ae..89884e6 100644
--- a/opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java
+++ b/opendj-server-legacy/src/main/java/org/opends/quicksetup/installer/Installer.java
@@ -40,7 +40,6 @@
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.PrintStream;
-import java.net.URI;
 import java.security.KeyStoreException;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -53,8 +52,6 @@
 import java.util.Map;
 import java.util.Set;
 
-import javax.naming.NamingException;
-import javax.naming.NamingSecurityException;
 import javax.naming.ldap.Rdn;
 import javax.swing.JPanel;
 
@@ -63,6 +60,8 @@
 import org.forgerock.i18n.LocalizableMessageDescriptor.Arg0;
 import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.config.ManagedObjectDefinition;
+import org.forgerock.opendj.ldap.AuthenticationException;
+import org.forgerock.opendj.ldap.AuthorizationException;
 import org.forgerock.opendj.ldap.DN;
 import org.forgerock.opendj.ldap.EntryNotFoundException;
 import org.forgerock.opendj.ldap.LdapException;
@@ -1946,7 +1945,7 @@
             backendTypes.get(backendId).getBackend());
       }
     }
-    catch (NamingException e)
+    catch (LdapException e)
     {
       LocalizableMessage failedMsg = getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(), e);
       throw new ApplicationException(ReturnCode.CONFIGURATION_ERROR, failedMsg, e);
@@ -2064,7 +2063,7 @@
       localTime = Utils.getServerClock(conn);
       localServerDisplay = conn.getHostPort();
     }
-    catch (NamingException ne)
+    catch (LdapException ne)
     {
       LocalizableMessage failedMsg = getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(), ne);
       throw new ApplicationException(ReturnCode.CONFIGURATION_ERROR, failedMsg, ne);
@@ -2615,8 +2614,8 @@
     ADSContext adsContext = null; // Bound to ADS host (via one of above).
 
     /*
-     * Outer try-catch-finally to convert occurrences of NamingException and
-     * ADSContextException to ApplicationException and clean up JNDI contexts.
+     * Outer try-catch-finally to convert occurrences of LdapException and ADSContextException to
+     * ApplicationException and clean up connections.
      */
     try
     {
@@ -2726,6 +2725,19 @@
         }
       }
     }
+    catch (LdapException ne)
+    {
+      LocalizableMessage msg;
+      if (isRemoteServer)
+      {
+        msg = getMessageForException(ne, auth.getHostPort().toString());
+      }
+      else
+      {
+        msg = Utils.getMessageForException(ne);
+      }
+      throw new ApplicationException(ReturnCode.CONFIGURATION_ERROR, msg, ne);
+    }
     catch (IOException e)
     {
       LocalizableMessage msg;
@@ -2739,19 +2751,6 @@
       }
       throw new ApplicationException(ReturnCode.CONFIGURATION_ERROR, msg, e);
     }
-    catch (NamingException ne)
-    {
-      LocalizableMessage msg;
-      if (isRemoteServer)
-      {
-        msg = getMessageForException(ne, auth.getHostPort().toString());
-      }
-      else
-      {
-        msg = Utils.getMessageForException(ne);
-      }
-      throw new ApplicationException(ReturnCode.CONFIGURATION_ERROR, msg, ne);
-    }
     catch (ADSContextException ace)
     {
       throw new ApplicationException(ReturnCode.CONFIGURATION_ERROR, (isRemoteServer ? INFO_REMOTE_ADS_EXCEPTION.get(
@@ -2763,21 +2762,21 @@
     }
   }
 
-  private ConnectionWrapper createConnection(AuthenticationData auth) throws NamingException
+  private ConnectionWrapper createConnection(AuthenticationData auth) throws LdapException
   {
-    String ldapUrl = auth.getLdapUrl();
+    HostPort hostPort = auth.getHostPort();
     DN dn = auth.getDn();
     String pwd = auth.getPwd();
 
     if (auth.useSecureConnection())
     {
       ApplicationTrustManager trustManager = getTrustManager();
-      trustManager.setHost(auth.getHostPort().getHost());
-      return new ConnectionWrapper(ldapUrl, LDAPS, dn, pwd, getConnectTimeout(), getTrustManager());
+      trustManager.setHost(hostPort.getHost());
+      return new ConnectionWrapper(hostPort, LDAPS, dn, pwd, getConnectTimeout(), getTrustManager());
     }
     else
     {
-      return new ConnectionWrapper(ldapUrl, LDAP, dn, pwd, getConnectTimeout(), getTrustManager());
+      return new ConnectionWrapper(hostPort, LDAP, dn, pwd, getConnectTimeout(), getTrustManager());
     }
   }
 
@@ -2913,16 +2912,7 @@
       AuthenticationData auth = repl.getAuthenticationData();
       if (auth != null)
       {
-        PreferredConnection.Type type;
-        if (auth.useSecureConnection())
-        {
-          type = PreferredConnection.Type.LDAPS;
-        }
-        else
-        {
-          type = PreferredConnection.Type.LDAP;
-        }
-        cnx.add(new PreferredConnection(auth.getLdapUrl(), type));
+        cnx.add(new PreferredConnection(auth.getHostPort(), auth.getConnectionType()));
       }
     }
     return cnx;
@@ -3430,20 +3420,9 @@
               excType = toUserDataCertificateExceptionType(cause);
               if (excType != null)
               {
-                String h;
-                int p;
-                try
-                {
-                  URI uri = new URI(e.getLdapUrl());
-                  h = uri.getHost();
-                  p = uri.getPort();
-                }
-                catch (Throwable t)
-                {
-                  logger.warn(LocalizableMessage.raw("Error parsing ldap url of TopologyCacheException.", t));
-                  h = INFO_NOT_AVAILABLE_LABEL.get().toString();
-                  p = -1;
-                }
+                HostPort hostPort2 = e.getHostPort();
+                String h = hostPort2.getHost();
+                int p = hostPort2.getPort();
                 throw new UserDataCertificateException(Step.REPLICATION_OPTIONS, INFO_CERTIFICATE_EXCEPTION.get(h, p),
                     e.getCause(), h, p, e.getTrustManager().getLastRefusedChain(), e.getTrustManager()
                         .getLastRefusedAuthType(), excType);
@@ -3491,12 +3470,12 @@
         qs.displayFieldInvalid(FieldName.REMOTE_SERVER_PWD, true);
         errorMsgs.add(INFO_CANNOT_CONNECT_TO_REMOTE_GENERIC.get(host + ":" + port, t));
       }
-      else if (t instanceof NamingException)
+      else if (t instanceof LdapException)
       {
-        errorMsgs.add(getMessageForException((NamingException) t, host + ":" + port));
+        errorMsgs.add(getMessageForException((LdapException) t, host + ":" + port));
         qs.displayFieldInvalid(FieldName.REMOTE_SERVER_DN, true);
         qs.displayFieldInvalid(FieldName.REMOTE_SERVER_PWD, true);
-        if (!(t instanceof NamingSecurityException))
+        if (!(t instanceof AuthorizationException) && !(t instanceof AuthenticationException))
         {
           qs.displayFieldInvalid(FieldName.REMOTE_SERVER_HOST, true);
           qs.displayFieldInvalid(FieldName.REMOTE_SERVER_PORT, true);
@@ -4083,7 +4062,7 @@
     return servers;
   }
 
-  private ConnectionWrapper createLocalConnection() throws NamingException
+  private ConnectionWrapper createLocalConnection() throws LdapException
   {
     UserData uData = getUserData();
     HostPort hostPort = new HostPort(uData.getHostName(), uData.getAdminConnectorPort());
diff --git a/opendj-server-legacy/src/main/java/org/opends/quicksetup/util/ServerController.java b/opendj-server-legacy/src/main/java/org/opends/quicksetup/util/ServerController.java
index 3278e98..a4ee88a 100644
--- a/opendj-server-legacy/src/main/java/org/opends/quicksetup/util/ServerController.java
+++ b/opendj-server-legacy/src/main/java/org/opends/quicksetup/util/ServerController.java
@@ -23,20 +23,19 @@
 import java.util.List;
 import java.util.Map;
 
-import javax.naming.NamingException;
-
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.LocalizableMessageBuilder;
 import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.ldap.DN;
+import org.forgerock.opendj.ldap.LdapException;
 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.types.HostPort;
 import org.opends.server.util.SetupUtils;
 
 import com.forgerock.opendj.cli.CliConstants;
@@ -45,6 +44,7 @@
 import static com.forgerock.opendj.cli.Utils.*;
 import static com.forgerock.opendj.util.OperatingSystem.*;
 
+import static org.opends.admin.ads.util.PreferredConnection.Type.*;
 import static org.opends.messages.QuickSetupMessages.*;
 import static org.opends.server.util.CollectionUtils.*;
 
@@ -457,22 +457,17 @@
 
     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)
       {
-        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;
-        }
+        timeout = application.getUserData().getConnectTimeout();
       }
-      catch (NamingException ne)
+      HostPort hp = new HostPort(getHostName(i), port);
+      try (ConnectionWrapper conn = new ConnectionWrapper(hp, LDAPS, userDn, userPw, timeout, null))
+      {
+        return;
+      }
+      catch (LdapException ne)
       {
         logger.warn(LocalizableMessage.raw("Could not connect to server: "+ne, ne));
       }
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java
index 9c908bf..929496c 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java
@@ -64,7 +64,6 @@
 import java.util.TreeSet;
 import java.util.concurrent.atomic.AtomicReference;
 
-import javax.naming.NamingException;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLHandshakeException;
 import javax.net.ssl.TrustManager;
@@ -1108,7 +1107,7 @@
         {
           return newConnectionWrapper(ci, LDAPS, ci.getConnectTimeout());
         }
-        catch (NamingException e)
+        catch (LdapException e)
         {
           if (promptForCertificate)
           {
@@ -1160,7 +1159,7 @@
         {
           return newConnectionWrapper(ci, START_TLS, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT);
         }
-        catch (NamingException e)
+        catch (LdapException e)
         {
           if (!promptForCertificate)
           {
@@ -1191,7 +1190,7 @@
       {
         return newConnectionWrapper(ci, LDAP, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT);
       }
-      catch (NamingException e)
+      catch (LdapException e)
       {
         throw failedToConnect(hostName, portNumber);
       }
@@ -1199,7 +1198,7 @@
   }
 
   private ConnectionWrapper newConnectionWrapper(
-      LDAPConnectionConsoleInteraction ci, Type connType, int connectTimeout) throws NamingException
+      LDAPConnectionConsoleInteraction ci, Type connType, int connectTimeout) throws LdapException
   {
     return new ConnectionWrapper(getHostPort(ci), connType, ci.getBindDN(), ci.getBindPassword(),
         connectTimeout, ci.getTrustManager(), ci.getKeyManager());
@@ -1482,7 +1481,7 @@
       return new ConnectionWrapper(uData.getHostPort(), connectionType,
           bindDn, uData.getAdminPwd(), getConnectTimeout(), getTrustManager(sourceServerCI));
     }
-    catch (NamingException e)
+    catch (LdapException e)
     {
       errPrintln();
       errPrintln(getMessageForException(e, uData.getHostPort().toString()));
@@ -3328,7 +3327,7 @@
               {
                 reloadTopology = true;
                 cancelled = !ci.promptForCertificateConfirmation(e.getCause(),
-                    e.getTrustManager(), e.getLdapUrl(), logger);
+                    e.getTrustManager(), e.getHostPort(), logger);
               }
               else
               {
@@ -3765,7 +3764,7 @@
       return new ConnectionWrapper(server.getHostPort(), connectionType, server.getBindDn(), server.getPwd(),
           getConnectTimeout(), getTrustManager(sourceServerCI));
     }
-    catch (NamingException e)
+    catch (LdapException e)
     {
       errorMessages.add(getMessageForException(e, server.getHostPort().toString()));
       logger.error(LocalizableMessage.raw("Error when creating connection for:" + server.getHostPort()));
@@ -3954,7 +3953,7 @@
       return new ConnectionWrapper(server, connectionType, getAdministratorDN(uData.getAdminUid()),
           uData.getAdminPwd(), getConnectTimeout(), getTrustManager(sourceServerCI));
     }
-    catch (NamingException ne)
+    catch (LdapException ne)
     {
       errPrintln();
       errPrintln(getMessageForException(ne, server.toString()));
@@ -6565,11 +6564,11 @@
           updateReplicationServer(conn, allRepServers);
         }
       }
-      catch (NamingException ne)
+      catch (LdapException e)
       {
         HostPort hostPort = getHostPort2(s, cache.getPreferredConnections());
-        LocalizableMessage msg = getMessageForException(ne, hostPort.toString());
-        throw new ReplicationCliException(msg, ERROR_CONNECTING, ne);
+        LocalizableMessage msg = getMessageForException(e, hostPort.toString());
+        throw new ReplicationCliException(msg, ERROR_CONNECTING, e);
       }
       catch (Exception ode)
       {
@@ -7236,7 +7235,7 @@
         }
       }
     }
-    catch (NamingException ne)
+    catch (LdapException ne)
     {
       hostPort = getHostPort2(server, cnx);
       LocalizableMessage msg = getMessageForException(ne, hostPort.toString());
@@ -7483,27 +7482,7 @@
     Throwable c = rce.getCause();
     if (c != null)
     {
-      String s;
-      if (c instanceof NamingException)
-      {
-        s = ((NamingException)c).toString(true);
-      }
-      else if (c instanceof OpenDsException)
-      {
-        LocalizableMessage msg = ((OpenDsException)c).getMessageObject();
-        if (msg != null)
-        {
-          s = msg.toString();
-        }
-        else
-        {
-          s = c.toString();
-        }
-      }
-      else
-      {
-        s = c.toString();
-      }
+      String s = toString(c);
       if (!mb.toString().contains(s))
       {
         mb.append(Constants.LINE_SEPARATOR);
@@ -9072,8 +9051,15 @@
 
   private String toString(Throwable t)
   {
-    return (t instanceof OpenDsException) ?
-        ((OpenDsException) t).getMessageObject().toString() : t.toString();
+    if (t instanceof OpenDsException)
+    {
+      LocalizableMessage msg = ((OpenDsException) t).getMessageObject();
+      if (msg != null)
+      {
+        return msg.toString();
+      }
+    }
+    return t.toString();
   }
 
   private TopologyCache createTopologyCache(ADSContext adsCtx, Set<PreferredConnection> cnx)
@@ -9095,7 +9081,7 @@
     }
   }
 
-  private ConnectionWrapper getConnection(TopologyCache cache, ServerDescriptor server) throws NamingException
+  private ConnectionWrapper getConnection(TopologyCache cache, ServerDescriptor server) throws LdapException
   {
     ConnectionWrapper conn = cache.getAdsContext().getConnection();
 
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java
index 6bc9415..f7166e1 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/tools/status/StatusCli.java
@@ -31,7 +31,6 @@
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.PrintStream;
-import java.net.URI;
 import java.security.GeneralSecurityException;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
@@ -40,8 +39,6 @@
 import java.util.TreeSet;
 import java.util.concurrent.TimeUnit;
 
-import javax.naming.AuthenticationException;
-import javax.naming.NamingException;
 import javax.net.ssl.KeyManager;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.TrustManager;
@@ -53,6 +50,7 @@
 import org.forgerock.opendj.config.LDAPProfile;
 import org.forgerock.opendj.config.client.ManagementContext;
 import org.forgerock.opendj.config.client.ldap.LDAPManagementContext;
+import org.forgerock.opendj.ldap.AuthenticationException;
 import org.forgerock.opendj.ldap.AuthorizationException;
 import org.forgerock.opendj.ldap.Connection;
 import org.forgerock.opendj.ldap.DN;
@@ -84,7 +82,6 @@
 import org.opends.server.util.cli.LDAPConnectionConsoleInteraction;
 
 import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.CliConstants;
 import com.forgerock.opendj.cli.ClientException;
 import com.forgerock.opendj.cli.ConsoleApplication;
 import com.forgerock.opendj.cli.IntegerArgument;
@@ -248,17 +245,7 @@
       // LDAPConnectionConsoleInteraction, this done, it will not prompt
       // the user for them.
       controlInfo.setConnectionPolicy(ConnectionProtocolPolicy.USE_ADMIN);
-      String ldapUrl = controlInfo.getAdminConnectorURL();
-      int port = CliConstants.DEFAULT_ADMINISTRATION_CONNECTOR_PORT;
-      try
-      {
-        final URI uri = new URI(ldapUrl);
-        port = uri.getPort();
-      }
-      catch (Throwable t)
-      {
-        logger.error(LocalizableMessage.raw("Error parsing url: " + ldapUrl));
-      }
+      int port = controlInfo.getAdminConnectorHostPort().getPort();
       final SecureConnectionCliArgs secureArgsList = argParser.getSecureArgsList();
       final StringArgument hostNameArg = secureArgsList.getHostNameArg();
       hostNameArg.setPresent(true);
@@ -325,7 +312,7 @@
           if (!controlInfo.getServerDescriptor().getExceptions().isEmpty()) {
             return ReturnCode.ERROR_INITIALIZING_SERVER.get();
           }
-        } catch (NamingException |IOException e) {
+        } catch (IOException e) {
           // This should not happen but this is useful information to
           // diagnose the error.
           println();
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java b/opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java
index 03c835c..b0e0cc1 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/StaticUtils.java
@@ -44,9 +44,6 @@
 import java.util.Map;
 import java.util.TimeZone;
 
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
 import org.forgerock.i18n.LocalizableMessage;
 import org.forgerock.i18n.LocalizableMessageBuilder;
 import org.forgerock.i18n.LocalizableMessageDescriptor;
@@ -2275,34 +2272,6 @@
   }
 
   /**
-   * Closes the provided {@link InitialContext}'s ignoring any errors which occurred.
-   *
-   * @param ctxs
-   *          The contexts to be closed, which may be {@code null}.
-   */
-  public static void close(InitialContext... ctxs)
-  {
-    if (ctxs == null)
-    {
-      return;
-    }
-    for (InitialContext ctx : ctxs)
-    {
-      if (ctx != null)
-      {
-        try
-        {
-          ctx.close();
-        }
-        catch (NamingException ignored)
-        {
-          // ignore
-        }
-      }
-    }
-  }
-
-  /**
    * Calls {@link Thread#sleep(long)}, surrounding it with the mandatory
    * {@code try} / {@code catch(InterruptedException)} block.
    *
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java b/opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
index a11ced7..c609010 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
@@ -16,10 +16,8 @@
  */
 package org.opends.server.util.cli;
 
-import static com.forgerock.opendj.cli.Utils.portValidationCallback;
-import static com.forgerock.opendj.cli.Utils.isDN;
-import static com.forgerock.opendj.cli.Utils.getAdministratorDN;
-import static com.forgerock.opendj.cli.Utils.getThrowableMsg;
+import static com.forgerock.opendj.cli.Utils.*;
+
 import static org.opends.messages.ToolMessages.*;
 
 import java.io.File;
@@ -27,8 +25,6 @@
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.net.InetAddress;
-import java.net.URI;
-import java.net.URISyntaxException;
 import java.net.UnknownHostException;
 import java.security.KeyStore;
 import java.security.KeyStoreException;
@@ -48,6 +44,7 @@
 import org.opends.server.tools.LDAPConnectionOptions;
 import org.opends.server.tools.SSLConnectionException;
 import org.opends.server.tools.SSLConnectionFactory;
+import org.opends.server.types.HostPort;
 import org.opends.server.util.CollectionUtils;
 import org.opends.server.util.SelectableCertificateKeyManager;
 
@@ -1580,15 +1577,14 @@
    *          the error raised because the certificate was not trusted.
    * @param usedTrustManager
    *          the trustManager used when trying to establish the connection.
-   * @param usedUrl
-   *          the LDAP URL used to connect to the server.
+   * @param hostPort
+   *          the HostPort used to connect to the server.
    * @param logger
    *          the Logger used to log messages.
-   * @return {@code true} if the user accepted the certificate and
-   *         {@code false} otherwise.
+   * @return {@code true} if the user accepted the certificate and {@code false} otherwise.
    */
   public boolean promptForCertificateConfirmation(Throwable errorRaised,
-      ApplicationTrustManager usedTrustManager, String usedUrl, LocalizedLogger logger)
+      ApplicationTrustManager usedTrustManager, HostPort hostPort, LocalizedLogger logger)
   {
     final ApplicationTrustManager.Cause cause = usedTrustManager != null ? usedTrustManager.getLastRefusedCause()
                                                                          : null;
@@ -1600,21 +1596,8 @@
       return false;
     }
 
-    String host;
-    int port;
-    try
-    {
-      URI uri = new URI(usedUrl);
-      host = uri.getHost();
-      port = uri.getPort();
-    }
-    catch (URISyntaxException e)
-    {
-      logger.warn(ERROR_CERTIFICATE_PARSING_URL.get(usedUrl, e));
-      host = INFO_NOT_AVAILABLE_LABEL.get().toString();
-      port = -1;
-    }
-
+    String host = hostPort.getHost();
+    int port = hostPort.getPort();
     final String authType = usedTrustManager.getLastRefusedAuthType();
     if (authType == null)
     {

--
Gitblit v1.10.0