From 31da6f93e7078135157ea5944e3977550eedef3e Mon Sep 17 00:00:00 2001
From: Jean-Noël Rouvignac <jean-noel.rouvignac@forgerock.com>
Date: Wed, 27 Jul 2016 12:07:23 +0000
Subject: [PATCH] code cleanup

---
 opendj-server-legacy/src/main/java/org/opends/server/tools/dsreplication/ReplicationCliMain.java |   65 +--
 opendj-cli/src/main/java/com/forgerock/opendj/cli/CommandBuilder.java                            |   48 +--
 opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/util/Utilities.java          |  544 +++++++++++++++++---------------------
 opendj-server-legacy/src/main/java/org/opends/admin/ads/util/ConnectionUtils.java                |  146 ++++------
 4 files changed, 346 insertions(+), 457 deletions(-)

diff --git a/opendj-cli/src/main/java/com/forgerock/opendj/cli/CommandBuilder.java b/opendj-cli/src/main/java/com/forgerock/opendj/cli/CommandBuilder.java
index 6f379e8..3333519 100644
--- a/opendj-cli/src/main/java/com/forgerock/opendj/cli/CommandBuilder.java
+++ b/opendj-cli/src/main/java/com/forgerock/opendj/cli/CommandBuilder.java
@@ -18,8 +18,8 @@
 
 import static com.forgerock.opendj.cli.Utils.OBFUSCATED_VALUE;
 
-import java.util.Arrays;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
@@ -27,38 +27,22 @@
 
 import com.forgerock.opendj.util.OperatingSystem;
 
