From 3d352ae91e3e7e6cd5c2ab96f01a6b38a2c5a253 Mon Sep 17 00:00:00 2001
From: Jean-Noel Rouvignac <jean-noel.rouvignac@forgerock.com>
Date: Wed, 29 Oct 2014 08:48:23 +0000
Subject: [PATCH] Code cleanup.

---
 opendj-sdk/opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/util/Utilities.java        |  309 +++++---------
 opendj-sdk/opendj3-server-dev/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java |  927 ++++++++++++++++++-------------------------
 2 files changed, 506 insertions(+), 730 deletions(-)

diff --git a/opendj-sdk/opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/util/Utilities.java b/opendj-sdk/opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/util/Utilities.java
index b89e418..c1d3cfb 100644
--- a/opendj-sdk/opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/util/Utilities.java
+++ b/opendj-sdk/opendj3-server-dev/src/guitools/org/opends/guitools/controlpanel/util/Utilities.java
@@ -142,14 +142,19 @@
   private static File rootDirectory;
   private static File instanceRootDirectory;
 
-  private static String[] attrsToObfuscate =
-  {ServerConstants.ATTR_USER_PASSWORD};
+  private static final String HTML_SPACE = "&nbsp;";
+  private static final String[] attrsToObfuscate = { ServerConstants.ATTR_USER_PASSWORD };
+  private static final String[] passwordSyntaxOIDs = { SchemaConstants.SYNTAX_USER_PASSWORD_OID };
+  private static final String[] binarySyntaxOIDs = {
+    SchemaConstants.SYNTAX_BINARY_OID,
+    SchemaConstants.SYNTAX_JPEG_OID,
+    SchemaConstants.SYNTAX_CERTIFICATE_OID,
+    SchemaConstants.SYNTAX_OCTET_STRING_OID
+  };
 
   private static ImageIcon warningIcon;
-
   private static ImageIcon requiredIcon;
 
-
   private static LocalizableMessage NO_VALUE_SET =
     INFO_CTRL_PANEL_NO_MONITORING_VALUE.get();
   private static LocalizableMessage NOT_IMPLEMENTED =
@@ -194,23 +199,18 @@
    */
   public static boolean mustObfuscate(String attrName, Schema schema)
   {
-    boolean toObfuscate = false;
-    if (schema == null)
+    if (schema != null)
     {
-      for (String attr : attrsToObfuscate)
+      return hasPasswordSyntax(attrName, schema);
+    }
+    for (String attr : attrsToObfuscate)
+    {
+      if (attr.equalsIgnoreCase(attrName))
       {
-        if (attr.equalsIgnoreCase(attrName))
-        {
-          toObfuscate = true;
-          break;
-        }
+        return true;
       }
     }
-    else
-    {
-      toObfuscate = hasPasswordSyntax(attrName, schema);
-    }
-    return toObfuscate;
+    return false;
   }
 
   /**
@@ -768,14 +768,13 @@
    */
   public static void setBorder(JComponent comp, Border border)
   {
-    if (comp.getBorder() == null)
+    if (comp.getBorder() != null)
     {
-      comp.setBorder(border);
+      comp.setBorder(BorderFactory.createCompoundBorder(comp.getBorder(), border));
     }
     else
     {
-      comp.setBorder(BorderFactory.createCompoundBorder(comp.getBorder(),
-          border));
+      comp.setBorder(border);
     }
   }
 
@@ -838,7 +837,7 @@
         }
         Component comp = renderer.getTableCellRendererComponent(table,
             table.getModel().getColumnName(col), false, false, 0, col);