-/**
- * Class used to be able to generate the non interactive mode.
- */
+/** Class used to be able to generate the non interactive mode. */
 public class CommandBuilder {
     private String commandName;
     private String subcommandName;
-    private final ArrayList<Argument> args = new ArrayList<>();
-    private final HashSet<Argument> obfuscatedArgs = new HashSet<>();
+    private final List<Argument> args = new ArrayList<>();
+    /** Arguments whose values must be obfuscated (passwords for instance). */
+    private final Set<Argument> obfuscatedArgs = new HashSet<>();
 
-    /**
-     * The separator used to link the lines of the resulting command-lines.
-     */
-    public static final String LINE_SEPARATOR;
-    static {
-        if (OperatingSystem.isWindows()) {
-            LINE_SEPARATOR = " ";
-        } else {
-            LINE_SEPARATOR = " \\\n          ";
-        }
-    }
+    /** The separator used to link the lines of the resulting command-lines. */
+    public static final String LINE_SEPARATOR =
+        OperatingSystem.isWindows() ? " " : " \\\n          ";
 
-    /**
-     * The separator used to link the lines of the resulting command-lines in HTML format.
-     */
-    public static final String HTML_LINE_SEPARATOR;
-    static {
-        if (OperatingSystem.isWindows()) {
-            HTML_LINE_SEPARATOR = "&nbsp;";
-        } else {
-            HTML_LINE_SEPARATOR = "&nbsp;\\<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
-        }
-    }
+    /** The separator used to link the lines of the resulting command-lines in HTML format. */
+    public static final String HTML_LINE_SEPARATOR = OperatingSystem.isWindows()
+        ? "&nbsp;"
+        : "&nbsp;\\<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
 
     /** Creates a {@link CommandBuilder} with {@code null} command and subcommand names. */
     public CommandBuilder() {
@@ -108,7 +92,7 @@
      *
      * @param argument
      *            The argument to be removed.
-     * @return <CODE>true</CODE> if the attribute was present and removed and <CODE>false</CODE> otherwise.
+     * @return {@code true} if the attribute was present and removed and {@code false} otherwise.
      */
     public boolean removeArgument(final Argument argument) {
         obfuscatedArgs.remove(argument);
@@ -217,9 +201,7 @@
         return escapeValue(value);
     }
 
-    /**
-     * Clears the arguments.
-     */
+    /** Clears the arguments. */
     public void clearArguments() {
         args.clear();
         obfuscatedArgs.clear();
@@ -239,7 +221,7 @@
      *
      * @param argument
      *            The argument to handle.
-     * @return <CODE>true</CODE> if the attribute's values must be obfuscated and <CODE>false</CODE> otherwise.
+     * @return {@code true} if the attribute's values must be obfuscated and {@code false} otherwise.
      */
     public boolean isObfuscated(final Argument argument) {
         return obfuscatedArgs.contains(argument);
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 86c219b..49feb14 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
@@ -93,12 +93,7 @@
       String pwd, int timeout, Hashtable<String, String> env)
       throws NamingException
   {
-    env = copy(env);
-    env.put(Context.INITIAL_CONTEXT_FACTORY,
-        "com.sun.jndi.ldap.LdapCtxFactory");
-    env.put("java.naming.ldap.attributes.binary",
-        EntryHistorical.HISTORICAL_ATTRIBUTE_NAME);
-    env.put(Context.PROVIDER_URL, ldapURL);
+    env = newEnvironmentFrom(ldapURL, env);
     if (timeout >= 1)
     {
       env.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(timeout));
@@ -113,8 +108,7 @@
     }
 
     /* Contains the DirContext and the Exception if any */
-    final Object[] pair = new Object[]
-      { null, null };
+    final Object[] pair = { null, null };
     final Hashtable<String, String> fEnv = env;
     Thread t = new Thread(new Runnable()
     {
@@ -124,11 +118,9 @@
         try
         {
           pair[0] = new InitialLdapContext(fEnv, null);
-
         } catch (NamingException ne)
         {
           pair[1] = ne;
-
         } catch (Throwable t)
         {
           t.printStackTrace();
@@ -166,20 +158,14 @@
    */
   static InitialLdapContext createLdapsContext(String ldapsURL,
       String dn, String pwd, int timeout, Hashtable<String, String> env,
-      TrustManager trustManager, KeyManager keyManager) throws NamingException {
-    env = copy(env);
-    env.put(Context.INITIAL_CONTEXT_FACTORY,
-        "com.sun.jndi.ldap.LdapCtxFactory");
-    env.put("java.naming.ldap.attributes.binary",
-        EntryHistorical.HISTORICAL_ATTRIBUTE_NAME);
-    env.put(Context.PROVIDER_URL, ldapsURL);
-    env.put("java.naming.ldap.factory.socket",
-        org.opends.admin.ads.util.TrustedSocketFactory.class.getName());
+      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)
     {
-      env.put(Context.SECURITY_PRINCIPAL, dn);
-      env.put(Context.SECURITY_CREDENTIALS, pwd);
+      newEnv.put(Context.SECURITY_PRINCIPAL, dn);
+      newEnv.put(Context.SECURITY_CREDENTIALS, pwd);
     }
 
     if (trustManager == null)
@@ -188,18 +174,14 @@
     }
 
     /* Contains the DirContext and the Exception if any */
-    final Object[] pair = new Object[] {null, null};
-    final Hashtable<String, String> fEnv = env;
+    final Object[] pair = { null, null };
     final TrustManager fTrustManager = trustManager;
-    final KeyManager   fKeyManager   = keyManager;
-
     Thread t = new Thread(new Runnable() {
       @Override
       public void run() {
         try {
-          TrustedSocketFactory.setCurrentThreadTrustManager(fTrustManager,
-              fKeyManager);
-          pair[0] = new InitialLdapContext(fEnv, null);
+          TrustedSocketFactory.setCurrentThreadTrustManager(fTrustManager, keyManager);
+          pair[0] = new InitialLdapContext(newEnv, null);
         } catch (NamingException | RuntimeException ne) {
           pair[1] = ne;
         }
@@ -221,19 +203,17 @@
    * @throws NamingException if there was an error creating the new connection.
    */
   public static ConnectionWrapper cloneConnectionWrapper(
-      final ConnectionWrapper conn, int timeout, TrustManager trustManager,
-      KeyManager keyManager) throws NamingException
+      final ConnectionWrapper conn, int timeout, final TrustManager trustManager,
+      final KeyManager keyManager) throws NamingException
   {
-    final Object[] pair = new Object[] {null, null};
-    final TrustManager fTrustManager = trustManager;
-    final KeyManager fKeyManager = keyManager;
+    final Object[] pair = { null, null };
     Thread t = new Thread(new Runnable() {
       @Override
       public void run() {
         try {
           if (conn.isSSL() || conn.isStartTLS())
           {
-            TrustedSocketFactory.setCurrentThreadTrustManager(fTrustManager, fKeyManager);
+            TrustedSocketFactory.setCurrentThreadTrustManager(trustManager, keyManager);
           }
           pair[0] = new ConnectionWrapper(conn);
         } catch (NamingException | RuntimeException ne) {
@@ -278,8 +258,8 @@
    * @see TrustedSocketFactory
    */
   static InitialLdapContext createStartTLSContext(String ldapURL,
-      String dn, String pwd, int timeout, Hashtable<String, String> env,
-      TrustManager trustManager, KeyManager keyManager,
+      final String dn, final String pwd, int timeout, Hashtable<String, String> env,
+      TrustManager trustManager, final KeyManager keyManager,
       HostnameVerifier verifier)
   throws NamingException
   {
@@ -291,41 +271,28 @@
       verifier = new BlindHostnameVerifier();
     }
 
-    env = copy(env);
-    env.put(Context.INITIAL_CONTEXT_FACTORY,
-        "com.sun.jndi.ldap.LdapCtxFactory");
-    env.put("java.naming.ldap.attributes.binary",
-        EntryHistorical.HISTORICAL_ATTRIBUTE_NAME);
-    env.put(Context.PROVIDER_URL, ldapURL);
-    env.put(Context.SECURITY_AUTHENTICATION , "none");
+    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 = new Object[] {null, null};
-    final Hashtable<?, ?> fEnv = env;
-    final String fDn = dn;
-    final String fPwd = pwd;
+    final Object[] pair = { null, null };
     final TrustManager fTrustManager = trustManager;
-    final KeyManager fKeyManager     = keyManager;
     final HostnameVerifier fVerifier = verifier;
 
     Thread t = new Thread(new Runnable() {
       @Override
       public void run() {
         try {
-          StartTlsResponse tls;
+          InitialLdapContext result = new InitialLdapContext(newEnv, null);
 
-          InitialLdapContext result = new InitialLdapContext(fEnv, null);
-
-          tls = (StartTlsResponse) result.extendedOperation(
-              new StartTlsRequest());
+          StartTlsResponse tls = (StartTlsResponse) result.extendedOperation(new StartTlsRequest());
           tls.setHostnameVerifier(fVerifier);
           try
           {
-            tls.negotiate(new TrustedSocketFactory(fTrustManager,fKeyManager));
+            tls.negotiate(new TrustedSocketFactory(fTrustManager, keyManager));
           }
           catch(IOException x) {
-            NamingException xx;
-            xx = new CommunicationException(
+            NamingException xx = new CommunicationException(
                 "Failed to negotiate Start TLS operation");
             xx.initCause(x);
             result.close();
@@ -333,13 +300,13 @@
           }
 
           result.addToEnvironment(STARTTLS_PROPERTY, "true");
-          if (fDn != null)
+          if (dn != null)
           {
             result.addToEnvironment(Context.SECURITY_AUTHENTICATION , "simple");
-            result.addToEnvironment(Context.SECURITY_PRINCIPAL, fDn);
-            if (fPwd != null)
+            result.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
+            if (pwd != null)
             {
-              result.addToEnvironment(Context.SECURITY_CREDENTIALS, fPwd);
+              result.addToEnvironment(Context.SECURITY_CREDENTIALS, pwd);
             }
             result.reconnect(null);
           }
@@ -358,12 +325,21 @@
     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</CODE> if we are connected and read the configuration
-   * and <CODE>false</CODE> otherwise.
+   * @return {@code true} if we are connected and read the configuration
+   * and {@code false} otherwise.
    */
   static boolean connectedAsAdministrativeUser(InitialLdapContext ctx)
   {
@@ -435,15 +411,12 @@
       {
         t.run();
       }
-
     } catch (InterruptedException x)
     {
       // This might happen for problems in sockets
       // so it does not necessarily imply a bug
     }
 
-    boolean throwException = false;
-
     if (timeout > 0 && t.isAlive())
     {
       t.interrupt();
@@ -455,38 +428,39 @@
         // This might happen for problems in sockets
         // so it does not necessarily imply a bug
       }
-      throwException = true;
+      throw connectionTimedOut();
     }
 
-    if (pair[0] == null && pair[1] == null)
+    Object connection = pair[0];
+    Object ex = pair[1];
+    if (connection == null && ex == null)
     {
-      throwException = true;
+      throw connectionTimedOut();
     }
 
-    if (throwException)
+    if (ex != null)
     {
-      NamingException xx = new CommunicationException("Connection timed out");
-      xx.initCause(new ConnectException("Connection timed out"));
-      throw xx;
-    }
-
-    if (pair[1] != null)
-    {
-      if (pair[1] instanceof NamingException)
+      if (ex instanceof NamingException)
       {
-        throw (NamingException) pair[1];
-
-      } else if (pair[1] instanceof RuntimeException)
+        throw (NamingException) ex;
+      }
+      else if (ex instanceof RuntimeException)
       {
-        throw (RuntimeException) pair[1];
-
-      } else if (pair[1] instanceof Throwable)
+        throw (RuntimeException) ex;
+      }
+      else if (ex instanceof Throwable)
       {
-        throw new IllegalStateException("Unexpected throwable occurred",
-            (Throwable) pair[1]);
+        throw new IllegalStateException("Unexpected throwable occurred", (Throwable) ex);
       }
     }
-    return (T) pair[0];
+    return (T) connection;
+  }
+
+  private static NamingException connectionTimedOut()
+  {
+    NamingException xx = new CommunicationException("Connection timed out");
+    xx.initCause(new ConnectException("Connection timed out"));
+    return xx;
   }
 
   /**
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 b606029..0ed7b7b 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
@@ -16,10 +16,9 @@
  */
 package org.opends.guitools.controlpanel.util;
 
-import static org.opends.server.util.SchemaUtils.getElementSchemaFile;
-
 import static com.forgerock.opendj.cli.Utils.*;
 import static com.forgerock.opendj.util.OperatingSystem.*;
+
 import static org.forgerock.opendj.ldap.DereferenceAliasesPolicy.*;
 import static org.forgerock.opendj.ldap.SearchScope.*;
 import static org.forgerock.opendj.ldap.requests.Requests.*;
@@ -107,8 +106,8 @@
 import org.forgerock.opendj.ldap.schema.SchemaBuilder;
 import org.forgerock.opendj.ldap.schema.SchemaElement;
 import org.forgerock.opendj.ldap.schema.Syntax;
-import org.forgerock.opendj.ldif.ConnectionEntryReader;
 import org.opends.admin.ads.util.ConnectionWrapper;
+import org.opends.admin.ads.util.PreferredConnection.Type;
 import org.opends.guitools.controlpanel.ControlPanel;
 import org.opends.guitools.controlpanel.browser.IconPool;
 import org.opends.guitools.controlpanel.datamodel.CategorizedComboBoxElement;
@@ -160,8 +159,8 @@
   private static ImageIcon warningIcon;
   private static ImageIcon requiredIcon;
 
-  private final static LocalizableMessage NO_VALUE_SET = INFO_CTRL_PANEL_NO_MONITORING_VALUE.get();
-  private final static LocalizableMessage NOT_IMPLEMENTED = INFO_CTRL_PANEL_NOT_IMPLEMENTED.get();
+  private static final LocalizableMessage NO_VALUE_SET = INFO_CTRL_PANEL_NO_MONITORING_VALUE.get();
+  private static final LocalizableMessage NOT_IMPLEMENTED = INFO_CTRL_PANEL_NOT_IMPLEMENTED.get();
 
   /**
    * Creates a combo box.
@@ -500,16 +499,14 @@
   public static JMenu createMenu(LocalizableMessage msg, LocalizableMessage description)
   {
     JMenu menu = new JMenu(msg.toString());
-    menu.getAccessibleContext().setAccessibleDescription(
-        description.toString());
+    menu.getAccessibleContext().setAccessibleDescription(description.toString());
     return menu;
   }
 
   /**
-   * Creates a label of type 'primary' (with bigger font than usual) with no
-   * text.
-   * @return the label of type 'primary' (with bigger font than usual) with no
-   * text.
+   * Creates a label of type 'primary' (with bigger font than usual) with no text.
+   *
+   * @return the label of type 'primary' (with bigger font than usual) with no text.
    */
   public static JLabel createPrimaryLabel()
   {
@@ -596,7 +593,7 @@
           BorderFactory.createMatteBorder(1, 1, 0, 0,
               ColorAndFontConstants.gridColor));
     }
-    if (isWindows())
+    else if (isWindows())
     {
       table.getTableHeader().setBorder(
           BorderFactory.createMatteBorder(1, 1, 0, 1,
@@ -671,8 +668,7 @@
    * @param cols the columns of the text area.
    * @return a text area.
    */
-  public static JTextArea createTextArea(LocalizableMessage text, int rows,
-      int cols)
+  public static JTextArea createTextArea(LocalizableMessage text, int rows, int cols)
   {
     JTextArea ta = new JTextArea(text.toString(), rows, cols);
     ta.setFont(ColorAndFontConstants.defaultFont);
@@ -726,7 +722,6 @@
     return tf;
   }
 
-
   /**
    * Creates a text field with the default size.
    * @return the created text field.
@@ -740,7 +735,7 @@
   }
 
   /**
-   * Creates a pasword text field.
+   * Creates a password text field.
    * @return the created password text field.
    */
   public static JPasswordField createPasswordField()
@@ -752,7 +747,7 @@
   }
 
   /**
-   * Creates a pasword text field.
+   * Creates a password text field.
    * @param cols the columns of the password text field.
    * @return the created password text field.
    */
@@ -772,14 +767,9 @@
    */
   public static void setBorder(JComponent comp, Border border)
   {
-    if (comp.getBorder() != null)
-    {
-      comp.setBorder(BorderFactory.createCompoundBorder(comp.getBorder(), border));
-    }
-    else
-    {
-      comp.setBorder(border);
-    }
+    comp.setBorder(comp.getBorder() != null
+        ? BorderFactory.createCompoundBorder(comp.getBorder(), border)
+        : border);
   }
 
   /**
@@ -793,14 +783,9 @@
     int width1 = table.getPreferredScrollableViewportSize().width;
     int width2 = scroll.getViewport().getWidth();
 
-    if (width1 > width2)
-    {
-      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
-    }
-    else
-    {
-      table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
-    }
+    table.setAutoResizeMode(width1 > width2
+        ? JTable.AUTO_RESIZE_OFF
+        : JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
   }
 
   /**
@@ -942,11 +927,11 @@
 
 
   /**
-   * Returns an ImageIcon or <CODE>null</CODE> if the path was invalid.
+   * Returns an ImageIcon or {@code null} if the path was invalid.
    * @param path the path of the image.
    * @param loader the class loader to use to load the image.  If
-   * <CODE>null</CODE> this class class loader will be used.
-   * @return an ImageIcon or <CODE>null</CODE> if the path was invalid.
+   * {@code null} this class class loader will be used.
+   * @return an ImageIcon or {@code null} if the path was invalid.
    */
   public static ImageIcon createImageIcon(String path, ClassLoader loader) {
     if (loader == null)
@@ -958,9 +943,9 @@
   }
 
   /**
-   * Returns an ImageIcon or <CODE>null</CODE> if the path was invalid.
+   * Returns an ImageIcon or {@code null} if the path was invalid.
    * @param path the path of the image.
-   * @return an ImageIcon or <CODE>null</CODE> if the path was invalid.
+   * @return an ImageIcon or {@code null} if the path was invalid.
    */
   public static ImageIcon createImageIcon(String path) {
     return createImageIcon(path, null);
@@ -1099,8 +1084,7 @@
       {
         if (s.length() >= i + HTML_SPACE.length())
         {
-          if (HTML_SPACE.equalsIgnoreCase(s.substring(i, i
-              + HTML_SPACE.length())))
+          if (HTML_SPACE.equalsIgnoreCase(s.substring(i, i + HTML_SPACE.length())))
           {
             if (lastLineLength < nCols)
             {
@@ -1261,10 +1245,10 @@
   }
 
   /**
-   * Returns the parent frame of a component.  <CODE>null</CODE> if this
+   * Returns the parent frame of a component.  {@code null} if this
    * component is not contained in any frame.
    * @param comp the component.
-   * @return the parent frame of a component.  <CODE>null</CODE> if this
+   * @return the parent frame of a component.  {@code null} if this
    * component is not contained in any frame.
    */
   public static JFrame getFrame(Component comp)
@@ -1278,10 +1262,10 @@
   }
 
   /**
-   * Returns the parent dialog of a component.  <CODE>null</CODE> if this
+   * Returns the parent dialog of a component.  {@code null} if this
    * component is not contained in any dialog.
    * @param comp the component.
-   * @return the parent dialog of a component.  <CODE>null</CODE> if this
+   * @return the parent dialog of a component.  {@code null} if this
    * component is not contained in any dialog.
    */
   public static Window getParentDialog(Component comp)
@@ -1317,131 +1301,8 @@
                 && StaticUtils.isHexDigit(stringBytes[i+1])
                 && StaticUtils.isHexDigit(stringBytes[i+2]))
         {
-          // Convert hex-encoded UTF-8 to 16-bit chars.
-          byte b;
-
-          byte escapedByte1 = stringBytes[++i];
-          switch (escapedByte1)
-          {
-          case '0':
-            b = (byte) 0x00;
-            break;
-          case '1':
-            b = (byte) 0x10;
-            break;
-          case '2':
-            b = (byte) 0x20;
-            break;
-          case '3':
-            b = (byte) 0x30;
-            break;
-          case '4':
-            b = (byte) 0x40;
-            break;
-          case '5':
-            b = (byte) 0x50;
-            break;
-          case '6':
-            b = (byte) 0x60;
-            break;
-          case '7':
-            b = (byte) 0x70;
-            break;
-          case '8':
-            b = (byte) 0x80;
-            break;
-          case '9':
-            b = (byte) 0x90;
-            break;
-          case 'a':
-          case 'A':
-            b = (byte) 0xA0;
-            break;
-          case 'b':
-          case 'B':
-            b = (byte) 0xB0;
-            break;
-          case 'c':
-          case 'C':
-            b = (byte) 0xC0;
-            break;
-          case 'd':
-          case 'D':
-            b = (byte) 0xD0;
-            break;
-          case 'e':
-          case 'E':
-            b = (byte) 0xE0;
-            break;
-          case 'f':
-          case 'F':
-            b = (byte) 0xF0;
-            break;
-          default:
-            throw new RuntimeException("Unexpected byte: "+escapedByte1);
-          }
-
-          byte escapedByte2 = stringBytes[++i];
-          switch (escapedByte2)
-          {
-          case '0':
-            break;
-          case '1':
-            b |= 0x01;
-            break;
-          case '2':
-            b |= 0x02;
-            break;
-          case '3':
-            b |= 0x03;
-            break;
-          case '4':
-            b |= 0x04;
-            break;
-          case '5':
-            b |= 0x05;
-            break;
-          case '6':
-            b |= 0x06;
-            break;
-          case '7':
-            b |= 0x07;
-            break;
-          case '8':
-            b |= 0x08;
-            break;
-          case '9':
-            b |= 0x09;
-            break;
-          case 'a':
-          case 'A':
-            b |= 0x0A;
-            break;
-          case 'b':
-          case 'B':
-            b |= 0x0B;
-            break;
-          case 'c':
-          case 'C':
-            b |= 0x0C;
-            break;
-          case 'd':
-          case 'D':
-            b |= 0x0D;
-            break;
-          case 'e':
-          case 'E':
-            b |= 0x0E;
-            break;
-          case 'f':
-          case 'F':
-            b |= 0x0F;
-            break;
-          default:
-            throw new RuntimeException("Unexpected byte: "+escapedByte2);
-          }
-
-          decodedBytes[pos++] = b;
+          decodedBytes[pos++] = convertHexEncodedUtf8To16BitChars(stringBytes, i);
+          i += 2;
         }
         else {
           decodedBytes[pos++] = stringBytes[i];
@@ -1449,13 +1310,142 @@
       }
       return new String(decodedBytes, 0, pos, "UTF-8");
     }
-    catch (UnsupportedEncodingException uee)
+    catch (UnsupportedEncodingException unexpected)
     {
-//    This is a bug, UTF-8 should be supported always by the JVM
-      throw new RuntimeException("UTF-8 encoding not supported", uee);
+      // This is a bug, UTF-8 should be supported always by the JVM
+      throw new RuntimeException("UTF-8 encoding not supported", unexpected);
     }
   }
 
+  /** Convert hex-encoded UTF-8 to 16-bit chars. */
+  private static byte convertHexEncodedUtf8To16BitChars(byte[] bytes, int i)
+  {
+    byte b;
+
+    byte escapedByte1 = bytes[i + 1];
+    switch (escapedByte1)
+    {
+    case '0':
+      b = (byte) 0x00;
+      break;
+    case '1':
+      b = (byte) 0x10;
+      break;
+    case '2':
+      b = (byte) 0x20;
+      break;
+    case '3':
+      b = (byte) 0x30;
+      break;
+    case '4':
+      b = (byte) 0x40;
+      break;
+    case '5':
+      b = (byte) 0x50;
+      break;
+    case '6':
+      b = (byte) 0x60;
+      break;
+    case '7':
+      b = (byte) 0x70;
+      break;
+    case '8':
+      b = (byte) 0x80;
+      break;
+    case '9':
+      b = (byte) 0x90;
+      break;
+    case 'a':
+    case 'A':
+      b = (byte) 0xA0;
+      break;
+    case 'b':
+    case 'B':
+      b = (byte) 0xB0;
+      break;
+    case 'c':
+    case 'C':
+      b = (byte) 0xC0;
+      break;
+    case 'd':
+    case 'D':
+      b = (byte) 0xD0;
+      break;
+    case 'e':
+    case 'E':
+      b = (byte) 0xE0;
+      break;
+    case 'f':
+    case 'F':
+      b = (byte) 0xF0;
+      break;
+    default:
+      throw new RuntimeException("Unexpected byte: " + escapedByte1);
+    }
+
+    byte escapedByte2 = bytes[i + 2];
+    switch (escapedByte2)
+    {
+    case '0':
+      break;
+    case '1':
+      b |= 0x01;
+      break;
+    case '2':
+      b |= 0x02;
+      break;
+    case '3':
+      b |= 0x03;
+      break;
+    case '4':
+      b |= 0x04;
+      break;
+    case '5':
+      b |= 0x05;
+      break;
+    case '6':
+      b |= 0x06;
+      break;
+    case '7':
+      b |= 0x07;
+      break;
+    case '8':
+      b |= 0x08;
+      break;
+    case '9':
+      b |= 0x09;
+      break;
+    case 'a':
+    case 'A':
+      b |= 0x0A;
+      break;
+    case 'b':
+    case 'B':
+      b |= 0x0B;
+      break;
+    case 'c':
+    case 'C':
+      b |= 0x0C;
+      break;
+    case 'd':
+    case 'D':
+      b |= 0x0D;
+      break;
+    case 'e':
+    case 'E':
+      b |= 0x0E;
+      break;
+    case 'f':
+    case 'F':
+      b |= 0x0F;
+      break;
+    default:
+      throw new RuntimeException("Unexpected byte: " + escapedByte2);
+    }
+
+    return b;
+  }
+
   /**
    * Returns whether the provided strings represent the same DN.
    *
@@ -1488,7 +1478,7 @@
   }
 
   /** The pattern for control characters. */
-  private final static Pattern cntrl_pattern = Pattern.compile("\\p{Cntrl}", Pattern.MULTILINE);
+  private static final Pattern cntrl_pattern = Pattern.compile("\\p{Cntrl}", Pattern.MULTILINE);
 
   /**
    * Checks if a string contains control characters.
@@ -2024,11 +2014,7 @@
       return configurationSchemaFileNames.contains(fileName);
     }
     String xOrigin = getElementOrigin(fileElement);
-    if (xOrigin != null)
-    {
-      return configurationSchemaOrigins.contains(xOrigin);
-    }
-    return false;
+    return xOrigin != null && configurationSchemaOrigins.contains(xOrigin);
   }
 
   /**
@@ -2157,21 +2143,9 @@
   public static ConnectionWrapper getAdminDirContext(ControlPanelInfo controlInfo, String bindDN, String pwd)
       throws NamingException, IOException, ConfigReadException
   {
-    String usedUrl = controlInfo.getAdminConnectorURL();
-    if (usedUrl == null)
-    {
-      throw new ConfigReadException(
-          ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
-    }
-
-    // Search for the config to check that it is the directory manager.
-    ConnectionWrapper conn = new ConnectionWrapper(
-        usedUrl, LDAPS, bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
-    checkCanReadConfig(conn);
-    return conn;
+    return createConnection(controlInfo.getAdminConnectorURL(), LDAPS, bindDN, pwd, controlInfo);
   }
 
-
   /**
    * Returns the connection to connect to the server using the
    * information in the ControlCenterInfo object (which provides the host, port
@@ -2190,41 +2164,30 @@
   public static ConnectionWrapper getUserDataDirContext(ControlPanelInfo controlInfo,
       String bindDN, String pwd) throws NamingException, IOException, ConfigReadException
   {
-    ConnectionWrapper conn;
     if (controlInfo.connectUsingStartTLS())
     {
-      String usedUrl = controlInfo.getStartTLSURL();
-      if (usedUrl == null)
-      {
-        throw new ConfigReadException(
-            ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
-      }
-      conn = new ConnectionWrapper(usedUrl, START_TLS,
-          bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
+      return createConnection(controlInfo.getStartTLSURL(), START_TLS, bindDN, pwd, controlInfo);
     }
     else if (controlInfo.connectUsingLDAPS())
     {
-      String usedUrl = controlInfo.getLDAPSURL();
-      if (usedUrl == null)
-      {
-        throw new ConfigReadException(
-            ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
-      }
-      conn = new ConnectionWrapper(usedUrl, LDAPS,
-          bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
+      return createConnection(controlInfo.getLDAPSURL(), LDAPS, bindDN, pwd, controlInfo);
     }
     else
     {
-      String usedUrl = controlInfo.getLDAPURL();
-      if (usedUrl == null)
-      {
-        throw new ConfigReadException(
-            ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
-      }
-      conn = new ConnectionWrapper(usedUrl, LDAP,
-          bindDN, pwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
+      return createConnection(controlInfo.getLDAPURL(), LDAP, bindDN, pwd, controlInfo);
+    }
+  }
+
+  private static ConnectionWrapper createConnection(String usedUrl, Type connectionType, String bindDN, String bindPwd,
+      ControlPanelInfo controlInfo) throws NamingException, IOException, ConfigReadException
+  {
+    if (usedUrl == null)
+    {
+      throw new ConfigReadException(ERR_COULD_NOT_FIND_VALID_LDAPURL.get());
     }
 
+    ConnectionWrapper conn = new ConnectionWrapper(usedUrl, connectionType,
+        bindDN, bindPwd, controlInfo.getConnectTimeout(), controlInfo.getTrustManager());
     checkCanReadConfig(conn);
     return conn;
   }
@@ -2241,13 +2204,8 @@
   {
     // Search for the config to check that it is the directory manager.
     SearchRequest request = newSearchRequest("cn=config", BASE_OBJECT, "objectclass=*", NO_ATTRIBUTES);
-    try (ConnectionEntryReader entryReader = conn.getConnection().search(request))
-    {
-      while (entryReader.hasNext())
-      {
-        entryReader.readEntry();
-      }
-    }
+    // rely on exception being thrown if we cannot read
+    conn.getConnection().searchSingleEntry(request);
   }
 
   /**
@@ -2265,7 +2223,7 @@
         .setSizeLimit(0)
         .setTimeLimit(0)
         .setDereferenceAliasesPolicy(NEVER);
-    connWrapper.getConnection().search(request);
+    connWrapper.getConnection().search(request).close();
   }
 
   /**
@@ -2354,10 +2312,10 @@
   }
 
   /**
-   * Returns the scrolpane where the provided component is contained.
-   * <CODE>null</CODE> if the component is not contained in any scrolpane.
+   * Returns the scrollpane where the provided component is contained.
+   * {@code null} if the component is not contained in any scrollpane.
    * @param comp the component.
-   * @return the scrolpane where the provided component is contained.
+   * @return the scrollpane where the provided component is contained.
    */
   public static JScrollPane getContainingScroll(Component comp)
   {
@@ -2430,7 +2388,7 @@
    * entry.
    *
    * @param sr
-   *          the entry. It may be <CODE>null</CODE>.
+   *          the entry. It may be {@code null}.
    * @param attrName
    *          the attribute name.
    * @return the first value as a String for a given attribute in the provided
@@ -2565,7 +2523,7 @@
    * @param newElements the new items for the combo box model.
    * @param model the combo box model to be updated.
    * @param comparator the object that will be used to compare the objects in
-   * the model.  If <CODE>null</CODE>, the equals method will be used.
+   * the model.  If {@code null}, the equals method will be used.
    */
   public static void updateComboBoxModel(Collection<?> newElements,
       DefaultComboBoxModel model,
@@ -2651,95 +2609,84 @@
   {
     for (String attrName : attrNames)
     {
-      int possibleResult;
-      if (monitor1 == null)
+      possibleResults.add(compareForAttribute(monitor1, monitor2, attrName));
+    }
+  }
+
+  private static int compareForAttribute(SearchResultEntry monitor1, SearchResultEntry monitor2, String attrName)
+  {
+    if (monitor1 == null)
+    {
+      return monitor2 == null ? 0 : -1;
+    }
+    else if (monitor2 == null)
+    {
+      return 1;
+    }
+    else
+    {
+      Object v1 = getFirstMonitoringValue(monitor1.getAttribute(attrName));
+      Object v2 = getFirstMonitoringValue(monitor2.getAttribute(attrName));
+      if (v1 == null)
       {
-        if (monitor2 == null)
-        {
-          possibleResult = 0;
-        }
-        else
-        {
-          possibleResult = -1;
-        }
+        return v2 == null ? 0 : -1;
       }
-      else if (monitor2 == null)
+      else if (v2 == null)
       {
-        possibleResult = 1;
+        return 1;
       }
-      else
+      else if (v1 instanceof Number)
       {
-        Object v1 = getFirstMonitoringValue(monitor1.getAttribute(attrName));
-        Object v2 = getFirstMonitoringValue(monitor2.getAttribute(attrName));
-        if (v1 == null)
+        if (v2 instanceof Number)
         {
-          if (v2 == null)
+          if (v1 instanceof Double || v2 instanceof Double)
           {
-            possibleResult = 0;
-          }
-          else
-          {
-            possibleResult = -1;
-          }
-        }
-        else if (v2 == null)
-        {
-          possibleResult = 1;
-        }
-        else if (v1 instanceof Number)
-        {
-          if (v2 instanceof Number)
-          {
-            if (v1 instanceof Double || v2 instanceof Double)
+            double n1 = ((Number) v1).doubleValue();
+            double n2 = ((Number) v2).doubleValue();
+            if (n1 > n2)
             {
-              double n1 = ((Number) v1).doubleValue();
-              double n2 = ((Number) v2).doubleValue();
-              if (n1 > n2)
-              {
-                possibleResult = 1;
-              }
-              else if (n1 < n2)
-              {
-                possibleResult = -1;
-              }
-              else
-              {
-                possibleResult = 0;
-              }
+              return 1;
+            }
+            else if (n1 < n2)
+            {
+              return -1;
             }
             else
             {
-              long n1 = ((Number) v1).longValue();
-              long n2 = ((Number) v2).longValue();
-              if (n1 > n2)
-              {
-                possibleResult = 1;
-              }
-              else if (n1 < n2)
-              {
-                possibleResult = -1;
-              }
-              else
-              {
-                possibleResult = 0;
-              }
+              return 0;
             }
           }
           else
           {
-            possibleResult = 1;
+            long n1 = ((Number) v1).longValue();
+            long n2 = ((Number) v2).longValue();
+            if (n1 > n2)
+            {
+              return 1;
+            }
+            else if (n1 < n2)
+            {
+              return -1;
+            }
+            else
+            {
+              return 0;
+            }
           }
         }
-        else if (v2 instanceof Number)
-        {
-          possibleResult = -1;
-        }
         else
         {
-          possibleResult = v1.toString().compareTo(v2.toString());
+          return 1;
         }
       }
-      possibleResults.add(possibleResult);
+      else if (v2 instanceof Number)
+      {
+        return -1;
+      }
+      else
+      {
+        return v1.toString().compareTo(v2.toString());
+      }
     }
   }
 
@@ -2751,8 +2698,7 @@
    * @param exceptions
    *          A list of exceptions.
    * @throws E
-   *           The first element of the provided list (if the list is not
-   *           empty).
+   *           The first element of the provided list (if the list is not empty).
    */
   public static <E extends Exception> void throwFirstFrom(List<? extends E> exceptions) throws E
   {
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 9b8f4ca..82e2889 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
@@ -65,7 +65,6 @@
 import java.util.concurrent.atomic.AtomicReference;
 
 import javax.naming.NamingException;
-import javax.net.ssl.KeyManager;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLHandshakeException;
 import javax.net.ssl.TrustManager;
@@ -1103,24 +1102,17 @@
   {
     // Interact with the user though the console to get
     // LDAP connection information
-    String hostName = getHostNameForLdapUrl(ci.getHostName());
-    int portNumber = ci.getPortNumber();
-    HostPort hostPort = new HostPort(hostName, portNumber);
-    String bindDN = ci.getBindDN();
-    String bindPassword = ci.getBindPassword();
-    TrustManager trustManager = ci.getTrustManager();
-    KeyManager keyManager = ci.getKeyManager();
+    final String hostName = getHostNameForLdapUrl(ci.getHostName());
+    final int portNumber = ci.getPortNumber();
+    final HostPort hostPort = new HostPort(hostName, portNumber);
 
-    ConnectionWrapper conn;
     if (ci.useSSL())
     {
       while (true)
       {
         try
         {
-          conn = new ConnectionWrapper(
-              hostPort, LDAPS, bindDN, bindPassword, ci.getConnectTimeout(), trustManager, keyManager);
-          break;
+          return newConnectionWrapper(ci, LDAPS, ci.getConnectTimeout());
         }
         catch (NamingException e)
         {
@@ -1129,13 +1121,10 @@
             OpendsCertificateException oce = getCertificateRootException(e);
             if (oce != null)
             {
-              String authType = getAuthType(trustManager);
+              String authType = getAuthType(ci.getTrustManager());
               if (ci.checkServerCertificate(oce.getChain(), authType, hostName))
               {
-                // If the certificate is trusted, update the trust manager.
-                trustManager = ci.getTrustManager();
-
-                // Try to connect again.
+                // User trusts the certificate, try to connect again.
                 continue;
               }
               else
@@ -1175,10 +1164,7 @@
       {
         try
         {
-          conn = new ConnectionWrapper(
-              hostPort, START_TLS, bindDN, bindPassword,
-              CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, trustManager, keyManager);
-          return conn;
+          return newConnectionWrapper(ci, START_TLS, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT);
         }
         catch (NamingException e)
         {
@@ -1191,13 +1177,10 @@
           {
             throw failedToConnect(hostName, portNumber);
           }
-          String authType = getAuthType(trustManager);
+          String authType = getAuthType(ci.getTrustManager());
           if (ci.checkServerCertificate(oce.getChain(), authType, hostName))
           {
-            // If the certificate is trusted, update the trust manager.
-            trustManager = ci.getTrustManager();
-
-            // Try to connect again.
+            // User trusts the certificate, try to connect again.
             continue;
           }
           else
@@ -1210,21 +1193,25 @@
     }
     else
     {
-      while (true)
+      try
       {
-        try
-        {
-          conn = new ConnectionWrapper(
-              hostPort, LDAP, bindDN, bindPassword, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT, null);
-          return conn;
-        }
-        catch (NamingException e)
-        {
-          throw failedToConnect(hostName, portNumber);
-        }
+        return newConnectionWrapper(ci, LDAP, CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT);
+      }
+      catch (NamingException e)
+      {
+        throw failedToConnect(hostName, portNumber);
       }
     }
-    return conn;
+  }
+
+  private ConnectionWrapper newConnectionWrapper(
+      LDAPConnectionConsoleInteraction ci, Type connType, int connectTimeout) throws NamingException
+  {
+    String hostName = getHostNameForLdapUrl(ci.getHostName());
+    int portNumber = ci.getPortNumber();
+    HostPort hostPort = new HostPort(hostName, portNumber);
+    return new ConnectionWrapper(hostPort, connType, ci.getBindDN(), ci.getBindPassword(),
+        connectTimeout, ci.getTrustManager(), ci.getKeyManager());
   }
 
   private String getAuthType(TrustManager trustManager)
@@ -3967,8 +3954,8 @@
     {
       errorMessages.add(getMessageForException(e, server.getHostPort().toString()));
       logger.error(LocalizableMessage.raw("Error when creating connection for:" + server.getHostPort()));
+      return null;
     }
-    return null;
   }
 
   /**

--
Gitblit v1.10.0