-        int colHeight = comp.getPreferredSize().height + (2 * verticalMargin);
+        int colHeight = comp.getPreferredSize().height + 2 * verticalMargin;
         if (colHeight > screenSize.height)
         {
           // There are some issues on Mac OS and sometimes the preferred size
@@ -855,7 +854,7 @@
       TableColumn tcol = table.getColumnModel().getColumn(col);
       TableCellRenderer renderer = tcol.getHeaderRenderer();
 
-      if ((renderer == null) && (header != null))
+      if (renderer == null && header != null)
       {
         renderer = header.getDefaultRenderer();
       }
@@ -864,8 +863,7 @@
       {
         Component comp = renderer.getTableCellRendererComponent(table,
             table.getModel().getColumnName(col), false, false, 0, col);
-        colMaxWidth = comp.getPreferredSize().width  + (2 * horizontalMargin) +
-        8;
+        colMaxWidth = comp.getPreferredSize().width  + 2 * horizontalMargin + 8;
       }
 
       if (colMaxWidth > screenSize.width)
@@ -877,7 +875,7 @@
       {
         renderer = table.getCellRenderer(row, col);
         Component comp = table.prepareRenderer(renderer, row, col);
-        int colWidth = comp.getPreferredSize().width + (2 * horizontalMargin);
+        int colWidth = comp.getPreferredSize().width + 2 * horizontalMargin;
         colMaxWidth = Math.max(colMaxWidth, colWidth);
       }
       tcol.setPreferredWidth(colMaxWidth);
@@ -887,9 +885,7 @@
 
     if (header != null && header.isVisible())
     {
-      header.setPreferredSize(new Dimension(
-          headerMaxWidth,
-          headerMaxHeight));
+      header.setPreferredSize(new Dimension(headerMaxWidth, headerMaxHeight));
     }
 
 
@@ -901,7 +897,7 @@
         TableCellRenderer renderer = table.getCellRenderer(row, col);
         Component comp = renderer.getTableCellRendererComponent(table,
             table.getModel().getValueAt(row, col), false, false, row, col);
-        int colHeight = comp.getPreferredSize().height + (2 * verticalMargin);
+        int colHeight = comp.getPreferredSize().height + 2 * verticalMargin;
         if (colHeight > screenSize.height)
         {
           colHeight = 0;
@@ -937,12 +933,7 @@
    */
   public static String applyFont(CharSequence html, Font font)
   {
-    StringBuilder buf = new StringBuilder();
-
-    buf.append("<span style=\"").append(getFontStyle(font)).append("\">")
-        .append(html).append("</span>");
-
-    return buf.toString();
+    return "<span style=\"" + getFontStyle(font) + "\">" + html + "</span>";
   }
 
 
@@ -986,19 +977,15 @@
       LocalizableMessage description, boolean useFast)
   {
     ImageIcon icon = new ImageIcon(bytes, description.toString());
-    if ((maxHeight > icon.getIconHeight()) || (icon.getIconHeight() <= 0))
+    if (maxHeight > icon.getIconHeight() || icon.getIconHeight() <= 0)
     {
       return icon;
     }
-    else
-    {
-      int newHeight = maxHeight;
-      int newWidth = (newHeight * icon.getIconWidth()) / icon.getIconHeight();
-      int algo = useFast ? Image.SCALE_FAST : Image.SCALE_SMOOTH;
-      Image scaledImage = icon.getImage().getScaledInstance(newWidth, newHeight,
-          algo);
-      return new ImageIcon(scaledImage);
-    }
+    int newHeight = maxHeight;
+    int newWidth = (newHeight * icon.getIconWidth()) / icon.getIconHeight();
+    int algo = useFast ? Image.SCALE_FAST : Image.SCALE_SMOOTH;
+    Image scaledImage = icon.getImage().getScaledInstance(newWidth, newHeight, algo);
+    return new ImageIcon(scaledImage);
   }
 
   /**
@@ -1023,7 +1010,7 @@
     JEditorPane pane2 = makeHtmlPane(wrappedText, font);
     pane.setPreferredSize(pane2.getPreferredSize());
     JFrame frame = getFrame(pane);
-    if ((frame != null) && frame.isVisible())
+    if (frame != null && frame.isVisible())
     {
       frame.getRootPane().revalidate();
       frame.getRootPane().repaint();
@@ -1035,7 +1022,7 @@
    * @param s string to strip
    * @return resulting string
    */
-  static public String stripHtmlToSingleLine(String s) {
+  public static String stripHtmlToSingleLine(String s) {
     String o = null;
     if (s != null) {
       s = s.replaceAll("<br>", " ");
@@ -1047,12 +1034,10 @@
       // '<tag attr="1 > 0">'. See test class for cases that
       // might cause problems.
       o = s.replaceAll("\\<.*?\\>","");
-
     }
     return o;
   }
 
-  private final static String HTML_SPACE = "&nbsp;";
   /**
    * Wraps the contents of the provided message using the specified number of
    * columns.
@@ -1256,16 +1241,16 @@
   {
     comp.setLocationRelativeTo(ref);
     // Apply the golden mean
-    if ((ref != null) && ref.isVisible())
+    if (ref != null && ref.isVisible())
     {
       int refY = ref.getY();
       int refHeight = ref.getHeight();
       int compHeight = comp.getPreferredSize().height;
 
-      int newY = refY + (int) ((refHeight * 0.3819) - (compHeight * 0.5));
+      int newY = refY + (int) (refHeight * 0.3819 - compHeight * 0.5);
       // Check that the new window will be fully visible
       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
-      if ((newY > 0) && (screenSize.height > newY + compHeight))
+      if (newY > 0 && screenSize.height > newY + compHeight)
       {
         comp.setLocation(comp.getX(), newY);
       }
@@ -1282,7 +1267,7 @@
   public static JFrame getFrame(Component comp)
   {
     Component parent = comp;
-    while ((parent != null) && !(parent instanceof JFrame))
+    while (parent != null && !(parent instanceof JFrame))
     {
       parent = parent.getParent();
     }
@@ -1324,9 +1309,10 @@
       int pos = 0;
       for (int i = 0; i < stringBytes.length; i++)
       {
-        if ((stringBytes[i] == '\\') && (i + 2 < stringBytes.length) &&
-            StaticUtils.isHexDigit(stringBytes[i+1]) &&
-            StaticUtils.isHexDigit(stringBytes[i+2]))
+        if (stringBytes[i] == '\\'
+                && i + 2 < stringBytes.length
+                && StaticUtils.isHexDigit(stringBytes[i+1])
+                && StaticUtils.isHexDigit(stringBytes[i+2]))
         {
           // Convert hex-encoded UTF-8 to 16-bit chars.
           byte b;
@@ -1534,9 +1520,8 @@
     return o;
   }
 
-  /* The pattern for control characters */
-  private static Pattern cntrl_pattern =
-      Pattern.compile("\\p{Cntrl}", Pattern.MULTILINE);
+  /** The pattern for control characters. */
+  private static Pattern cntrl_pattern = Pattern.compile("\\p{Cntrl}", Pattern.MULTILINE);
 
   /**
    * Checks if a string contains control characters.
@@ -1587,10 +1572,9 @@
   public static Name getJNDIName(String dn) throws InvalidNameException
   {
     Name name = new CompositeName();
-    if ((dn != null) && (dn.length() > 0)) {
+    if (dn != null && dn.length() > 0) {
       name.add(dn);
     }
-
     return name;
   }
 
@@ -1950,29 +1934,24 @@
    */
   public static boolean isServerRunning(File serverRootDirectory)
   {
-    boolean isServerRunning;
-    String lockFileName = ServerConstants.SERVER_LOCK_FILE_NAME +
-    ServerConstants.LOCK_FILE_SUFFIX;
+    String lockFileName = ServerConstants.SERVER_LOCK_FILE_NAME + ServerConstants.LOCK_FILE_SUFFIX;
     String lockPathRelative = Installation.LOCKS_PATH_RELATIVE;
     File locksPath = new File(serverRootDirectory, lockPathRelative);
     String lockFile = new File(locksPath, lockFileName).getAbsolutePath();
     StringBuilder failureReason = new StringBuilder();
     try {
-      if (LockFileManager.acquireExclusiveLock(lockFile,
-              failureReason)) {
-        LockFileManager.releaseLock(lockFile,
-                failureReason);
-        isServerRunning = false;
-      } else {
-        isServerRunning = true;
+      if (LockFileManager.acquireExclusiveLock(lockFile, failureReason))
+      {
+        LockFileManager.releaseLock(lockFile, failureReason);
+        return false;
       }
+      return true;
     }
     catch (Throwable t) {
       // Assume that if we cannot acquire the lock file the
       // server is running.
-      isServerRunning = true;
+      return true;
     }
-    return isServerRunning;
   }
 
   private static final String VALID_SCHEMA_SYNTAX =
@@ -1987,24 +1966,22 @@
    */
   public static boolean isValidObjectclassName(String s)
   {
-    boolean isValid;
-    if ((s == null) || (s.length() == 0))
+    if (s == null || s.length() == 0)
     {
-      isValid = false;
-    } else {
-      isValid = true;
-      StringCharacterIterator iter =
-        new StringCharacterIterator(s,  0);
-      for (char c = iter.first();
-      (c != CharacterIterator.DONE) && isValid;
-      c = iter.next()) {
-        if (VALID_SCHEMA_SYNTAX.indexOf(Character.toLowerCase(c)) == -1)
-        {
-          isValid = false;
-        }
-      }
+      return false;
     }
-    return isValid;
+
+    final StringCharacterIterator iter = new StringCharacterIterator(s, 0);
+    char c = iter.first();
+    while (c != CharacterIterator.DONE)
+    {
+      if (VALID_SCHEMA_SYNTAX.indexOf(Character.toLowerCase(c)) == -1)
+      {
+        return false;
+      }
+      c = iter.next();
+    }
+    return true;
   }
 
   /**
@@ -2041,24 +2018,24 @@
     return INFO_CTRL_PANEL_VLV_INDEX_CELL.get(index.getName()).toString();
   }
 
-  private final static String[] standardSchemaFileNames =
+  private static final String[] standardSchemaFileNames =
   {
       "00-core.ldif", "01-pwpolicy.ldif", "03-changelog.ldif",
       "03-uddiv3.ldif", "05-solaris.ldif"
   };
 
-  private final static String[] configurationSchemaOrigins =
+  private static final String[] configurationSchemaOrigins =
   {
       "OpenDJ Directory Server", "OpenDS Directory Server",
       "Sun Directory Server", "Microsoft Active Directory"
   };
 
-  private final static String[] standardSchemaOrigins =
+  private static final String[] standardSchemaOrigins =
   {
       "Sun Java System Directory Server", "Solaris Specific", "X.501"
   };
 
-  private final static String[] configurationSchemaFileNames =
+  private static final String[] configurationSchemaFileNames =
   {
       "02-config.ldif", "06-compat.ldif"
   };
@@ -2072,30 +2049,20 @@
    */
   public static boolean isStandard(SchemaFileElement fileElement)
   {
-    boolean isStandard = false;
-    String fileName = getSchemaFile(fileElement);
+    final String fileName = getSchemaFile(fileElement);
     if (fileName != null)
     {
-      isStandard = contains(standardSchemaFileNames, fileName);
-      if (!isStandard)
-      {
-        isStandard = fileName.toLowerCase().indexOf("-rfc") != -1;
-      }
+      return contains(standardSchemaFileNames, fileName) || fileName.toLowerCase().indexOf("-rfc") != -1;
     }
     else if (fileElement instanceof CommonSchemaElements)
     {
       String xOrigin = getOrigin(fileElement);
       if (xOrigin != null)
       {
-        isStandard = contains(standardSchemaOrigins, xOrigin);
-        if (!isStandard)
-        {
-          isStandard = xOrigin.startsWith("RFC ") ||
-          xOrigin.startsWith("draft-");
-        }
+        return contains(standardSchemaOrigins, xOrigin) || xOrigin.startsWith("RFC ") || xOrigin.startsWith("draft-");
       }
     }
-    return isStandard;
+    return false;
   }
 
   /**
@@ -2107,21 +2074,20 @@
    */
   public static boolean isConfiguration(SchemaFileElement fileElement)
   {
-    boolean isConfiguration = false;
     String fileName = getSchemaFile(fileElement);
     if (fileName != null)
     {
-      isConfiguration = contains(configurationSchemaFileNames, fileName);
+      return contains(configurationSchemaFileNames, fileName);
     }
     else if (fileElement instanceof CommonSchemaElements)
     {
       String xOrigin = getOrigin(fileElement);
       if (xOrigin != null)
       {
-        isConfiguration = contains(configurationSchemaOrigins, xOrigin);
+        return contains(configurationSchemaOrigins, xOrigin);
       }
     }
-    return isConfiguration;
+    return false;
   }
 
   private static boolean contains(String[] names, String toFind)
@@ -2154,28 +2120,15 @@
    */
   public static String getSyntaxText(AttributeSyntax<?> syntax)
   {
-    String returnValue;
     String syntaxName = syntax.getName();
     String syntaxOID = syntax.getOID();
-    if (syntaxName == null)
+    if (syntaxName != null)
     {
-      returnValue = syntaxOID;
+      return syntaxName + " - " + syntaxOID;
     }
-    else
-    {
-      returnValue = syntaxName+" - "+syntaxOID;
-    }
-    return returnValue;
+    return syntaxOID;
   }
 
-  private final static String[] binarySyntaxOIDs =
-  {
-    SchemaConstants.SYNTAX_BINARY_OID,
-    SchemaConstants.SYNTAX_JPEG_OID,
-    SchemaConstants.SYNTAX_CERTIFICATE_OID,
-    SchemaConstants.SYNTAX_OCTET_STRING_OID
-  };
-
   /**
    * Returns <CODE>true</CODE> if the provided attribute has image syntax and
    * <CODE>false</CODE> otherwise.
@@ -2186,23 +2139,22 @@
    */
   public static boolean hasImageSyntax(String attrName, Schema schema)
   {
-    boolean hasImageSyntax = false;
     attrName = Utilities.getAttributeNameWithoutOptions(attrName).toLowerCase();
     if ("photo".equals(attrName))
     {
-      hasImageSyntax = true;
+      return true;
     }
     // Check all the attributes that we consider binaries.
-    if (!hasImageSyntax && (schema != null))
+    if (schema != null)
     {
       AttributeType attr = schema.getAttributeType(attrName);
       if (attr != null)
       {
         String syntaxOID = attr.getSyntax().getOID();
-        hasImageSyntax = SchemaConstants.SYNTAX_JPEG_OID.equals(syntaxOID);
+        return SchemaConstants.SYNTAX_JPEG_OID.equals(syntaxOID);
       }
     }
-    return hasImageSyntax;
+    return false;
   }
 
   /**
@@ -2215,34 +2167,10 @@
    */
   public static boolean hasBinarySyntax(String attrName, Schema schema)
   {
-    boolean hasBinarySyntax = attrName.toLowerCase().indexOf(";binary") != -1;
-    // Check all the attributes that we consider binaries.
-    if (!hasBinarySyntax && (schema != null))
-    {
-      attrName =
-        Utilities.getAttributeNameWithoutOptions(attrName).toLowerCase();
-      AttributeType attr = schema.getAttributeType(attrName);
-      if (attr != null)
-      {
-        String syntaxOID = attr.getSyntax().getOID();
-        for (String oid : binarySyntaxOIDs)
-        {
-          if (oid.equals(syntaxOID))
-          {
-            hasBinarySyntax = true;
-            break;
-          }
-        }
-      }
-    }
-    return hasBinarySyntax;
+    return attrName.toLowerCase().contains(";binary")
+        || hasAnySyntax(attrName, schema, binarySyntaxOIDs);
   }
 
-  private final static String[] passwordSyntaxOIDs =
-  {
-    SchemaConstants.SYNTAX_USER_PASSWORD_OID
-  };
-
   /**
    * Returns <CODE>true</CODE> if the provided attribute has password syntax and
    * <CODE>false</CODE> otherwise.
@@ -2253,27 +2181,21 @@
    */
   public static boolean hasPasswordSyntax(String attrName, Schema schema)
   {
-    boolean hasPasswordSyntax = false;
-    // Check all the attributes that we consider binaries.
+    return hasAnySyntax(attrName, schema, passwordSyntaxOIDs);
+  }
+
+  private static boolean hasAnySyntax(String attrName, Schema schema, String[] oids)
+  {
     if (schema != null)
     {
-      attrName =
-        Utilities.getAttributeNameWithoutOptions(attrName).toLowerCase();
+      attrName = Utilities.getAttributeNameWithoutOptions(attrName).toLowerCase();
       AttributeType attr = schema.getAttributeType(attrName);
       if (attr != null)
       {
-        String syntaxOID = attr.getSyntax().getOID();
-        for (String oid : passwordSyntaxOIDs)
-        {
-          if (oid.equals(syntaxOID))
-          {
-            hasPasswordSyntax = true;
-            break;
-          }
-        }
+        return contains(oids, attr.getSyntax().getOID());
       }
     }
-    return hasPasswordSyntax;
+    return false;
   }
 
   /**
@@ -2395,14 +2317,10 @@
   public static void checkCanReadConfig(InitialLdapContext ctx)
   throws NamingException
   {
-    /*
-     * Search for the config to check that it is the directory manager.
-     */
+    // 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 });
+    searchControls.setSearchScope(SearchControls.OBJECT_SCOPE);
+    searchControls.setReturningAttributes(new String[] { SchemaConstants.NO_ATTRIBUTES });
     NamingEnumeration<SearchResult> sr =
       ctx.search("cn=config", "objectclass=*", searchControls);
     try
@@ -2453,8 +2371,7 @@
     if (confEntry != null)
     {
       // Copy the values to avoid problems with this recursive method.
-      ArrayList<DN> childDNs = new ArrayList<DN>();
-      childDNs.addAll(confEntry.getChildren().keySet());
+      ArrayList<DN> childDNs = new ArrayList<DN>(confEntry.getChildren().keySet());
       for (DN childDN : childDNs)
       {
         deleteConfigSubtree(confHandler, childDN);
@@ -2531,7 +2448,7 @@
   {
     JScrollPane scroll = null;
     Container parent = comp.getParent();
-    while ((scroll == null) && (parent != null))
+    while (scroll == null && parent != null)
     {
       if (parent instanceof JScrollPane)
       {
@@ -2661,7 +2578,7 @@
     {
       Long l = Long.parseLong(monitoringValue.toString());
       long mb = l / (1024 * 1024);
-      long kbs = (l - (mb * 1024 * 1024)) / 1024;
+      long kbs = (l - mb * 1024 * 1024) / 1024;
       return INFO_CTRL_PANEL_MEMORY_VALUE.get(mb, kbs).toString();
     }
     return monitoringValue.toString();
@@ -2679,9 +2596,8 @@
       CustomSearchResult monitoringEntry)
   {
     Object monitoringValue = Utilities.getFirstMonitoringValue(
-        monitoringEntry,
-        attr.getAttributeName());
-    if (attr.isNumeric() && (monitoringValue != null))
+        monitoringEntry, attr.getAttributeName());
+    if (attr.isNumeric() && monitoringValue != null)
     {
       try
       {
@@ -2735,15 +2651,15 @@
       int i = 0;
       for (Object newElement : newElements)
       {
-        if (comparator == null)
-        {
-          changed = !newElement.equals(model.getElementAt(i));
-        }
-        else
+        if (comparator != null)
         {
           changed =
             comparator.compare(newElement, model.getElementAt(i)) != 0;
         }
+        else
+        {
+          changed = !newElement.equals(model.getElementAt(i));
+        }
         if (changed)
         {
           break;
@@ -2780,13 +2696,10 @@
         for (int i=0; i<model.getSize(); i++)
         {
           Object o = model.getElementAt(i);
-          if (o instanceof CategorizedComboBoxElement)
+          if (o instanceof CategorizedComboBoxElement
+              && ((CategorizedComboBoxElement)o).getType() == CategorizedComboBoxElement.Type.CATEGORY)
           {
-            if (((CategorizedComboBoxElement)o).getType() ==
-              CategorizedComboBoxElement.Type.CATEGORY)
-            {
-              continue;
-            }
+            continue;
           }
           model.setSelectedItem(o);
           break;
diff --git a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java
index 18245dd..af3ffb9 100644
--- a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java
+++ b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/tools/dsreplication/ReplicationCliMain.java
@@ -49,6 +49,7 @@
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicReference;
 
 import javax.naming.NameAlreadyBoundException;
 import javax.naming.NameNotFoundException;
@@ -358,9 +359,7 @@
     }
     catch (ArgumentException ae)
     {
-      LocalizableMessage message =
-        ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage());
-      println(message);
+      println(ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
       logger.error(LocalizableMessage.raw("Complete error stack:"), ae);
       returnValue = CANNOT_INITIALIZE_ARGS;
     }
@@ -383,9 +382,7 @@
       }
       catch (ArgumentException ae)
       {
-        LocalizableMessage message = ERR_ERROR_PARSING_ARGS.get(ae.getMessage());
-
-        println(message);
+        println(ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
         println();
         println(LocalizableMessage.raw(argParser.getUsage()));
         logger.error(LocalizableMessage.raw("Complete error stack:"), ae);
@@ -1507,16 +1504,7 @@
         if (helper.isDone(state) || helper.isStoppedByError(state))
         {
           isOver = true;
-          LocalizableMessage errorMsg;
-          String server = getHostPort(ctx);
-          if (lastLogMsg != null)
-          {
-            errorMsg = INFO_ERROR_DURING_PURGE_HISTORICAL_LOG.get(lastLogMsg, state, server);
-          }
-          else
-          {
-            errorMsg = INFO_ERROR_DURING_PURGE_HISTORICAL_NO_LOG.get(state, server);
-          }
+          LocalizableMessage errorMsg = getPurgeErrorMsg(lastLogMsg, state, ctx);
 
           if (helper.isCompletedWithErrors(state))
           {
@@ -1551,6 +1539,16 @@
     return returnCode;
   }
 
+  private LocalizableMessage getPurgeErrorMsg(String lastLogMsg, String state, InitialLdapContext ctx)
+  {
+    String server = getHostPort(ctx);
+    if (lastLogMsg != null)
+    {
+      return INFO_ERROR_DURING_PURGE_HISTORICAL_LOG.get(lastLogMsg, state, server);
+    }
+    return INFO_ERROR_DURING_PURGE_HISTORICAL_NO_LOG.get(state, server);
+  }
+
   /**
    * Checks that historical can actually be purged in the provided baseDNs
    * for the server.
@@ -1764,114 +1762,26 @@
    */
   private boolean promptIfRequired(PurgeHistoricalUserData uData)
   {
-    boolean cancelled = false;
-    boolean onlineSet = false;
-
-    boolean firstTry = true;
-    Boolean serverRunning = null;
-
     InitialLdapContext ctx = null;
-    while (!cancelled && !onlineSet)
+    try
     {
-      boolean promptForConnection = false;
-      if (argParser.connectionArgumentsPresent() && firstTry)
+      ctx = getInitialLdapContext(uData);
+      if (ctx == null)
       {
-        promptForConnection = true;
+        return false;
       }
-      else
-      {
-        if (serverRunning == null)
-        {
-          serverRunning = Utilities.isServerRunning(
-              Installation.getLocal().getInstanceDirectory());
-        }
-        if (!serverRunning)
-        {
-          try
-          {
-            println();
-            promptForConnection =
-              !askConfirmation(
-                  INFO_REPLICATION_PURGE_HISTORICAL_LOCAL_PROMPT.get(),
-                  true, logger);
-          }
-          catch (ClientException ce)
-          {
-            println(ce.getMessageObject());
-            cancelled = true;
-          }
-        }
-        else
-        {
-          promptForConnection = true;
-        }
-      }
-      if (promptForConnection)
-      {
-        try
-        {
-          ci.run();
-          String host = ci.getHostName();
-          int port = ci.getPortNumber();
-          String adminUid = ci.getAdministratorUID();
-          String adminPwd = ci.getBindPassword();
 
-          ctx = createInitialLdapContextInteracting(ci);
-          if (ctx == null)
-          {
-            cancelled = true;
-          }
-          else
-          {
-            uData.setOnline(true);
-            uData.setAdminUid(adminUid);
-            uData.setAdminPwd(adminPwd);
-            uData.setHostName(host);
-            uData.setPort(port);
-            onlineSet = true;
-          }
-        }
-        catch (ClientException ce)
-        {
-          logger.warn(LocalizableMessage.raw("Client exception "+ce));
-          println();
-          println(ce.getMessageObject());
-          println();
-          ci.resetConnectionArguments();
-        }
-        catch (ArgumentException ae)
-        {
-          logger.warn(LocalizableMessage.raw("Argument exception "+ae));
-          println();
-          println(ae.getMessageObject());
-          println();
-          cancelled = true;
-        }
-      }
-      else
-      {
-        uData.setOnline(false);
-        onlineSet = true;
-      }
-      firstTry = false;
-    }
-
-    if (!cancelled)
-    {
-      int maximumDuration = argParser.getMaximumDuration();
       /* Prompt for maximum duration */
+      int maximumDuration = argParser.getMaximumDuration();
       if (!argParser.maximumDurationArg.isPresent())
       {
         println();
-        maximumDuration = askInteger(
-            INFO_REPLICATION_PURGE_HISTORICAL_MAXIMUM_DURATION_PROMPT.get(),
+        maximumDuration = askInteger(INFO_REPLICATION_PURGE_HISTORICAL_MAXIMUM_DURATION_PROMPT.get(),
             argParser.getDefaultMaximumDuration(), logger);
       }
       uData.setMaximumDuration(maximumDuration);
-    }
 
-    if (!cancelled)
-    {
+
       LinkedList<String> suffixes = argParser.getBaseDNs();
       if (uData.isOnline())
       {
@@ -1881,31 +1791,110 @@
       {
         checkSuffixesForLocalPurgeHistorical(suffixes, true);
       }
-      cancelled = suffixes.isEmpty();
+      if (suffixes.isEmpty())
+      {
+        return false;
+      }
       uData.setBaseDNs(suffixes);
+
+
+      if (uData.isOnline())
+      {
+        List<? extends TaskEntry> taskEntries = getAvailableTaskEntries(ctx);
+
+        TaskScheduleInteraction interaction =
+            new TaskScheduleInteraction(uData.getTaskSchedule(), argParser.taskArgs, this,
+                INFO_PURGE_HISTORICAL_TASK_NAME.get());
+        interaction.setFormatter(formatter);
+        interaction.setTaskEntries(taskEntries);
+        try
+        {
+          interaction.run();
+        }
+        catch (ClientException ce)
+        {
+          println(ce.getMessageObject());
+          return false;
+        }
+      }
+      return true;
     }
-
-    if (uData.isOnline() && !cancelled)
+    finally
     {
-      List<? extends TaskEntry> taskEntries = getAvailableTaskEntries(ctx);
+      close(ctx);
+    }
+  }
 
-      TaskScheduleInteraction interaction =
-        new TaskScheduleInteraction(uData.getTaskSchedule(), argParser.taskArgs,
-            this, INFO_PURGE_HISTORICAL_TASK_NAME.get());
-      interaction.setFormatter(formatter);
-      interaction.setTaskEntries(taskEntries);
+  private InitialLdapContext getInitialLdapContext(PurgeHistoricalUserData uData)
+  {
+    boolean firstTry = true;
+    Boolean serverRunning = null;
+
+    while (true)
+    {
+      boolean promptForConnection = firstTry && argParser.connectionArgumentsPresent();
+      if (!promptForConnection)
+      {
+        if (serverRunning == null)
+        {
+          serverRunning = Utilities.isServerRunning(Installation.getLocal().getInstanceDirectory());
+        }
+
+        if (!serverRunning)
+        {
+          try
+          {
+            println();
+            promptForConnection = !askConfirmation(
+                INFO_REPLICATION_PURGE_HISTORICAL_LOCAL_PROMPT.get(), true, logger);
+          }
+          catch (ClientException ce)
+          {
+            println(ce.getMessageObject());
+          }
+
+          if (!promptForConnection)
+          {
+            uData.setOnline(false);
+            return null;
+          }
+        }
+      }
+
+
       try
       {
-        interaction.run();
+        ci.run();
+
+        InitialLdapContext ctx = createInitialLdapContextInteracting(ci);
+        if (ctx != null)
+        {
+          uData.setOnline(true);
+          uData.setHostName(ci.getHostName());
+          uData.setPort(ci.getPortNumber());
+          uData.setAdminUid(ci.getAdministratorUID());
+          uData.setAdminPwd(ci.getBindPassword());
+        }
+        return ctx;
       }
       catch (ClientException ce)
       {
+        logger.warn(LocalizableMessage.raw("Client exception " + ce));
+        println();
         println(ce.getMessageObject());
-        cancelled = true;
+        println();
+        ci.resetConnectionArguments();
       }
+      catch (ArgumentException ae)
+      {
+        logger.warn(LocalizableMessage.raw("Argument exception " + ae));
+        println();
+        println(ae.getMessageObject());
+        println();
+        return null;
+      }
+      firstTry = false;
     }
-    close(ctx);
-    return !cancelled;
   }
 
   private List<? extends TaskEntry> getAvailableTaskEntries(
@@ -1985,8 +1974,7 @@
     {
       try
       {
-        ci.setHeadingMessage(
-            INFO_REPLICATION_ENABLE_HOST1_CONNECTION_PARAMETERS.get());
+        ci.setHeadingMessage(INFO_REPLICATION_ENABLE_HOST1_CONNECTION_PARAMETERS.get());
         ci.run();
         host1 = ci.getHostName();
         port1 = ci.getPortNumber();
@@ -2005,7 +1993,6 @@
         pwd1 = ci.getBindPassword();
 
         ctx1 = createInitialLdapContextInteracting(ci);
-
         if (ctx1 == null)
         {
           cancelled = true;
@@ -2057,9 +2044,9 @@
       }
 
       // Try to get the replication port for server 1 only if it is required.
-      if (!replicationServer1Configured
+      if (!cancelled
           && configureReplicationServer1
-          && !cancelled
+          && !replicationServer1Configured
           && argParser.advancedArg.isPresent()
           && configureReplicationDomain1)
       {
@@ -2078,8 +2065,8 @@
         }
       }
       if (!cancelled
-          && !replicationServer1Configured
-          && configureReplicationServer1)
+          && configureReplicationServer1
+          && !replicationServer1Configured)
       {
         boolean tryWithDefault = argParser.getReplicationPort1() != -1;
         while (replicationPort1 == -1)
@@ -2157,9 +2144,9 @@
       // eventually admin authentication data.
       if (!cancelled)
       {
-        InitialLdapContext[] aux = new InitialLdapContext[] {ctx1};
+        AtomicReference<InitialLdapContext> aux = new AtomicReference<InitialLdapContext>(ctx1);
         cancelled = !loadADSAndAcceptCertificates(aux, uData, true);
-        ctx1 = aux[0];
+        ctx1 = aux.get();
       }
       if (!cancelled)
       {
@@ -2233,8 +2220,7 @@
     {
       try
       {
-        ci.setHeadingMessage(
-            INFO_REPLICATION_ENABLE_HOST2_CONNECTION_PARAMETERS.get());
+        ci.setHeadingMessage(INFO_REPLICATION_ENABLE_HOST2_CONNECTION_PARAMETERS.get());
         ci.run();
         host2 = ci.getHostName();
         port2 = ci.getPortNumber();
@@ -2265,7 +2251,6 @@
         if (!error)
         {
           ctx2 = createInitialLdapContextInteracting(ci, true);
-
           if (ctx2 == null)
           {
             cancelled = true;
@@ -2332,8 +2317,9 @@
       }
 
       // Try to get the replication port for server 2 only if it is required.
-      if (!replicationServer2Configured && configureReplicationServer2 &&
-          !cancelled)
+      if (!cancelled
+          && configureReplicationServer2
+          && !replicationServer2Configured)
       {
         // Only ask if the replication domain will be configured (if not the
         // replication server MUST be configured).
@@ -2352,8 +2338,9 @@
             cancelled = true;
           }
         }
-        if (!cancelled &&
-            !replicationServer2Configured && configureReplicationServer2)
+        if (!cancelled
+            && configureReplicationServer2
+            && !replicationServer2Configured)
         {
           boolean tryWithDefault = argParser.getReplicationPort2() != -1;
           while (replicationPort2 == -1)
@@ -2439,9 +2426,9 @@
       // to load the ADS to ask the user to accept the certificates.
       if (!cancelled)
       {
-        InitialLdapContext[] aux = new InitialLdapContext[] {ctx2};
+        AtomicReference<InitialLdapContext> aux = new AtomicReference<InitialLdapContext>(ctx2);
         cancelled = !loadADSAndAcceptCertificates(aux, uData, false);
-        ctx2 = aux[0];
+        ctx2 = aux.get();
       }
       if (!cancelled)
       {
@@ -2510,15 +2497,11 @@
         {
           try
           {
-            adminPwdConfirm =
-                String
-                    .valueOf(readPassword(INFO_ADMINISTRATOR_PWD_CONFIRM_PROMPT
-                        .get()));
+            adminPwdConfirm = String.valueOf(readPassword(INFO_ADMINISTRATOR_PWD_CONFIRM_PROMPT.get()));
           }
           catch (ClientException ex)
           {
-            logger.warn(LocalizableMessage
-                .raw("Error reading input: " + ex, ex));
+            logger.warn(LocalizableMessage.raw("Error reading input: " + ex, ex));
           }
           println();
         }
@@ -2591,7 +2574,6 @@
         adminPwd = ci.getBindPassword();
 
         ctx = createInitialLdapContextInteracting(ci);
-
         if (ctx == null)
         {
           cancelled = true;
@@ -2630,9 +2612,9 @@
       // disableReplication(DisableReplicationUserData) method.  Here we have
       // to load the ADS to ask the user to accept the certificates and
       // eventually admin authentication data.
-      InitialLdapContext[] aux = new InitialLdapContext[] {ctx};
+      AtomicReference<InitialLdapContext> aux = new AtomicReference<InitialLdapContext>(ctx);
       cancelled = !loadADSAndAcceptCertificates(aux, uData, false);
-      ctx = aux[0];
+      ctx = aux.get();
     }
 
     boolean disableAll = argParser.disableAllArg.isPresent();
@@ -2776,94 +2758,46 @@
    */
   private boolean promptIfRequired(InitializeAllReplicationUserData uData)
   {
-    boolean cancelled = false;
-
-    String adminPwd = argParser.getBindPasswordAdmin();
-    String adminUid = argParser.getAdministratorUID();
-
-    String host = argParser.getHostNameToInitializeAll();
-    int port = argParser.getPortToInitializeAll();
-
-    /*
-     * Try to connect to the server.
-     */
     InitialLdapContext ctx = null;
-
-    while (ctx == null && !cancelled)
+    try
     {
-      try
+      ctx = getInitialLdapContext(uData);
+      if (ctx == null)
       {
-        ci.setHeadingMessage(
-            INFO_REPLICATION_INITIALIZE_SOURCE_CONNECTION_PARAMETERS.get());
-        ci.run();
-        host = ci.getHostName();
-        port = ci.getPortNumber();
-        adminUid = ci.getAdministratorUID();
-        adminPwd = ci.getBindPassword();
-
-        ctx = createInitialLdapContextInteracting(ci);
-
-        if (ctx == null)
-        {
-          cancelled = true;
-        }
+        return false;
       }
-      catch (ClientException ce)
-      {
-        logger.warn(LocalizableMessage.raw("Client exception "+ce));
-        println();
-        println(ce.getMessageObject());
-        println();
-        ci.resetConnectionArguments();
-      }
-      catch (ArgumentException ae)
-      {
-        logger.warn(LocalizableMessage.raw("Argument exception "+ae));
-        println();
-        println(ae.getMessageObject());
-        println();
-        cancelled = true;
-      }
-    }
-    if (!cancelled)
-    {
-      uData.setHostName(host);
-      uData.setPort(port);
-      uData.setAdminUid(adminUid);
-      uData.setAdminPwd(adminPwd);
-    }
 
-    if (!cancelled)
-    {
       LinkedList<String> suffixes = argParser.getBaseDNs();
       checkSuffixesForInitializeReplication(suffixes, ctx, true);
-      cancelled = suffixes.isEmpty();
-
+      if (suffixes.isEmpty())
+      {
+        return false;
+      }
       uData.setBaseDNs(suffixes);
-    }
 
-    if (!cancelled)
-    {
       // Ask for confirmation to initialize.
-      String hostPortSource = getHostPort(ctx);
-      LocalizableMessage msg;
-      if (initializeADS(uData.getBaseDNs()))
-      {
-        msg = INFO_REPLICATION_CONFIRM_INITIALIZE_ALL_ADS.get(
-            ADSContext.getAdministrationSuffixDN(), hostPortSource);
-      }
-      else
-      {
-        msg = INFO_REPLICATION_CONFIRM_INITIALIZE_ALL_GENERIC.get(hostPortSource);
-      }
-
       println();
-      cancelled = !askConfirmation(msg, true);
+      if (!askConfirmation(getPrompt(uData, ctx), true))
+      {
+        return false;
+      }
       println();
+      return true;
     }
+    finally
+    {
+      close(ctx);
+    }
+  }
 
-    close(ctx);
-    return !cancelled;
+  private LocalizableMessage getPrompt(InitializeAllReplicationUserData uData, InitialLdapContext ctx)
+  {
+    String hostPortSource = getHostPort(ctx);
+    if (initializeADS(uData.getBaseDNs()))
+    {
+      return INFO_REPLICATION_CONFIRM_INITIALIZE_ALL_ADS.get(ADSContext.getAdministrationSuffixDN(), hostPortSource);
+    }
+    return INFO_REPLICATION_CONFIRM_INITIALIZE_ALL_GENERIC.get(hostPortSource);
   }
 
   private boolean askConfirmation(final LocalizableMessage msg, final boolean defaultValue)
@@ -2890,39 +2824,55 @@
    */
   private boolean promptIfRequiredForPreOrPost(MonoServerReplicationUserData uData)
   {
-    boolean cancelled = false;
-
-    String adminPwd = argParser.getBindPasswordAdmin();
-    String adminUid = argParser.getAdministratorUID();
-
-    String host = argParser.getHostNameToInitializeAll();
-    int port = argParser.getPortToInitializeAll();
-
-    /*
-     * Try to connect to the server.
-     */
     InitialLdapContext ctx = null;
+    try
+    {
+      ctx = getInitialLdapContext(uData);
+      if (ctx == null)
+      {
+        return false;
+      }
+      LinkedList<String> suffixes = argParser.getBaseDNs();
+      checkSuffixesForInitializeReplication(suffixes, ctx, true);
+      uData.setBaseDNs(suffixes);
+      return !suffixes.isEmpty();
+    }
+    finally
+    {
+      close(ctx);
+    }
+  }
 
-    while (ctx == null && !cancelled)
+  private InitialLdapContext getInitialLdapContext(MonoServerReplicationUserData uData)
+  {
+    // Try to connect to the server.
+    while (true)
     {
       try
       {
-        ci.run();
-        host = ci.getHostName();
-        port = ci.getPortNumber();
-        adminUid = ci.getAdministratorUID();
-        adminPwd = ci.getBindPassword();
-
-        ctx = createInitialLdapContextInteracting(ci);
-
-        if (ctx == null)
+        if (uData instanceof InitializeAllReplicationUserData)
         {
-          cancelled = true;
+          ci.setHeadingMessage(INFO_REPLICATION_INITIALIZE_SOURCE_CONNECTION_PARAMETERS.get());
         }
+        ci.run();
+
+        InitialLdapContext ctx = createInitialLdapContextInteracting(ci);
+        if (ctx != null)
+        {
+          uData.setHostName(ci.getHostName());
+          uData.setPort(ci.getPortNumber());
+          uData.setAdminUid(ci.getAdministratorUID());
+          uData.setAdminPwd(ci.getBindPassword());
+          if (uData instanceof StatusReplicationUserData)
+          {
+            ((StatusReplicationUserData) uData).setScriptFriendly(argParser.isScriptFriendly());
+          }
+        }
+        return ctx;
       }
       catch (ClientException ce)
       {
-        logger.warn(LocalizableMessage.raw("Client exception "+ce));
+        logger.warn(LocalizableMessage.raw("Client exception " + ce));
         println();
         println(ce.getMessageObject());
         println();
@@ -2930,32 +2880,13 @@
       }
       catch (ArgumentException ae)
       {
-        logger.warn(LocalizableMessage.raw("Argument exception "+ae));
+        logger.warn(LocalizableMessage.raw("Argument exception " + ae));
         println();
         println(ae.getMessageObject());
         println();
-        cancelled = true;
+        return null;
       }
     }
-    if (!cancelled)
-    {
-      uData.setHostName(host);
-      uData.setPort(port);
-      uData.setAdminUid(adminUid);
-      uData.setAdminPwd(adminPwd);
-    }
-
-    if (!cancelled)
-    {
-      LinkedList<String> suffixes = argParser.getBaseDNs();
-      checkSuffixesForInitializeReplication(suffixes, ctx, true);
-      cancelled = suffixes.isEmpty();
-
-      uData.setBaseDNs(suffixes);
-    }
-
-    close(ctx);
-    return !cancelled;
   }
 
   /**
@@ -2972,79 +2903,38 @@
   private boolean promptIfRequired(StatusReplicationUserData uData)
   throws ReplicationCliException
   {
-    boolean cancelled = false;
-
-    String adminPwd = argParser.getBindPasswordAdmin();
-    String adminUid = argParser.getAdministratorUID();
-
-    String host = argParser.getHostNameToStatus();
-    int port = argParser.getPortToStatus();
-
-    /*
-     * Try to connect to the server.
-     */
     InitialLdapContext ctx = null;
-    while (ctx == null && !cancelled)
+    try
     {
-      try
+      ctx = getInitialLdapContext(uData);
+      if (ctx == null)
       {
-        ci.run();
-        host = ci.getHostName();
-        port = ci.getPortNumber();
-        adminUid = ci.getAdministratorUID();
-        adminPwd = ci.getBindPassword();
+        return false;
+      }
 
-        ctx = createInitialLdapContextInteracting(ci);
-
-        if (ctx == null)
-        {
-          cancelled = true;
-        }
-      }
-      catch (ClientException ce)
-      {
-        logger.warn(LocalizableMessage.raw("Client exception "+ce));
-        println();
-        println(ce.getMessageObject());
-        println();
-        ci.resetConnectionArguments();
-      }
-      catch (ArgumentException ae)
-      {
-        logger.warn(LocalizableMessage.raw("Argument exception "+ae));
-        println();
-        println(ae.getMessageObject());
-        println();
-        cancelled = true;
-      }
-    }
-    if (!cancelled)
-    {
-      uData.setHostName(host);
-      uData.setPort(port);
-      uData.setAdminUid(adminUid);
-      uData.setAdminPwd(adminPwd);
-      uData.setScriptFriendly(argParser.isScriptFriendly());
-    }
-    if (ctx != null)
-    {
       // If the server contains an ADS, try to load it and only load it: if
       // there are issues with the ADS they will be encountered in the
-      // statusReplication(StatusReplicationUserData) method.  Here we have
+      // statusReplication(StatusReplicationUserData) method. Here we have
       // to load the ADS to ask the user to accept the certificates and
       // eventually admin authentication data.
-      InitialLdapContext[] aux = new InitialLdapContext[] {ctx};
-      cancelled = !loadADSAndAcceptCertificates(aux, uData, false);
-      ctx = aux[0];
-    }
+      AtomicReference<InitialLdapContext> aux = new AtomicReference<InitialLdapContext>(ctx);
+      boolean cancelled = !loadADSAndAcceptCertificates(aux, uData, false);
+      ctx = aux.get();
+      if (cancelled)
+      {
+        return false;
+      }
 
-    if (!cancelled)
+      if (!cancelled)
+      {
+        uData.setBaseDNs(argParser.getBaseDNs());
+      }
+      return !cancelled;
+    }
+    finally
     {
-      uData.setBaseDNs(argParser.getBaseDNs());
+      close(ctx);
     }
-
-    close(ctx);
-    return !cancelled;
   }
 
   /**
@@ -3067,12 +2957,9 @@
     int portSource = argParser.getPortSource();
 
     Map<String, String> pwdFile = null;
-
     if (argParser.getSecureArgsList().bindPasswordFileArg.isPresent())
     {
-      pwdFile =
-        argParser.getSecureArgsList().bindPasswordFileArg.
-        getNameToValueMap();
+      pwdFile = argParser.getSecureArgsList().bindPasswordFileArg.getNameToValueMap();
     }
 
 
@@ -3092,8 +2979,7 @@
     {
       try
       {
-        ci.setHeadingMessage(
-            INFO_REPLICATION_INITIALIZE_SOURCE_CONNECTION_PARAMETERS.get());
+        ci.setHeadingMessage(INFO_REPLICATION_INITIALIZE_SOURCE_CONNECTION_PARAMETERS.get());
         ci.run();
         hostSource = ci.getHostName();
         portSource = ci.getPortNumber();
@@ -3159,8 +3045,7 @@
     {
       try
       {
-        ci.setHeadingMessage(
-           INFO_REPLICATION_INITIALIZE_DESTINATION_CONNECTION_PARAMETERS.get());
+        ci.setHeadingMessage(INFO_REPLICATION_INITIALIZE_DESTINATION_CONNECTION_PARAMETERS.get());
         ci.run();
         hostDestination = ci.getHostName();
         portDestination = ci.getPortNumber();
@@ -3221,22 +3106,8 @@
     if (!cancelled)
     {
       // Ask for confirmation to initialize.
-      String hostPortSource = getHostPort(ctxSource);
-      String hostPortDestination = getHostPort(ctxDestination);
-      LocalizableMessage msg;
-      if (initializeADS(uData.getBaseDNs()))
-      {
-        msg = INFO_REPLICATION_CONFIRM_INITIALIZE_ADS.get(
-            ADSContext.getAdministrationSuffixDN(), hostPortDestination, hostPortSource);
-      }
-      else
-      {
-        msg = INFO_REPLICATION_CONFIRM_INITIALIZE_GENERIC.get(
-            hostPortDestination, hostPortSource);
-      }
-
       println();
-      cancelled = !askConfirmation(msg, true);
+      cancelled = !askConfirmation(getPrompt(uData, ctxSource, ctxDestination), true);
       println();
     }
 
@@ -3244,6 +3115,19 @@
     return !cancelled;
   }
 
+  private LocalizableMessage getPrompt(InitializeReplicationUserData uData, InitialLdapContext ctxSource,
+      InitialLdapContext ctxDestination)
+  {
+    String hostPortSource = getHostPort(ctxSource);
+    String hostPortDestination = getHostPort(ctxDestination);
+    if (initializeADS(uData.getBaseDNs()))
+    {
+      final String adminSuffixDN = ADSContext.getAdministrationSuffixDN();
+      return INFO_REPLICATION_CONFIRM_INITIALIZE_ADS.get(adminSuffixDN, hostPortDestination, hostPortSource);
+    }
+    return INFO_REPLICATION_CONFIRM_INITIALIZE_GENERIC.get(hostPortDestination, hostPortSource);
+  }
+
   private boolean initializeADS(List<String> baseDNs)
   {
     for (String dn : baseDNs)
@@ -3566,16 +3450,17 @@
    * if the user did not accept a certificate or any of the confirmation
    * messages.
    */
-  private boolean loadADSAndAcceptCertificates(InitialLdapContext[] ctx,
+  private boolean loadADSAndAcceptCertificates(AtomicReference<InitialLdapContext> ctx,
       ReplicationUserData uData, boolean isFirstOrSourceServer)
   throws ReplicationCliException
   {
     boolean cancelled = false;
     boolean triedWithUserProvidedAdmin = false;
-    String host = getHostName(ctx[0]);
-    int port = getPort(ctx[0]);
-    boolean isSSL = isSSL(ctx[0]);
-    boolean isStartTLS = isStartTLS(ctx[0]);
+    final InitialLdapContext ctx1 = ctx.get();
+    String host = getHostName(ctx1);
+    int port = getPort(ctx1);
+    boolean isSSL = isSSL(ctx1);
+    boolean isStartTLS = isStartTLS(ctx1);
     if (getTrustManager() == null)
     {
       // This is required when the user did  connect to the server using SSL or
@@ -3585,7 +3470,7 @@
     }
     try
     {
-      ADSContext adsContext = new ADSContext(ctx[0]);
+      ADSContext adsContext = new ADSContext(ctx1);
       if (adsContext.hasAdminData())
       {
         boolean reloadTopology = true;
@@ -3599,7 +3484,7 @@
               getTrustManager(), getConnectTimeout());
           cache.getFilter().setSearchMonitoringInformation(false);
           cache.getFilter().setSearchBaseDNInformation(false);
-          cache.setPreferredConnections(getPreferredConnections(ctx[0]));
+          cache.setPreferredConnections(getPreferredConnections(ctx1));
           cache.reloadTopology();
 
           reloadTopology = false;
@@ -3664,18 +3549,19 @@
                     adminPwd = askForAdministratorPwd(logger);
                     println();
                   }
-                  close(ctx[0]);
+                  close(ctx1);
                   try
                   {
-                    ctx[0] = createAdministrativeContext(host, port, isSSL,
+                    final InitialLdapContext ctx2 = createAdministrativeContext(host, port, isSSL,
                         isStartTLS, getAdministratorDN(adminUid),
                         adminPwd, getConnectTimeout(), getTrustManager());
-                    adsContext = new ADSContext(ctx[0]);
+                    ctx.set(ctx2);
+                    adsContext = new ADSContext(ctx2);
                     cache = new TopologyCache(adsContext, getTrustManager(),
                         getConnectTimeout());
                     cache.getFilter().setSearchMonitoringInformation(false);
                     cache.getFilter().setSearchBaseDNInformation(false);
-                    cache.setPreferredConnections(getPreferredConnections(ctx[0]));
+                    cache.setPreferredConnections(getPreferredConnections(ctx2));
                     connected = true;
                   }
                   catch (Throwable t)
@@ -4332,7 +4218,6 @@
   {
     InitialLdapContext ctxSource = createAdministrativeContext(uData, true);
     InitialLdapContext ctxDestination = createAdministrativeContext(uData, false);
-
     try
     {
       if (ctxSource == null || ctxDestination == null)
@@ -4342,41 +4227,36 @@
 
       List<String> baseDNs = uData.getBaseDNs();
       checkSuffixesForInitializeReplication(baseDNs, ctxSource, ctxDestination, false);
-      if (!baseDNs.isEmpty())
-      {
-        if (mustPrintCommandBuilder())
-        {
-          uData.setBaseDNs(baseDNs);
-          printNewCommandBuilder(INITIALIZE_REPLICATION_SUBCMD_NAME, uData);
-        }
-
-        ReplicationCliReturnCode returnValue = SUCCESSFUL_NOP;
-        for (String baseDN : baseDNs)
-        {
-          try
-          {
-            println();
-            LocalizableMessage msg =
-                formatter.getFormattedProgress(INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN, getHostPort(ctxSource)));
-            print(msg);
-            println();
-            initializeSuffix(baseDN, ctxSource, ctxDestination, true);
-            returnValue = SUCCESSFUL;
-          }
-          catch (ReplicationCliException rce)
-          {
-            println();
-            println(getCriticalExceptionMessage(rce));
-            returnValue = rce.getErrorCode();
-            logger.error(LocalizableMessage.raw("Complete error stack:"), rce);
-          }
-        }
-        return returnValue;
-      }
-      else
+      if (baseDNs.isEmpty())
       {
         return REPLICATION_CANNOT_BE_INITIALIZED_ON_BASEDN;
       }
+      if (mustPrintCommandBuilder())
+      {
+        uData.setBaseDNs(baseDNs);
+        printNewCommandBuilder(INITIALIZE_REPLICATION_SUBCMD_NAME, uData);
+      }
+
+      ReplicationCliReturnCode returnValue = SUCCESSFUL_NOP;
+      for (String baseDN : baseDNs)
+      {
+        try
+        {
+          println();
+          print(formatter.getFormattedProgress(INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN, getHostPort(ctxSource))));
+          println();
+          initializeSuffix(baseDN, ctxSource, ctxDestination, true);
+          returnValue = SUCCESSFUL;
+        }
+        catch (ReplicationCliException rce)
+        {
+          println();
+          println(getCriticalExceptionMessage(rce));
+          returnValue = rce.getErrorCode();
+          logger.error(LocalizableMessage.raw("Complete error stack:"), rce);
+        }
+      }
+      return returnValue;
     }
     finally
     {
@@ -4427,39 +4307,36 @@
     {
       List<String> baseDNs = uData.getBaseDNs();
       checkSuffixesForInitializeReplication(baseDNs, ctx, false);
-      if (!baseDNs.isEmpty())
-      {
-        if (mustPrintCommandBuilder())
-        {
-          uData.setBaseDNs(baseDNs);
-          printNewCommandBuilder(INITIALIZE_ALL_REPLICATION_SUBCMD_NAME, uData);
-        }
-
-        ReplicationCliReturnCode returnValue = SUCCESSFUL_NOP;
-        for (String baseDN : baseDNs)
-        {
-          try
-          {
-            println();
-            print(formatter.getFormattedProgress(INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN, getHostPort(ctx))));
-            println();
-            initializeAllSuffix(baseDN, ctx, true);
-            returnValue = SUCCESSFUL;
-          }
-          catch (ReplicationCliException rce)
-          {
-            println();
-            println(getCriticalExceptionMessage(rce));
-            returnValue = rce.getErrorCode();
-            logger.error(LocalizableMessage.raw("Complete error stack:"), rce);
-          }
-        }
-        return returnValue;
-      }
-      else
+      if (baseDNs.isEmpty())
       {
         return REPLICATION_CANNOT_BE_INITIALIZED_ON_BASEDN;
       }
+      if (mustPrintCommandBuilder())
+      {
+        uData.setBaseDNs(baseDNs);
+        printNewCommandBuilder(INITIALIZE_ALL_REPLICATION_SUBCMD_NAME, uData);
+      }
+
+      ReplicationCliReturnCode returnValue = SUCCESSFUL_NOP;
+      for (String baseDN : baseDNs)
+      {
+        try
+        {
+          println();
+          print(formatter.getFormattedProgress(INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN, getHostPort(ctx))));
+          println();
+          initializeAllSuffix(baseDN, ctx, true);
+          returnValue = SUCCESSFUL;
+        }
+        catch (ReplicationCliException rce)
+        {
+          println();
+          println(getCriticalExceptionMessage(rce));
+          returnValue = rce.getErrorCode();
+          logger.error(LocalizableMessage.raw("Complete error stack:"), rce);
+        }
+      }
+      return returnValue;
     }
     finally
     {
@@ -4490,43 +4367,39 @@
     {
       List<String> baseDNs = uData.getBaseDNs();
       checkSuffixesForInitializeReplication(baseDNs, ctx, false);
-      if (!baseDNs.isEmpty())
-      {
-        if (mustPrintCommandBuilder())
-        {
-          uData.setBaseDNs(baseDNs);
-          printNewCommandBuilder(PRE_EXTERNAL_INITIALIZATION_SUBCMD_NAME, uData);
-        }
-
-        ReplicationCliReturnCode returnValue = SUCCESSFUL;
-        for (String baseDN : baseDNs)
-        {
-          try
-          {
-            println();
-            print(formatter.getFormattedWithPoints(
-                INFO_PROGRESS_PRE_EXTERNAL_INITIALIZATION.get(baseDN)));
-            preExternalInitialization(baseDN, ctx);
-            print(formatter.getFormattedDone());
-            println();
-          }
-          catch (ReplicationCliException rce)
-          {
-            println();
-            println(getCriticalExceptionMessage(rce));
-            returnValue = rce.getErrorCode();
-            logger.error(LocalizableMessage.raw("Complete error stack:"), rce);
-          }
-        }
-        println();
-        print(INFO_PROGRESS_PRE_INITIALIZATION_FINISHED_PROCEDURE.get(POST_EXTERNAL_INITIALIZATION_SUBCMD_NAME));
-        println();
-        return returnValue;
-      }
-      else
+      if (baseDNs.isEmpty())
       {
         return REPLICATION_CANNOT_BE_INITIALIZED_ON_BASEDN;
       }
+      if (mustPrintCommandBuilder())
+      {
+        uData.setBaseDNs(baseDNs);
+        printNewCommandBuilder(PRE_EXTERNAL_INITIALIZATION_SUBCMD_NAME, uData);
+      }
+
+      ReplicationCliReturnCode returnValue = SUCCESSFUL;
+      for (String baseDN : baseDNs)
+      {
+        try
+        {
+          println();
+          print(formatter.getFormattedWithPoints(INFO_PROGRESS_PRE_EXTERNAL_INITIALIZATION.get(baseDN)));
+          preExternalInitialization(baseDN, ctx);
+          print(formatter.getFormattedDone());
+          println();
+        }
+        catch (ReplicationCliException rce)
+        {
+          println();
+          println(getCriticalExceptionMessage(rce));
+          returnValue = rce.getErrorCode();
+          logger.error(LocalizableMessage.raw("Complete error stack:"), rce);
+        }
+      }
+      println();
+      print(INFO_PROGRESS_PRE_INITIALIZATION_FINISHED_PROCEDURE.get(POST_EXTERNAL_INITIALIZATION_SUBCMD_NAME));
+      println();
+      return returnValue;
     }
     finally
     {
@@ -4557,43 +4430,39 @@
     {
       List<String> baseDNs = uData.getBaseDNs();
       checkSuffixesForInitializeReplication(baseDNs, ctx, false);
-      if (!baseDNs.isEmpty())
-      {
-        if (mustPrintCommandBuilder())
-        {
-          uData.setBaseDNs(baseDNs);
-          printNewCommandBuilder(POST_EXTERNAL_INITIALIZATION_SUBCMD_NAME, uData);
-        }
-
-        ReplicationCliReturnCode returnValue = SUCCESSFUL;
-        for (String baseDN : baseDNs)
-        {
-          try
-          {
-            println();
-            print(formatter.getFormattedWithPoints(
-                INFO_PROGRESS_POST_EXTERNAL_INITIALIZATION.get(baseDN)));
-            postExternalInitialization(baseDN, ctx);
-            println(formatter.getFormattedDone());
-            println();
-          }
-          catch (ReplicationCliException rce)
-          {
-            println();
-            println(getCriticalExceptionMessage(rce));
-            returnValue = rce.getErrorCode();
-            logger.error(LocalizableMessage.raw("Complete error stack:"), rce);
-          }
-        }
-        println();
-        print(INFO_PROGRESS_POST_INITIALIZATION_FINISHED_PROCEDURE.get());
-        println();
-        return returnValue;
-      }
-      else
+      if (baseDNs.isEmpty())
       {
         return REPLICATION_CANNOT_BE_INITIALIZED_ON_BASEDN;
       }
+      if (mustPrintCommandBuilder())
+      {
+        uData.setBaseDNs(baseDNs);
+        printNewCommandBuilder(POST_EXTERNAL_INITIALIZATION_SUBCMD_NAME, uData);
+      }
+
+      ReplicationCliReturnCode returnValue = SUCCESSFUL;
+      for (String baseDN : baseDNs)
+      {
+        try
+        {
+          println();
+          print(formatter.getFormattedWithPoints(INFO_PROGRESS_POST_EXTERNAL_INITIALIZATION.get(baseDN)));
+          postExternalInitialization(baseDN, ctx);
+          println(formatter.getFormattedDone());
+          println();
+        }
+        catch (ReplicationCliException rce)
+        {
+          println();
+          println(getCriticalExceptionMessage(rce));
+          returnValue = rce.getErrorCode();
+          logger.error(LocalizableMessage.raw("Complete error stack:"), rce);
+        }
+      }
+      println();
+      print(INFO_PROGRESS_POST_INITIALIZATION_FINISHED_PROCEDURE.get());
+      println();
+      return returnValue;
     }
     finally
     {
@@ -6710,9 +6579,7 @@
         tableBuilder.appendCell(EMPTY_MSG);
       }
       // Secure
-      tableBuilder.appendCell(
-        LocalizableMessage.raw(
-          Boolean.toString(server.isReplicationSecure())));
+      tableBuilder.appendCell(LocalizableMessage.raw(Boolean.toString(server.isReplicationSecure())));
     }
 
     PrintStream out = getOutputStream();
@@ -6720,15 +6587,13 @@
 
     if (scriptFriendly)
     {
-      print(
-          INFO_REPLICATION_STATUS_INDEPENDENT_REPLICATION_SERVERS.get());
+      print(INFO_REPLICATION_STATUS_INDEPENDENT_REPLICATION_SERVERS.get());
       println();
       printer = new TabSeparatedTablePrinter(out);
     }
     else
     {
-      LocalizableMessage msg =
-        INFO_REPLICATION_STATUS_INDEPENDENT_REPLICATION_SERVERS.get();
+      LocalizableMessage msg = INFO_REPLICATION_STATUS_INDEPENDENT_REPLICATION_SERVERS.get();
       print(msg);
       println();
       int length = msg.length();
@@ -7555,20 +7420,7 @@
         if (helper.isDone(state) || helper.isStoppedByError(state))
         {
           isOver = true;
-          LocalizableMessage errorMsg;
-          String server = getHostPort(ctx);
-          if (lastLogMsg == null)
-          {
-            errorMsg = isPre
-                ? INFO_ERROR_DURING_PRE_EXTERNAL_INITIALIZATION_NO_LOG.get(state, server)
-                : INFO_ERROR_DURING_POST_EXTERNAL_INITIALIZATION_NO_LOG.get(state, server);
-          }
-          else
-          {
-            errorMsg = isPre
-                ? INFO_ERROR_DURING_PRE_EXTERNAL_INITIALIZATION_LOG.get(lastLogMsg, state, server)
-                : INFO_ERROR_DURING_POST_EXTERNAL_INITIALIZATION_LOG.get(lastLogMsg, state, server);
-          }
+          LocalizableMessage errorMsg = getPrePostErrorMsg(isPre, lastLogMsg, state, ctx);
 
           if (helper.isCompletedWithErrors(state))
           {
@@ -7601,6 +7453,20 @@
     }
   }
 
+  private LocalizableMessage getPrePostErrorMsg(boolean isPre, String lastLogMsg, String state, InitialLdapContext ctx)
+  {
+    String server = getHostPort(ctx);
+    if (lastLogMsg == null)
+    {
+      return isPre
+          ? INFO_ERROR_DURING_PRE_EXTERNAL_INITIALIZATION_NO_LOG.get(state, server)
+          : INFO_ERROR_DURING_POST_EXTERNAL_INITIALIZATION_NO_LOG.get(state, server);
+    }
+    return isPre
+        ? INFO_ERROR_DURING_PRE_EXTERNAL_INITIALIZATION_LOG.get(lastLogMsg, state, server)
+        : INFO_ERROR_DURING_POST_EXTERNAL_INITIALIZATION_LOG.get(lastLogMsg, state, server);
+  }
+
   private void sleepCatchInterrupt(long millis)
   {
     try
@@ -7706,10 +7572,8 @@
 
         // Get the number of entries that have been handled and
         // a percentage...
-        String sProcessed = getFirstValue(sr,
-        "ds-task-processed-entry-count");
-        String sUnprocessed = getFirstValue(sr,
-        "ds-task-unprocessed-entry-count");
+        String sProcessed = getFirstValue(sr, "ds-task-processed-entry-count");
+        String sUnprocessed = getFirstValue(sr, "ds-task-unprocessed-entry-count");
         long processed = -1;
         long unprocessed = -1;
         if (sProcessed != null)
@@ -7758,7 +7622,6 @@
         if (helper.isDone(state) || helper.isStoppedByError(state))
         {
           isOver = true;
-          LocalizableMessage errorMsg;
           logger.info(LocalizableMessage.raw("Last task entry: "+sr));
           if (displayProgress && msg != null && !msg.equals(lastDisplayedMsg))
           {
@@ -7766,17 +7629,8 @@
             lastDisplayedMsg = msg;
             println();
           }
-          if (lastLogMsg == null)
-          {
-            errorMsg = INFO_ERROR_DURING_INITIALIZATION_NO_LOG.get(
-                    serverDisplay, state, serverDisplay);
-          }
-          else
-          {
-            errorMsg = INFO_ERROR_DURING_INITIALIZATION_LOG.get(
-                serverDisplay, lastLogMsg, state, serverDisplay);
-          }
 
+          LocalizableMessage errorMsg = getInitializeAllErrorMsg(serverDisplay, lastLogMsg, state);
           if (helper.isCompletedWithErrors(state))
           {
             logger.warn(LocalizableMessage.raw("Processed errorMsg: "+errorMsg));
@@ -7838,6 +7692,15 @@
     }
   }
 
+  private LocalizableMessage getInitializeAllErrorMsg(String serverDisplay, String lastLogMsg, String state)
+  {
+    if (lastLogMsg != null)
+    {
+      return INFO_ERROR_DURING_INITIALIZATION_LOG.get(serverDisplay, lastLogMsg, state, serverDisplay);
+    }
+    return INFO_ERROR_DURING_INITIALIZATION_NO_LOG.get(serverDisplay, state, serverDisplay);
+  }
+
   private LocalizableMessage getMsg(LocalizableMessage lastDisplayedMsg,
       String sProcessed, String sUnprocessed, long processed, long unprocessed)
   {

--
Gitblit v1.10.0