From 585d1bf2936de4197aaf3af84f07a5607e013a1e Mon Sep 17 00:00:00 2001
From: Jean-Noel Rouvignac <jean-noel.rouvignac@forgerock.com>
Date: Fri, 09 Aug 2013 08:34:00 +0000
Subject: [PATCH] *Test*.java: Used TestCaseUtils.findFreePort() instead of TestCaseUtils.bindFreePort(). Used StaticUtils.close().

---
 opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/jmx/JmxConnectTest.java                           |  107 +--
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerFailoverTest.java       |   74 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/AssuredReplicationPluginTest.java        |   13 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalTest.java                      |    8 
 opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/LdapTestCase.java                            |   85 +-
 opends/tests/unit-tests-testng/src/server/org/opends/quicksetup/TestUtilities.java                                      |   36 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/StateMachineTest.java                    |  238 ++-----
 opends/tests/unit-tests-testng/src/server/org/opends/server/extensions/LDAPPassThroughAuthenticationPolicyTestCase.java |  237 ++-----
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/GenerationIdTest.java                           |   65 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/AssuredReplicationServerTest.java        |   20 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/GroupIdHandshakeTest.java                |   98 +--
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/FractionalReplicationTest.java           |    6 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerLoadBalancingTest.java  |   24 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/SchemaReplicationTest.java                      |   30 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ChangeNumberControlPluginTestCase.java          |   31 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReSyncTest.java                                 |   14 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerDynamicConfTest.java    |   19 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/InitOnLineTest.java                             |   67 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ProtocolWindowTest.java                         |   26 
 opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/TestLDAPConnectionHandler.java               |    2 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/IsolationTest.java                       |   17 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/MonitorTest.java                         |   64 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/service/ReplicationDomainTest.java              |   79 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalCsnOrderingTest.java           |   77 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java                    |   52 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/TestCaseUtils.java                                          |  113 +--
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java                        |   55 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/DependencyTest.java                             |   47 -
 opends/tests/unit-tests-testng/src/server/org/opends/server/snmp/SNMPConnectionManager.java                             |    6 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/DraftCNDbHandlerTest.java                |   11 
 opends/tests/unit-tests-testng/src/server/org/opends/server/admin/server/AggregationServerTest.java                     |   84 +-
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/StressTest.java                                 |   35 
 opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerTest.java               |   36 
 33 files changed, 613 insertions(+), 1,263 deletions(-)

diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/quicksetup/TestUtilities.java b/opends/tests/unit-tests-testng/src/server/org/opends/quicksetup/TestUtilities.java
index 09e8c66..12b01de 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/quicksetup/TestUtilities.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/quicksetup/TestUtilities.java
@@ -23,27 +23,24 @@
  *
  *
  *      Copyright 2009 Sun Microsystems, Inc.
+ *      Portions copyright 2013 ForgeRock AS
  */
-
 package org.opends.quicksetup;
 
-import org.opends.quicksetup.util.ZipExtractor;
-import org.opends.quicksetup.util.ServerController;
-import org.opends.quicksetup.util.FileManager;
-import org.opends.server.TestCaseUtils;
-import org.opends.server.types.OperatingSystem;
-import org.opends.server.types.ByteStringBuilder;
-
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.net.ServerSocket;
-import java.util.List;
 import java.util.ArrayList;
+import java.util.List;
 
-/**
- *
- */
+import org.opends.quicksetup.util.FileManager;
+import org.opends.quicksetup.util.ServerController;
+import org.opends.quicksetup.util.ZipExtractor;
+import org.opends.server.TestCaseUtils;
+import org.opends.server.types.ByteStringBuilder;
+import org.opends.server.types.OperatingSystem;
+
+@SuppressWarnings("javadoc")
 public class TestUtilities {
 
   /**
@@ -55,7 +52,6 @@
   public static final String DIRECTORY_MANAGER_PASSWORD = "password";
 
   public static Integer ldapPort;
-
   public static Integer jmxPort;
 
   private static boolean initialized;
@@ -80,13 +76,9 @@
   }
 
   static private void setupServer() throws IOException, InterruptedException {
-    ServerSocket ldapSocket = TestCaseUtils.bindFreePort();
-    ldapPort = ldapSocket.getLocalPort();
-    ldapSocket.close();
-
-    ServerSocket jmxSocket = TestCaseUtils.bindFreePort();
-    jmxPort = jmxSocket.getLocalPort();
-    jmxSocket.close();
+    int[] ports = TestCaseUtils.findFreePorts(2);
+    ldapPort = ports[0];
+    jmxPort = ports[1];
 
     List<String> args = new ArrayList<String>();
     File root = getQuickSetupTestServerRootDir();
@@ -107,7 +99,7 @@
     args.add("-O");
 
     ProcessBuilder pb = new ProcessBuilder(args);
-    
+
     Process p = pb.start();
     if (p.waitFor() != 0) {
       ByteStringBuilder stdOut = new ByteStringBuilder();
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/TestCaseUtils.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/TestCaseUtils.java
index a554143..f82609b 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/TestCaseUtils.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/TestCaseUtils.java
@@ -79,6 +79,7 @@
  * This class defines some utility functions which can be used by test
  * cases.
  */
+@SuppressWarnings("javadoc")
 public final class TestCaseUtils {
   /**
    * The name of the system property that specifies the server build root.
@@ -456,40 +457,10 @@
 
       // Find some free ports for the listeners and write them to the
       // config-chamges.ldif file.
-      ServerSocket serverLdapSocket  = null;
-      ServerSocket serverAdminSocket  = null;
-      ServerSocket serverJmxSocket   = null;
-      ServerSocket serverLdapsSocket = null;
-
-      String ldapPort = System.getProperty(PROPERTY_LDAP_PORT);
-      if (ldapPort == null)
-      {
-        serverLdapSocket = bindFreePort();
-        serverLdapPort = serverLdapSocket.getLocalPort();
-      }
-      else
-      {
-        serverLdapPort = Integer.valueOf(ldapPort);
-        serverLdapSocket = bindPort(serverLdapPort);
-      }
-
-      String adminPort = System.getProperty(PROPERTY_ADMIN_PORT);
-      if (adminPort == null)
-      {
-        serverAdminSocket = bindFreePort();
-        serverAdminPort = serverAdminSocket.getLocalPort();
-      }
-      else
-      {
-        serverAdminPort = Integer.valueOf(adminPort);
-        serverAdminSocket = bindPort(serverAdminPort);
-      }
-
-      serverJmxSocket = bindFreePort();
-      serverJmxPort = serverJmxSocket.getLocalPort();
-
-      serverLdapsSocket = bindFreePort();
-      serverLdapsPort = serverLdapsSocket.getLocalPort();
+      serverLdapPort = getFreePort(PROPERTY_LDAP_PORT);
+      serverAdminPort = getFreePort(PROPERTY_ADMIN_PORT);
+      serverJmxPort = findFreePort();
+      serverLdapsPort = findFreePort();
 
       String defaultConfigChangeFile = testResourceDir + File.separator
           + "config-changes.ldif";
@@ -502,7 +473,6 @@
       PrintStream writer = new PrintStream(outFile);
 
       String line = reader.readLine();
-
       while(line != null)
       {
         line = line.replaceAll("#ldapport#", String.valueOf(serverLdapPort));
@@ -514,14 +484,7 @@
         line = reader.readLine();
       }
 
-      writer.close();
-      outFile.close();
-      reader.close();
-
-      serverLdapSocket.close();
-      serverAdminSocket.close();
-      serverJmxSocket.close();
-      serverLdapsSocket.close();
+      close(writer, outFile, reader);
 
       // Create a configuration for the server.
       DirectoryEnvironmentConfig config = new DirectoryEnvironmentConfig();
@@ -581,6 +544,19 @@
     }
   }
 
+  private static int getFreePort(String portPropertyName) throws IOException
+  {
+    String port = System.getProperty(portPropertyName);
+    if (port == null)
+    {
+      return findFreePort();
+    }
+    int portNb = Integer.parseInt(port);
+    // Check this port is free
+    bindPort(portNb).close();
+    return portNb;
+  }
+
   /**
    * Similar to startServer, but it will restart the server each time it is
    * called.  Since this is somewhat expensive, it should be called under
@@ -765,7 +741,7 @@
 
   /**
    * Find a free port on the local host.
-   * 
+   *
    * @throws IOException
    *           in case of underlying exception.
    * @return the free port number found
@@ -1090,22 +1066,19 @@
    *           If the file could not be copied.
    */
   public static void copyFile(File src, File dst) throws IOException {
-    InputStream in = new FileInputStream(src);
-    OutputStream out = new FileOutputStream(dst);
-
-    // Transfer bytes from in to out
-    byte[] buf = new byte[8192];
-    int len;
-    while ((len = in.read(buf)) > 0) {
-      out.write(buf, 0, len);
-    }
-    in.close();
-    out.close();
+    copyOrAppend(src, dst, false);
   }
 
-  public static void appendFile(File src, File dst) throws IOException {
+  public static void appendFile(File src, File dst) throws IOException
+  {
+    copyOrAppend(src, dst, true);
+  }
+
+  private static void copyOrAppend(File src, File dst, boolean append)
+      throws IOException
+  {
     InputStream in = new FileInputStream(src);
-    OutputStream out = new FileOutputStream(dst, true);
+    OutputStream out = new FileOutputStream(dst, append);
 
     // Transfer bytes from in to out
     byte[] buf = new byte[8192];
@@ -1113,8 +1086,7 @@
     while ((len = in.read(buf)) > 0) {
       out.write(buf, 0, len);
     }
-    in.close();
-    out.close();
+    close(in, out);
   }
 
 
@@ -1414,9 +1386,7 @@
     } catch (Exception t) {
       t.printStackTrace();
     } finally {
-      if (s != null) {
-        s.close();
-      }
+      close(s);
     }
     return false;
   }
@@ -1866,14 +1836,10 @@
         bytes = bout.toByteArray();
       }
       finally {
-        if (close) {
-          try {
-            is.close();
-          }
-          catch (java.io.IOException ex) {
-            // ignore these
-          }
-        } // end of if (is != null)
+        if (close)
+        {
+          close(is);
+        }
       }
     }
     return bytes;
@@ -1906,12 +1872,7 @@
       fos = new FileOutputStream(path);
       fos.write(contents);
     } finally {
-      try {
-        if (fos != null) fos.close();
-      }
-      catch (java.io.IOException e) {
-        // ignore these
-      }
+      close(fos);
     }
   }
 
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/admin/server/AggregationServerTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/admin/server/AggregationServerTest.java
index 2d6a19a..786acb2 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/admin/server/AggregationServerTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/admin/server/AggregationServerTest.java
@@ -23,12 +23,10 @@
  *
  *
  *      Copyright 2007-2008 Sun Microsystems, Inc.
+ *      Portions copyright 2013 ForgeRock AS
  */
 package org.opends.server.admin.server;
 
-
-
-import java.net.ServerSocket;
 import java.util.Collection;
 import java.util.List;
 import java.util.SortedSet;
@@ -38,18 +36,7 @@
 
 import org.opends.messages.Message;
 import org.opends.server.TestCaseUtils;
-import org.opends.server.admin.AdminTestCase;
-import org.opends.server.admin.AdministratorAction;
-import org.opends.server.admin.AggregationPropertyDefinition;
-import org.opends.server.admin.IllegalPropertyValueStringException;
-import org.opends.server.admin.ManagedObjectNotFoundException;
-import org.opends.server.admin.PropertyException;
-import org.opends.server.admin.PropertyOption;
-import org.opends.server.admin.TestCfg;
-import org.opends.server.admin.TestChildCfg;
-import org.opends.server.admin.TestChildCfgDefn;
-import org.opends.server.admin.TestParentCfg;
-import org.opends.server.admin.UndefinedDefaultBehaviorProvider;
+import org.opends.server.admin.*;
 import org.opends.server.admin.client.OperationRejectedException;
 import org.opends.server.admin.client.ldap.JNDIDirContextAdaptor;
 import org.opends.server.admin.condition.Conditions;
@@ -68,8 +55,6 @@
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-
-
 /**
  * Test cases for aggregations on the server-side.
  */
@@ -86,6 +71,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public ConfigChangeResult applyConfigurationChange(
         TestChildCfg configuration) {
       return new ConfigChangeResult(ResultCode.SUCCESS, false);
@@ -96,6 +82,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public boolean isConfigurationChangeAcceptable(TestChildCfg configuration,
         List<Message> unacceptableReasons) {
       return true;
@@ -114,6 +101,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public ConfigChangeResult applyConfigurationDelete(
         TestChildCfg configuration) {
       return new ConfigChangeResult(ResultCode.SUCCESS, false);
@@ -124,6 +112,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public boolean isConfigurationDeleteAcceptable(TestChildCfg configuration,
         List<Message> unacceptableReasons) {
       return true;
@@ -134,10 +123,10 @@
 
   private static final String TEST_CHILD_6_DN = "cn=test child 6,cn=test children,cn=test parent 1,cn=test parents,cn=config";
 
-  // The name of the test connection handler.
+  /** The name of the test connection handler. */
   private static final String TEST_CONNECTION_HANDLER_NAME = "Test Connection Handler";
 
-  // Test child 1 LDIF.
+  /** Test child 1 LDIF. */
   private static final String[] TEST_CHILD_1 = new String[] {
       "dn: cn=test child 1,cn=test children,cn=test parent 1,cn=test parents,cn=config",
       "objectclass: top",
@@ -149,7 +138,7 @@
       "ds-cfg-conflict-behavior: virtual-overrides-real"
   };
 
-  // Test child 2 LDIF.
+  /** Test child 2 LDIF. */
   private static final String[] TEST_CHILD_2 = new String[] {
       "dn: cn=test child 2,cn=test children,cn=test parent 1,cn=test parents,cn=config",
       "objectclass: top",
@@ -162,7 +151,7 @@
       "ds-cfg-rotation-policy: cn=LDAP Connection Handler, cn=connection handlers, cn=config"
   };
 
-  // Test child 3 LDIF (invalid reference).
+  /** Test child 3 LDIF (invalid reference). */
   private static final String[] TEST_CHILD_3 = new String[] {
       "dn: cn=test child 3,cn=test children,cn=test parent 1,cn=test parents,cn=config",
       "objectclass: top",
@@ -175,7 +164,7 @@
       "ds-cfg-rotation-policy: cn=LDAP Connection Handler, cn=bad rdn, cn=config"
   };
 
-  // Test child 4 LDIF.
+  /** Test child 4 LDIF. */
   private static final String[] TEST_CHILD_4 = new String[] {
       "dn: cn=test child 4,cn=test children,cn=test parent 1,cn=test parents,cn=config",
       "objectclass: top",
@@ -189,7 +178,7 @@
       "ds-cfg-rotation-policy: cn=LDAPS Connection Handler, cn=connection handlers, cn=config"
   };
 
-  // Test child 5 LDIF.
+  /** Test child 5 LDIF. */
   private static final String[] TEST_CHILD_5 = new String[] {
       "dn: cn=test child 5,cn=test children,cn=test parent 1,cn=test parents,cn=config",
       "objectclass: top",
@@ -204,7 +193,7 @@
       "ds-cfg-rotation-policy: cn=LDAP Connection Handler, cn=connection handlers, cn=config"
   };
 
-  // Test child 6 LDIF.
+  /** Test child 6 LDIF. */
   private static final String[] TEST_CHILD_6 = new String[] {
       "dn: cn=test child 6,cn=test children,cn=test parent 1,cn=test parents,cn=config",
       "objectclass: top",
@@ -218,7 +207,7 @@
           + ", cn=connection handlers, cn=config"
   };
 
-  // Test child 7 LDIF.
+  /** Test child 7 LDIF. */
   private static final String[] TEST_CHILD_7 = new String[] {
       "dn: cn=test child 7,cn=test children,cn=test parent 1,cn=test parents,cn=config",
       "objectclass: top",
@@ -232,7 +221,7 @@
           + ", cn=connection handlers, cn=config"
   };
 
-  // Test LDIF.
+  /** Test LDIF. */
   private static final String[] TEST_LDIF = new String[] {
       // Base entries.
       "dn: cn=test parents,cn=config",
@@ -258,18 +247,21 @@
       ""
   };
 
-  // JNDI LDAP context.
+  /** JNDI LDAP context. */
   private JNDIDirContextAdaptor adaptor = null;
 
-  // The saved test child configuration "aggregation-property"
-  // property definition.
+  /**
+   * The saved test child configuration "aggregation-property" property
+   * definition.
+   */
   private AggregationPropertyDefinition<ConnectionHandlerCfgClient, ConnectionHandlerCfg> aggregationPropertyDefinitionDefault = null;
 
-  // An aggregation where the target must be enabled if the source is
-  // enabled.
+  /**
+   * An aggregation where the target must be enabled if the source is enabled.
+   */
   private AggregationPropertyDefinition<ConnectionHandlerCfgClient, ConnectionHandlerCfg> aggregationPropertyDefinitionTargetAndSourceMustBeEnabled = null;
 
-  // An aggregation where the target must be enabled.
+  /** An aggregation where the target must be enabled. */
   private AggregationPropertyDefinition<ConnectionHandlerCfgClient, ConnectionHandlerCfg> aggregationPropertyDefinitionTargetMustBeEnabled = null;
 
 
@@ -887,7 +879,7 @@
 
 
 
-  // Assert that the values of child 1 are correct.
+  /** Assert that the values of child 1 are correct. */
   private void assertChild1(TestChildCfg child) {
     Assert.assertEquals(child.getMandatoryClassProperty(),
         "org.opends.server.extensions.UserDefinedVirtualAttributeProvider");
@@ -898,7 +890,7 @@
 
 
 
-  // Assert that the values of child 2 are correct.
+  /** Assert that the values of child 2 are correct. */
   private void assertChild2(TestChildCfg child) {
     Assert.assertEquals(child.getMandatoryClassProperty(),
         "org.opends.server.extensions.UserDefinedVirtualAttributeProvider");
@@ -915,7 +907,7 @@
 
 
 
-  // Assert that the values of child 4 are correct.
+  /** Assert that the values of child 4 are correct. */
   private void assertChild4(TestChildCfg child) {
     Assert.assertEquals(child.getMandatoryClassProperty(),
         "org.opends.server.extensions.UserDefinedVirtualAttributeProvider");
@@ -927,7 +919,7 @@
 
 
 
-  // Asserts that the actual set of DNs contains the expected values.
+  /** Asserts that the actual set of DNs contains the expected values. */
   private void assertSetEquals(SortedSet<String> actual, String... expected) {
     SortedSet<String> values = new TreeSet<String>(TestChildCfgDefn
         .getInstance().getAggregationPropertyPropertyDefinition());
@@ -941,11 +933,9 @@
 
 
 
-  // Creates a test connection handler for testing.
+  /** Creates a test connection handler for testing. */
   private void createConnectionHandler(boolean enabled) throws Exception {
-    ServerSocket freeSocket = TestCaseUtils.bindFreePort();
-    int freePort = freeSocket.getLocalPort();
-    freeSocket.close();
+    int freePort = TestCaseUtils.findFreePort();
 
     RootCfgClient root = TestCaseUtils.getRootConfiguration();
     LDAPConnectionHandlerCfgClient client = root.createConnectionHandler(
@@ -958,7 +948,7 @@
 
 
 
-  // Deletes the test connection handler after testing.
+  /** Deletes the test connection handler after testing. */
   private void deleteConnectionHandler() throws Exception {
     RootCfgClient root = TestCaseUtils.getRootConfiguration();
     root.removeConnectionHandler(TEST_CONNECTION_HANDLER_NAME);
@@ -966,14 +956,14 @@
 
 
 
-  // Deletes the named sub-tree.
+  /** Deletes the named sub-tree. */
   private void deleteSubtree(String dn) throws Exception {
     getAdaptor().deleteSubtree(new LdapName(dn));
   }
 
 
 
-  // Gets the JNDI connection for the test server instance.
+  /** Gets the JNDI connection for the test server instance. */
   private synchronized JNDIDirContextAdaptor getAdaptor() throws Exception {
     if (adaptor == null) {
       adaptor = JNDIDirContextAdaptor.simpleSSLBind("127.0.0.1", TestCaseUtils
@@ -984,14 +974,12 @@
 
 
 
-  // Gets the named parent configuration.
+  /** Gets the named parent configuration. */
   private TestParentCfg getParent(String name) throws IllegalArgumentException,
       ConfigException {
     ServerManagementContext ctx = ServerManagementContext.getInstance();
     ServerManagedObject<RootCfg> root = ctx.getRootConfigurationManagedObject();
-    TestParentCfg parent = root.getChild(
-        TestCfg.getTestOneToManyParentRelationDefinition(), name)
-        .getConfiguration();
-    return parent;
+    return root.getChild(TestCfg.getTestOneToManyParentRelationDefinition(),
+        name).getConfiguration();
   }
 }
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/extensions/LDAPPassThroughAuthenticationPolicyTestCase.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/extensions/LDAPPassThroughAuthenticationPolicyTestCase.java
index 801995d..51bc2e5 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/extensions/LDAPPassThroughAuthenticationPolicyTestCase.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/extensions/LDAPPassThroughAuthenticationPolicyTestCase.java
@@ -22,14 +22,12 @@
  * CDDL HEADER END
  *
  *
- *      Copyright 2011 ForgeRock AS.
+ *      Copyright 2011-2013 ForgeRock AS.
  */
 package org.opends.server.extensions;
 
-
-
-import static org.opends.server.extensions.LDAPPassThroughAuthenticationPolicyFactory.isServiceError;
-import static org.opends.server.protocols.ldap.LDAPConstants.OID_NOTICE_OF_DISCONNECTION;
+import static org.opends.server.extensions.LDAPPassThroughAuthenticationPolicyFactory.*;
+import static org.opends.server.protocols.ldap.LDAPConstants.*;
 import static org.testng.Assert.*;
 
 import java.io.IOException;
@@ -66,11 +64,10 @@
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
-
-
 /**
  * Test LDAP authentication mappingPolicy implementation.
  */
+@SuppressWarnings("javadoc")
 public class LDAPPassThroughAuthenticationPolicyTestCase extends
     ExtensionsTestCase
 {
@@ -79,15 +76,11 @@
   {
     private final GetConnectionEvent getConnectionEvent;
 
-
-
     CloseEvent(final GetConnectionEvent getConnectionEvent)
     {
       this.getConnectionEvent = getConnectionEvent;
     }
 
-
-
     /**
      * {@inheritDoc}
      */
@@ -99,10 +92,7 @@
         final CloseEvent closeEvent = (CloseEvent) event;
         return getConnectionEvent.matchesEvent(closeEvent.getConnectionEvent);
       }
-      else
-      {
-        return false;
-      }
+      return false;
     }
 
 
@@ -133,10 +123,7 @@
       {
         return matchesEvent((Event<?>) obj);
       }
-      else
-      {
-        return false;
-      }
+      return false;
     }
 
 
@@ -155,12 +142,8 @@
       return null;
     }
 
-
-
     abstract boolean matchesEvent(Event<?> event);
 
-
-
     abstract StringBuilder toString(StringBuilder builder);
   }
 
@@ -171,15 +154,11 @@
     private final GetLDAPConnectionFactoryEvent fevent;
     private final ResultCode resultCode;
 
-
-
     GetConnectionEvent(final GetLDAPConnectionFactoryEvent fevent)
     {
       this(fevent, ResultCode.SUCCESS);
     }
 
-
-
     GetConnectionEvent(final GetLDAPConnectionFactoryEvent fevent,
         final ResultCode resultCode)
     {
@@ -187,8 +166,6 @@
       this.resultCode = resultCode;
     }
 
-
-
     /**
      * {@inheritDoc}
      */
@@ -200,10 +177,7 @@
         return new DirectoryException(resultCode,
             resultCode.getResultCodeName());
       }
-      else
-      {
-        return null;
-      }
+      return null;
     }
 
 
@@ -219,10 +193,7 @@
         final GetConnectionEvent getConnectionEvent = (GetConnectionEvent) event;
         return fevent.matchesEvent(getConnectionEvent.fevent);
       }
-      else
-      {
-        return false;
-      }
+      return false;
     }
 
 
@@ -272,10 +243,7 @@
         return hostPort.equals(providerEvent.hostPort)
             && options == providerEvent.options;
       }
-      else
-      {
-        return false;
-      }
+      return false;
     }
 
 
@@ -389,6 +357,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public void close()
     {
       // Nothing to do.
@@ -726,6 +695,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public String getMappedSearchBindPasswordEnvironmentVariable()
     {
       return mappedSearchBindPasswordEnvVar;
@@ -736,6 +706,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public String getMappedSearchBindPasswordFile()
     {
       return mappedSearchBindPasswordFile;
@@ -746,6 +717,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public String getMappedSearchBindPasswordProperty()
     {
       return mappedSearchBindPasswordProperty;
@@ -756,6 +728,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public long getCachedPasswordTTL()
     {
       return 86400;
@@ -766,6 +739,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public String getCachedPasswordStorageScheme()
     {
       return "Salted SHA-1";
@@ -776,6 +750,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public DN getCachedPasswordStorageSchemeDN()
     {
       try
@@ -793,6 +768,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public boolean isUsePasswordCaching()
     {
       return usePasswordCaching;
@@ -818,6 +794,7 @@
 
 
 
+      @Override
       public boolean cancel(final boolean mayInterruptIfRunning)
       {
         monitorRunnables.remove(this);
@@ -826,6 +803,7 @@
 
 
 
+      @Override
       public int compareTo(final Delayed o)
       {
         return 0;
@@ -833,6 +811,7 @@
 
 
 
+      @Override
       public Void get() throws InterruptedException, ExecutionException
       {
         return null;
@@ -840,6 +819,7 @@
 
 
 
+      @Override
       public Void get(final long timeout, final TimeUnit unit)
           throws InterruptedException, ExecutionException, TimeoutException
       {
@@ -848,6 +828,7 @@
 
 
 
+      @Override
       public long getDelay(final TimeUnit unit)
       {
         return 0;
@@ -855,6 +836,7 @@
 
 
 
+      @Override
       public boolean isCancelled()
       {
         return false;
@@ -862,6 +844,7 @@
 
 
 
+      @Override
       public boolean isDone()
       {
         return false;
@@ -1054,6 +1037,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public ScheduledExecutorService getScheduledExecutorService()
     {
       return mockScheduler;
@@ -1064,6 +1048,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public String getCurrentTime()
     {
       return currentTime;
@@ -1074,6 +1059,7 @@
     /**
      * {@inheritDoc}
      */
+    @Override
     public long getCurrentTimeMS()
     {
       try
@@ -1146,6 +1132,7 @@
     // Waits for an incoming client connection.
     class AcceptAction extends Action
     {
+      @Override
       void run() throws Exception
       {
         accept();
@@ -1175,6 +1162,7 @@
 
 
 
+      @Override
       void run() throws Exception
       {
         latch.await();
@@ -1303,6 +1291,7 @@
         /**
          * {@inheritDoc}
          */
+        @Override
         public void run()
         {
           for (final Action action : actions)
@@ -1318,28 +1307,8 @@
             }
           }
 
-          if (socket != null)
-          {
-            try
-            {
-              socket.close();
-            }
-            catch (final IOException ignored)
-            {
-              // Ignore
-            }
-          }
-          if (serverSocket != null)
-          {
-            try
-            {
-              serverSocket.close();
-            }
-            catch (final IOException ignored)
-            {
-              // Ignore
-            }
-          }
+          StaticUtils.close(serverSocket);
+          StaticUtils.close(socket);
 
           // Release test thread.
           stopLatch.countDown();
@@ -1508,10 +1477,7 @@
             && scope.equals(searchEvent.scope)
             && filter.equals(searchEvent.filter);
       }
-      else
-      {
-        return false;
-      }
+      return false;
     }
 
 
@@ -1577,10 +1543,7 @@
         return new DirectoryException(resultCode,
             resultCode.getResultCodeName());
       }
-      else
-      {
-        return null;
-      }
+      return null;
     }
 
 
@@ -1598,10 +1561,7 @@
             && username.equals(simpleBindEvent.username)
             && password.equals(simpleBindEvent.password);
       }
-      else
-      {
-        return false;
-      }
+      return false;
     }
 
 
@@ -2433,7 +2393,7 @@
         .withConnectionTimeout(500);
 
     // Mock server.
-    final MockServer server = mockServer(cfg).thenAccept().thenBlock().start();
+    final MockServer server = mockServer().thenAccept().thenBlock().start();
 
     // Test connect and close.
     final LDAPConnectionFactory factory = new LDAPConnectionFactory(
@@ -2453,10 +2413,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.unblock();
       server.stop();
     }
@@ -2478,7 +2435,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg).thenAccept()
+    final MockServer server = mockServer().thenAccept()
         .thenReceive(1, newBindRequest(searchBindDNString, userPassword))
         .thenClose().start();
 
@@ -2500,10 +2457,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -2525,7 +2479,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1, newBindRequest(searchBindDNString, userPassword))
         .thenSend(0 /* disconnect ID */,
@@ -2549,10 +2503,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -2574,7 +2525,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg).thenAccept()
+    final MockServer server = mockServer().thenAccept()
         .thenReceive(1, newBindRequest(searchBindDNString, userPassword))
         .thenSend(1, newBindResult(ResultCode.INVALID_CREDENTIALS)).start();
 
@@ -2596,10 +2547,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -2620,7 +2568,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg).thenAccept()
+    final MockServer server = mockServer().thenAccept()
         .thenReceive(1, newBindRequest(searchBindDNString, userPassword))
         .thenSend(1, newBindResult(ResultCode.UNAVAILABLE)).start();
 
@@ -2641,10 +2589,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -2664,7 +2609,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg).thenAccept()
+    final MockServer server = mockServer().thenAccept()
         .thenReceive(1, newBindRequest(searchBindDNString, userPassword))
         .thenSend(1, newBindResult(ResultCode.SUCCESS)).start();
 
@@ -2680,10 +2625,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -2703,7 +2645,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg).thenAccept()
+    final MockServer server = mockServer().thenAccept()
         .thenReceive(1, new UnbindRequestProtocolOp()).thenClose().start();
 
     // Test connect and close.
@@ -2732,12 +2674,7 @@
   @Test(enabled = true)
   public void testLDAPConnectionFactoryConnectPortNotInUse() throws Exception
   {
-    // Grab an unused port.
-    final ServerSocket socket = TestCaseUtils.bindFreePort();
-    final int port = socket.getLocalPort();
-
-    // FIXME: will it matter if the port is left in TIME_WAIT?
-    socket.close();
+    final int port = TestCaseUtils.findFreePort();
 
     // Mock configuration.
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
@@ -2758,10 +2695,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
     }
   }
 
@@ -2796,10 +2730,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
     }
   }
 
@@ -2820,7 +2751,7 @@
         .withConnectionTimeout(500);
 
     // Mock server.
-    final MockServer server = mockServer(cfg).thenAccept().thenBlock().start();
+    final MockServer server = mockServer().thenAccept().thenBlock().start();
 
     // Test connect and close.
     final LDAPConnectionFactory factory = new LDAPConnectionFactory(
@@ -2840,10 +2771,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.unblock();
       server.stop();
     }
@@ -2866,7 +2794,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1,
             newSearchRequest(searchBindDNString, "(uid=aduser)", cfg))
@@ -2890,10 +2818,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -2915,7 +2840,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1,
             newSearchRequest(searchBindDNString, "(uid=aduser)", cfg))
@@ -2940,10 +2865,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -2964,7 +2886,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1,
             newSearchRequest(searchBindDNString, "(uid=aduser)", cfg))
@@ -2988,10 +2910,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -3012,7 +2931,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1,
             newSearchRequest(searchBindDNString, "(uid=aduser)", cfg))
@@ -3036,10 +2955,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -3061,7 +2977,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1,
             newSearchRequest(searchBindDNString, "(uid=aduser)", cfg))
@@ -3086,10 +3002,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -3109,7 +3022,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1,
             newSearchRequest(searchBindDNString, "(uid=aduser)", cfg))
@@ -3130,10 +3043,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -3155,7 +3065,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1,
             newSearchRequest(searchBindDNString, "(uid=aduser)", cfg))
@@ -3180,10 +3090,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -3204,7 +3111,7 @@
     final LDAPPassThroughAuthenticationPolicyCfg cfg = mockCfg();
 
     // Mock server.
-    final MockServer server = mockServer(cfg)
+    final MockServer server = mockServer()
         .thenAccept()
         .thenReceive(1,
             newSearchRequest(searchBindDNString, "(uid=aduser)", cfg))
@@ -3230,10 +3137,7 @@
     }
     finally
     {
-      if (connection != null)
-      {
-        connection.close();
-      }
+      StaticUtils.close(connection);
       server.stop();
     }
   }
@@ -4472,8 +4376,7 @@
 
 
 
-  MockServer mockServer(final LDAPPassThroughAuthenticationPolicyCfg cfg)
-      throws IOException
+  MockServer mockServer() throws IOException
   {
     final ServerSocket serverSocket = TestCaseUtils.bindFreePort();
     return new MockServer(serverSocket);
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/jmx/JmxConnectTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/jmx/JmxConnectTest.java
index da3fa3f..fc47267 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/jmx/JmxConnectTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/jmx/JmxConnectTest.java
@@ -23,10 +23,11 @@
  *
  *
  *      Copyright 2006-2008 Sun Microsystems, Inc.
+ *      Portions copyright 2013 ForgeRock AS
  */
 package org.opends.server.protocols.jmx;
 
-
+import static org.testng.Assert.*;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -37,17 +38,16 @@
 import java.security.KeyStore;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Set;
+import java.util.Map;
 
 import javax.management.Attribute;
 import javax.management.AttributeNotFoundException;
 import javax.management.MBeanServerConnection;
 import javax.management.ObjectName;
-import javax.net.ssl.TrustManager;
 import javax.net.ssl.TrustManagerFactory;
 
-import org.opends.server.TestCaseUtils;
 import org.opends.messages.Message;
+import org.opends.server.TestCaseUtils;
 import org.opends.server.admin.server.AdminTestCaseUtils;
 import org.opends.server.admin.std.meta.JMXConnectionHandlerCfgDefn;
 import org.opends.server.admin.std.server.JMXConnectionHandlerCfg;
@@ -66,27 +66,25 @@
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
-import static org.testng.Assert.*;
-
-
-
 /**
- * A simple test for : - JMX connection establishment withou using SSL -
+ * A simple test for : - JMX connection establishment without using SSL -
  * JMX get and set - configuration change
  */
+@SuppressWarnings("javadoc")
 public class JmxConnectTest extends JmxTestCase {
-  
+
   /**
    * Set up the environment for performing the tests in this suite.
-   * 
+   *
    * @throws Exception
    *           If the environment could not be set up.
    */
+  @Override
   @BeforeClass
   public void setUp() throws Exception
   {
     super.setUp();
-    
+
     TestCaseUtils.addEntries(
         "dn: cn=Privileged User,o=test",
         "objectClass: top",
@@ -138,11 +136,11 @@
         "ds-pwp-password-policy-dn: cn=Clear UserPassword Policy," +
              "cn=Password Policies,cn=config");
   }
-  
-  
+
+
   /**
    * Clean up the environment after performing the tests in this suite.
-   * 
+   *
    * @throws Exception
    *           If the environment could not be set up.
    */
@@ -155,14 +153,13 @@
     DeleteOperation deleteOperation = conn.processDelete(DN
         .decode("cn=Privileged User,o=test"));
     assertEquals(deleteOperation.getResultCode(), ResultCode.SUCCESS);
-    
+
     deleteOperation = conn.processDelete(DN
         .decode("cn=Unprivileged JMX User,o=test"));
     assertEquals(deleteOperation.getResultCode(), ResultCode.SUCCESS);
-    
   }
-  
-  
+
+
 
   /**
    * Build data for the simpleConnect test.
@@ -198,7 +195,7 @@
       connector.close();
     }
   }
-  
+
   /**
    * Build some data for the simpleGet test.
    */
@@ -259,19 +256,16 @@
     MBeanServerConnection jmxc = connector.getMBeanServerConnection();
     assertNotNull(jmxc);
 
-    Set names = jmxc.queryNames(null, null);
-    names.clear();
+    jmxc.queryNames(null, null).clear();
 
     final String dn = "cn=config";
     final String attribute = "ds-cfg-size-limit";
 
-    Long val = (Long) jmxGet(dn, attribute, jmxc);
-
+    long val = (Long) jmxGet(dn, attribute, jmxc);
     jmxSet(dn, attribute, val + 1, jmxc);
 
-    Long newVal = (Long) jmxGet(dn, attribute, jmxc);
-
-    assertEquals((long) newVal, (long) val + 1);
+    long newVal = (Long) jmxGet(dn, attribute, jmxc);
+    assertEquals(newVal, val + 1);
 
     jmxSet(dn, attribute, val + 1, jmxc);
 
@@ -333,18 +327,15 @@
     assertNotNull(jmxc);
 
     // Disable the "new" connector
-    toggleEnableJmxConnector(connector, newJmxConnectionJmx.getDN(),
-        false);
+    toggleEnableJmxConnector(connector, newJmxConnectionJmx.getDN(), false);
     Thread.sleep(100);
     OpendsJmxConnector jmxcDisabled = connect("cn=Privileged User,o=test",
         "password", serverJmxPort);
     assertNull(jmxcDisabled);
 
-    toggleEnableJmxConnector(connector, newJmxConnectionJmx.getDN(),
-        true);
+    toggleEnableJmxConnector(connector, newJmxConnectionJmx.getDN(), true);
     Thread.sleep(100);
-    jmxcDisabled = connect("cn=Privileged User,o=test", "password",
-        serverJmxPort);
+    jmxcDisabled = connect("cn=Privileged User,o=test", "password", serverJmxPort);
     assertNotNull(jmxcDisabled);
 
     // cleanup client connection
@@ -361,8 +352,6 @@
 
   /**
    * Test changing JMX port through LDAP
-   *
-   * @throws Exception
    */
   @Test(enabled = false)
   public void changePort() throws Exception {
@@ -380,10 +369,8 @@
     connector.close();
     assertNotNull(initJmxPort);
 
-    // change the configuration of the connection handler to use
-    // a free port
-    ServerSocket serverJmxSocket = TestCaseUtils.bindFreePort();
-    int serverJmxPort = serverJmxSocket.getLocalPort();
+    // change the configuration of the connection handler to use a free port
+    int serverJmxPort = TestCaseUtils.findFreePort();
 
     Entry entry = TestCaseUtils
             .makeEntry(
@@ -396,16 +383,14 @@
                 "ds-cfg-enabled: true",
                 "ds-cfg-use-ssl: false", "ds-cfg-listen-port: "
                     + serverJmxPort, "cn: JMX Connection Handler");
-    serverJmxSocket.close();
     configureJmx(entry);
 
     // connect the the JMX service using the new port
-    connector = connect("cn=Privileged User,o=test", "password",
-        serverJmxPort);
+    connector = connect("cn=Privileged User,o=test", "password", serverJmxPort);
     jmxc = connector.getMBeanServerConnection();
     assertNotNull(jmxc);
-    Long val = (Long) jmxGet(dn, attribute, jmxc);
-    assertEquals((long) val, (long) serverJmxPort);
+    long val = (Long) jmxGet(dn, attribute, jmxc);
+    assertEquals(val, serverJmxPort);
     connector.close();
 
     // re-establish the initial configuration of the JMX service
@@ -462,7 +447,7 @@
     OpendsJmxConnector jmxc = sslConnect("cn=Privileged User,o=test",
         "password", initJmxPort);
     assertNotNull(jmxc,"OpendsJmxConnector shouldn't be null");
-    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
+    jmxc.getMBeanServerConnection();
     jmxc.close();
 
     // Before returning the result,
@@ -521,9 +506,9 @@
   /**
    * Connect to the JMX service.
    */
-  private OpendsJmxConnector connect(String user, String password,
-      long jmxPort) throws MalformedURLException, IOException{
-    HashMap<String, Object> env = new HashMap<String, Object>();
+  private OpendsJmxConnector connect(String user, String password, int jmxPort)
+        throws MalformedURLException, IOException {
+    Map<String, Object> env = new HashMap<String, Object>();
 
     // Provide the credentials required by the server to successfully
     // perform user authentication
@@ -542,8 +527,7 @@
     //
     OpendsJmxConnector opendsConnector;
     try {
-      opendsConnector = new OpendsJmxConnector("localhost",
-          (int) jmxPort, env);
+      opendsConnector = new OpendsJmxConnector("localhost", jmxPort, env);
       opendsConnector.connect();
       return opendsConnector;
     } catch (SecurityException e) {
@@ -560,7 +544,7 @@
    */
   private OpendsJmxConnector sslConnect(String user, String password,
       long jmxPort) throws Exception {
-    HashMap<String, Object> env = new HashMap<String, Object>();
+    Map<String, Object> env = new HashMap<String, Object>();
 
     // Provide the credentials required by the server to successfully
     // perform user authentication
@@ -572,18 +556,15 @@
     env.put("jmx.remote.credentials", credentials);
 
     // Provide the Trust manager.
-    KeyStore ks = null;
-    ks = KeyStore.getInstance("JKS");
-    FileInputStream keyStoreFile = new FileInputStream(
-        getJmxKeystorePath());
+    KeyStore ks = KeyStore.getInstance("JKS");
+    FileInputStream keyStoreFile = new FileInputStream(getJmxKeystorePath());
     ks.load(keyStoreFile, "password".toCharArray());
     keyStoreFile.close();
 
     TrustManagerFactory tmf = TrustManagerFactory
         .getInstance(TrustManagerFactory.getDefaultAlgorithm());
     tmf.init(ks);
-    TrustManager tms[] = tmf.getTrustManagers();
-    env.put(JmxConnectionHandler.TRUST_MANAGER_ARRAY_KEY, tms);
+    env.put(JmxConnectionHandler.TRUST_MANAGER_ARRAY_KEY, tmf.getTrustManagers());
 
     // Create an RMI connector client and
     // connect it to the RMI connector server
@@ -594,17 +575,12 @@
       opendsConnector.connect();
       return opendsConnector;
     } catch (Exception e) {
-
       return null;
     }
-
   }
 
 
 
-  /**
-   * @return
-   */
   private String getJmxKeystorePath() {
     return DirectoryServer.getInstanceRoot() + File.separator + "config"
         + File.separator + "server.keystore";
@@ -656,10 +632,11 @@
     try
     {
       Attribute status = (Attribute) mbsc.getAttribute(name, attributeName);
-      if (status == null)
-        return null;
-      else
+      if (status != null)
+      {
         return status.getValue();
+      }
+      return null;
     }
     catch (AttributeNotFoundException anfe)
     {
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/LdapTestCase.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/LdapTestCase.java
index 74b6e00..5bda047 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/LdapTestCase.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/LdapTestCase.java
@@ -23,36 +23,33 @@
  *
  *
  *      Copyright 2006-2008 Sun Microsystems, Inc.
+ *      Portions copyright 2013 ForgeRock AS
  */
 package org.opends.server.protocols.ldap ;
 
-import static org.opends.server.config.ConfigConstants.ATTR_LISTEN_PORT;
+import static org.opends.server.config.ConfigConstants.*;
 
-import org.opends.server.types.Attributes;
-import org.opends.server.types.Entry;
+import java.util.Iterator;
+import java.util.List;
+
 import org.opends.server.DirectoryServerTestCase;
+import org.opends.server.TestCaseUtils;
 import org.opends.server.admin.server.AdminTestCaseUtils;
 import org.opends.server.admin.std.meta.LDAPConnectionHandlerCfgDefn;
 import org.opends.server.admin.std.server.LDAPConnectionHandlerCfg;
 import org.opends.server.config.ConfigException;
 import org.opends.server.types.Attribute;
+import org.opends.server.types.Attributes;
+import org.opends.server.types.Entry;
 import org.testng.annotations.Test;
 
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.util.LinkedList;
-import java.util.ListIterator;
-
 /**
  * An abstract class that all types  unit test should extend.
  */
-
 @Test(groups = { "precommit", "ldap" }, sequential = true)
 public abstract class LdapTestCase extends DirectoryServerTestCase
 {
-	
-	private static String localHost = "127.0.0.1";
-	
+
   /**
    * Determine whether one LDAPAttribute is equal to another.
    * The values of the attribute must be identical and in the same order.
@@ -62,11 +59,11 @@
    */
   static boolean testEqual(LDAPAttribute a1, LDAPAttribute a2)
   {
-    if (!a1.getAttributeType().equals(a2.getAttributeType()))
+    if (a1.getAttributeType().equals(a2.getAttributeType()))
     {
-      return false;
+      return a1.getValues().equals(a2.getValues());
     }
-    return a1.getValues().equals(a2.getValues());
+    return false;
   }
 
   /**
@@ -75,18 +72,17 @@
    * @param list2 The second list of LDAPAttribute.
    * @return true if the first list of LDAPAttribute is equal to the second.
    */
-  static boolean testEqual(LinkedList<LDAPAttribute> list1,
-                           LinkedList<LDAPAttribute> list2)
+  static boolean testEqual(List<LDAPAttribute> list1, List<LDAPAttribute> list2)
   {
-    ListIterator<LDAPAttribute> e1 = list1.listIterator();
-    ListIterator<LDAPAttribute> e2 = list2.listIterator();
+    Iterator<LDAPAttribute> e1 = list1.iterator();
+    Iterator<LDAPAttribute> e2 = list2.iterator();
     while(e1.hasNext() && e2.hasNext()) {
       LDAPAttribute o1 = e1.next();
       LDAPAttribute o2 = e2.next();
-      if (!(o1==null ? o2==null : testEqual(o1, o2)))
+      if (o1 == null ? o2 != null : !testEqual(o1, o2))
         return false;
     }
-    return !(e1.hasNext() || e2.hasNext());
+    return !e1.hasNext() && !e2.hasNext();
   }
 
   /**
@@ -94,41 +90,37 @@
    * @param op The op.
    * @throws Exception If the toString method fails.
    */
-  static void 
-  toString(ProtocolOp op) throws Exception {
+  static void toString(ProtocolOp op) throws Exception
+  {
 	  StringBuilder sb = new StringBuilder();
 	  op.toString(sb);
 	  op.toString(sb, 1);
   }
-  
+
   /**
    * Generate a LDAPConnectionHandler from a entry. The listen port is
    * determined automatically, so no ATTR_LISTEN_PORT should be in the
    * entry.
-   * 
+   *
    * @param handlerEntry The entry to be used to configure the handle.
    * @return Returns the new LDAP connection handler.
    * @throws Exception if the handler cannot be initialized.
    */
-  static LDAPConnectionHandler 
-  getLDAPHandlerInstance(Entry handlerEntry) throws Exception {
-	  ServerSocket serverLdapSocket = new ServerSocket();
-	  serverLdapSocket.setReuseAddress(true);
-	  serverLdapSocket.bind(new InetSocketAddress(localHost, 0));
-	  long serverLdapPort = serverLdapSocket.getLocalPort();
-    serverLdapSocket.close();
-	  Attribute a=Attributes.create(ATTR_LISTEN_PORT, String.valueOf(serverLdapPort));
-	  handlerEntry.addAttribute(a,null);
-    LDAPConnectionHandlerCfg config =
-      getConfiguration(handlerEntry);
+  static LDAPConnectionHandler getLDAPHandlerInstance(Entry handlerEntry)
+      throws Exception
+  {
+    long serverLdapPort = TestCaseUtils.findFreePort();
+    Attribute a = Attributes.create(ATTR_LISTEN_PORT, String.valueOf(serverLdapPort));
+    handlerEntry.addAttribute(a, null);
+    LDAPConnectionHandlerCfg config = getConfiguration(handlerEntry);
     LDAPConnectionHandler handler = new LDAPConnectionHandler();
     handler.initializeConnectionHandler(config);
-	  return handler;
+    return handler;
   }
 
   /**
    * Decode an LDAP connection handler configuration entry.
-   * 
+   *
    * @param handlerEntry
    *          The configuration entry.
    * @return Returns the decoded LDAP connection handler
@@ -139,20 +131,7 @@
   static LDAPConnectionHandlerCfg getConfiguration(
       Entry handlerEntry) throws ConfigException {
     return AdminTestCaseUtils.getConfiguration(
-        LDAPConnectionHandlerCfgDefn
-            .getInstance(), handlerEntry);
+        LDAPConnectionHandlerCfgDefn.getInstance(), handlerEntry);
   }
-  
-  /**
-   * @return A free port number.
-   * @throws Exception
-   *           if socket cannot be created or bound to.
-   */
-static long
-  getFreePort() throws Exception {
-	  ServerSocket serverLdapSocket = new ServerSocket();
-	  serverLdapSocket.setReuseAddress(true);
-	  serverLdapSocket.bind(new InetSocketAddress(localHost, 0));
-	  return serverLdapSocket.getLocalPort();
-  }
+
 }
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/TestLDAPConnectionHandler.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/TestLDAPConnectionHandler.java
index 8382ef1..7a06986 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/TestLDAPConnectionHandler.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/protocols/ldap/TestLDAPConnectionHandler.java
@@ -284,7 +284,7 @@
     GoodHandlerEntry.removeAttribute(rAttr11, null);
     GoodHandlerEntry.removeAttribute(rAttr12, null);
     //Make new AttrTypes with different values
-    long newPort=getFreePort();
+    long newPort = TestCaseUtils.findFreePort();
     Attribute a2=Attributes.create(ATTR_LISTEN_PORT, String.valueOf(newPort));
     //uncomment if want to test listen address
 //    Attribute a3=new Attribute(ATTR_LISTEN_ADDRESS, "localhost");
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ChangeNumberControlPluginTestCase.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ChangeNumberControlPluginTestCase.java
index e839247..7f7a0fd 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ChangeNumberControlPluginTestCase.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ChangeNumberControlPluginTestCase.java
@@ -23,28 +23,29 @@
  *
  *
  *      Copyright 2006-2008 Sun Microsystems, Inc.
+ *      Portions copyright 2013 ForgeRock AS
  */
 package org.opends.server.replication;
 
 import java.io.BufferedReader;
 import java.io.FileOutputStream;
 import java.io.FileReader;
-import java.net.ServerSocket;
+
 import org.opends.server.TestCaseUtils;
-import org.opends.server.replication.ReplicationTestCase;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
 import org.opends.server.tools.LDAPModify;
 import org.opends.server.types.DN;
-import static org.opends.server.util.ServerConstants.*;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-import static org.opends.server.TestCaseUtils.*;
-import static org.opends.messages.ToolMessages.*;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
 
-public class ChangeNumberControlPluginTestCase
-    extends ReplicationTestCase {
+import static org.opends.messages.ToolMessages.*;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.util.ServerConstants.*;
+import static org.testng.Assert.*;
+
+@SuppressWarnings("javadoc")
+public class ChangeNumberControlPluginTestCase extends ReplicationTestCase
+{
 
   /**
    * The port of the replicationServer.
@@ -61,16 +62,14 @@
    * replicationServer.
    */
 
+  @Override
   @BeforeClass(alwaysRun=true)
   public void setUp() throws Exception {
     super.setUp();
 
     baseDn = DN.decode(TEST_ROOT_DN_STRING);
 
-    //  find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replServerPort = socket.getLocalPort();
-    socket.close();
+    replServerPort = TestCaseUtils.findFreePort();
 
     // replication server
     String replServerLdif =
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/DependencyTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/DependencyTest.java
index cc7a7c9..83dd8b9 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/DependencyTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/DependencyTest.java
@@ -23,17 +23,16 @@
  *
  *
  *      Copyright 2007-2010 Sun Microsystems, Inc.
- *      Portions Copyright 2011 ForgeRock AS
+ *      Portions Copyright 2011-2013 ForgeRock AS
  */
 package org.opends.server.replication;
 
-import org.opends.server.util.StaticUtils;
-import java.io.File;
+import static org.opends.server.TestCaseUtils.*;
 import static org.testng.Assert.*;
 
+import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.net.ServerSocket;
 import java.util.LinkedList;
 import java.util.SortedSet;
 import java.util.TreeSet;
@@ -41,30 +40,27 @@
 import org.opends.server.TestCaseUtils;
 import org.opends.server.backends.MemoryBackend;
 import org.opends.server.core.DirectoryServer;
-import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.replication.common.ChangeNumberGenerator;
 import org.opends.server.replication.plugin.DomainFakeCfg;
-import org.opends.server.replication.plugin.MultimasterReplication;
 import org.opends.server.replication.plugin.LDAPReplicationDomain;
+import org.opends.server.replication.plugin.MultimasterReplication;
 import org.opends.server.replication.protocol.AddMsg;
 import org.opends.server.replication.protocol.DeleteMsg;
 import org.opends.server.replication.protocol.ModifyDNMsg;
 import org.opends.server.replication.protocol.ModifyMsg;
 import org.opends.server.replication.server.ReplServerFakeConfiguration;
 import org.opends.server.replication.server.ReplicationServer;
-import org.opends.server.types.AttributeType;
-import org.opends.server.types.AttributeValue;
-import org.opends.server.types.Attributes;
-import org.opends.server.types.DN;
-import org.opends.server.types.Entry;
-import org.testng.annotations.*;
-import static org.opends.server.TestCaseUtils.*;
+import org.opends.server.replication.service.ReplicationBroker;
+import org.opends.server.types.*;
+import org.opends.server.util.StaticUtils;
+import org.testng.annotations.Test;
 
 /**
  * Test that the dependencies are computed correctly when replaying
  * sequences of operations that requires to follow a given order
  * such as : ADD an entry, ADD a children entry.
  */
+@SuppressWarnings("javadoc")
 public class DependencyTest extends ReplicationTestCase
 {
   /**
@@ -87,7 +83,6 @@
    * Then test that the sequence of Delete necessary to remove
    * all those entries is also correctly ordered.
    */
-  @SuppressWarnings("unchecked")
   @Test(enabled=true, groups="slow")
   public void addModDelDependencyTest() throws Exception
   {
@@ -123,10 +118,7 @@
       AttributeType uidType =
         DirectoryServer.getSchema().getAttributeType("entryuuid");
 
-      // find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort = socket.getLocalPort();
-      socket.close();
+      int replServerPort = TestCaseUtils.findFreePort();
 
       ReplServerFakeConfiguration conf =
         new ReplServerFakeConfiguration(replServerPort, "dependencyTestAddModDelDependencyTestDb",
@@ -248,7 +240,6 @@
    * when an entry is renamed to a new dn and then deleted.
    * Disabled: need investigations to fix random failures
    */
-  @SuppressWarnings("unchecked")
   @Test(enabled=false)
   public void moddnDelDependencyTest() throws Exception
   {
@@ -276,10 +267,7 @@
       ChangeNumberGenerator gen = new ChangeNumberGenerator(brokerId, 0L);
       int renamedEntryUuid = 100;
 
-      // find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort = socket.getLocalPort();
-      socket.close();
+      int replServerPort = TestCaseUtils.findFreePort();
 
       ReplServerFakeConfiguration conf =
         new ReplServerFakeConfiguration(replServerPort, "dependencyTestModdnDelDependencyTestDb",
@@ -363,7 +351,6 @@
       if (domain != null)
         MultimasterReplication.deleteDomain(baseDn);
     }
-
   }
 
 
@@ -403,7 +390,6 @@
    * has been added.
    * To increase the risks of failures a loop of add/del/add is done.
    */
-  @SuppressWarnings("unchecked")
   @Test(enabled=true, groups="slow")
   public void addDelAddDependencyTest() throws Exception
   {
@@ -426,10 +412,7 @@
       AttributeType uidType =
         DirectoryServer.getSchema().getAttributeType("entryuuid");
 
-      // find a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort = socket.getLocalPort();
-      socket.close();
+      int replServerPort = TestCaseUtils.findFreePort();
 
       ReplServerFakeConfiguration conf =
         new ReplServerFakeConfiguration(replServerPort, "dependencyTestAddDelAddDependencyTestDb", 0,
@@ -533,7 +516,6 @@
    * Check that the dependency of moddn operation are working by
    * issuing a set of Add operation followed by a modrdn of the added entry.
    */
-  @SuppressWarnings("unchecked")
   @Test(enabled=true, groups="slow")
   public void addModdnDependencyTest() throws Exception
   {
@@ -557,10 +539,7 @@
       AttributeType uidType =
         DirectoryServer.getSchema().getAttributeType("entryuuid");
 
-      // find a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort = socket.getLocalPort();
-      socket.close();
+      int replServerPort = TestCaseUtils.findFreePort();
 
       ReplServerFakeConfiguration conf =
         new ReplServerFakeConfiguration(replServerPort, "dependencyTestAddModdnDependencyTestDb", 0,
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/GenerationIdTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/GenerationIdTest.java
index d4bce6a..a2f214f 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/GenerationIdTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/GenerationIdTest.java
@@ -51,17 +51,14 @@
 import org.testng.annotations.Test;
 
 import java.io.File;
-import java.net.ServerSocket;
 import java.net.SocketException;
 import java.net.SocketTimeoutException;
 import java.util.*;
 
-import static org.opends.server.TestCaseUtils.TEST_BACKEND_ID;
-import static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
-import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
+import static org.opends.server.util.StaticUtils.*;
 import static org.testng.Assert.*;
 
 /**
@@ -72,12 +69,11 @@
  *
  * - testMultiRS : tests generation ID propagation with more than one
  *   Replication server.
- *
  */
-
+@SuppressWarnings("javadoc")
 public class GenerationIdTest extends ReplicationTestCase
 {
-  // The tracer object for the debug logger
+  /** The tracer object for the debug logger */
   private static final DebugTracer TRACER = getTracer();
 
   private static final String baseDnStr = TEST_ROOT_DN_STRING;
@@ -188,7 +184,7 @@
         "ds-task-initialize-replica-server-id: " + server2ID);
   }
 
-  // Tests that entries have been written in the db
+  /** Tests that entries have been written in the db */
   private int testEntriesInDb()
   {
     debugInfo("TestEntriesInDb");
@@ -235,7 +231,7 @@
     return found;
   }
 
-  /*
+  /**
    * Creates entries necessary to the test.
    */
   private String[] newLDIFEntries()
@@ -291,7 +287,9 @@
         msg = broker.receive();
 
         if (msg == null)
+        {
           break;
+        }
 
         if (msg instanceof InitializeTargetMsg)
         {
@@ -312,8 +310,7 @@
         else if (msg instanceof ErrorMsg)
         {
           ErrorMsg em = (ErrorMsg)msg;
-          debugInfo("Broker " + serverID + " receives ERROR "
-              + em.toString());
+          debugInfo("Broker " + serverID + " receives ERROR " + em);
           break;
         }
         else
@@ -416,8 +413,10 @@
       {
         doToco =
           LDAPReplicationDomain.retrievesReplicationDomain(baseDn);
-        if ((doToco!=null) && (doToco.isConnected()))
+        if (doToco != null && doToco.isConnected())
+        {
           break;
+        }
         Thread.sleep(waitCo * 200);
         waitCo++;
       }
@@ -432,7 +431,7 @@
     }
   }
 
-  /*
+  /**
    * Disconnect DS from the replicationServer
    */
   private void disconnectFromReplServer(int changelogID)
@@ -487,22 +486,11 @@
     }
   }
 
-  private int getChangelogPort(int changelogID)
+  private int getChangelogPort(int changelogID) throws Exception
   {
     if (replServerPort[changelogID] == 0)
     {
-      try
-      {
-        // Find  a free port for the replicationServer
-        ServerSocket socket = TestCaseUtils.bindFreePort();
-        replServerPort[changelogID] = socket.getLocalPort();
-        socket.close();
-      }
-      catch(Exception e)
-      {
-        fail("Cannot retrieve a free port for replication server."
-            + e.getMessage());
-      }
+      replServerPort[changelogID] = TestCaseUtils.findFreePort();
     }
     return replServerPort[changelogID];
   }
@@ -648,9 +636,9 @@
         personWithUUIDEntry.getAttributes(), new ArrayList<Attribute>());
   }
 
-  /*
-   * Check that the expected number of changes are in the replication
-   * server database.
+  /**
+   * Check that the expected number of changes are in the replication server
+   * database.
    */
   private void checkChangelogSize(int expectedCount)
   {
@@ -676,7 +664,6 @@
     }
     catch(Exception e)
     {
-
     }
   }
 
@@ -734,7 +721,7 @@
       debugInfo(testCase + " ** TEST ** Non empty backend");
 
       debugInfo(testCase + " Adding test entries to DS");
-      this.addTestEntriesToDB(updatedEntries);
+      addTestEntriesToDB(updatedEntries);
 
       debugInfo(testCase + " Configuring DS1 to replicate to RS1(" + changelog1ID + ") on a non empty backend");
       connectServer1ToChangelog(changelog1ID);
@@ -795,7 +782,7 @@
 
       // Now create a change that must be replicated
       String ent1[] = { createEntry(UUID.randomUUID()) };
-      this.addTestEntriesToDB(ent1);
+      addTestEntriesToDB(ent1);
 
       // Verify that RS1 does contain the change related to this ADD.
       Thread.sleep(500);
@@ -943,7 +930,7 @@
 
       debugInfo("Add entries to DS1, update should not be sent to DS2 and DS3 that are in bad gen id");
       String[] ent3 = { createEntry(UUID.randomUUID()) };
-      this.addTestEntriesToDB(ent3);
+      addTestEntriesToDB(ent3);
 
       debugInfo("RS1 must have stored that update.");
       Thread.sleep(500);
@@ -990,7 +977,7 @@
       // Signal that we just entered the full update status
       broker2.signalStatusChange(ServerStatus.FULL_UPDATE_STATUS);
 
-      int receivedEntriesNb = this.receiveImport(broker2, server2ID, null);
+      int receivedEntriesNb = receiveImport(broker2, server2ID, null);
       debugInfo("broker2 has been initialized from DS with #entries=" + receivedEntriesNb);
 
       broker2.stop();
@@ -1168,7 +1155,7 @@
       assertEquals(replServer3.getGenerationId(baseDn.toNormalizedString()), -1);
 
       debugInfo("Add entries to DS");
-      this.addTestEntriesToDB(updatedEntries);
+      addTestEntriesToDB(updatedEntries);
 
       debugInfo("Connecting DS to replServer2");
       connectServer1ToChangelog(changelog2ID);
@@ -1407,7 +1394,7 @@
       genId = readGenIdFromSuffixRootEntry();
       assertEquals(genId,-1);
 
-      this.addTestEntriesToDB(updatedEntries);
+      addTestEntriesToDB(updatedEntries);
 
       debugInfo(testCase + " Expect genId attribute to be retrievable");
       genId = readGenIdFromSuffixRootEntry();
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/InitOnLineTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/InitOnLineTest.java
index c76ad6e..68601a4 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/InitOnLineTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/InitOnLineTest.java
@@ -27,60 +27,36 @@
  */
 package org.opends.server.replication;
 
-import java.io.File;
-import static org.opends.server.config.ConfigConstants.ATTR_TASK_COMPLETION_TIME;
-import static org.opends.server.config.ConfigConstants.ATTR_TASK_INITIALIZE_DONE;
-import static org.opends.server.config.ConfigConstants.ATTR_TASK_INITIALIZE_LEFT;
-import static org.opends.server.config.ConfigConstants.ATTR_TASK_LOG_MESSAGES;
-import static org.opends.server.config.ConfigConstants.ATTR_TASK_STATE;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
 import static org.opends.messages.ReplicationMessages.*;
 import static org.opends.messages.TaskMessages.*;
-import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
+import static org.opends.server.config.ConfigConstants.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
+import static org.opends.server.util.StaticUtils.*;
+import static org.testng.Assert.*;
 
-import java.net.ServerSocket;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import java.util.UUID;
+import java.io.File;
 import java.net.SocketTimeoutException;
+import java.util.*;
 
+import org.opends.messages.Category;
+import org.opends.messages.Message;
+import org.opends.messages.Severity;
 import org.opends.server.TestCaseUtils;
 import org.opends.server.backends.task.TaskState;
 import org.opends.server.core.AddOperationBasis;
 import org.opends.server.core.DirectoryServer;
 import org.opends.server.loggers.debug.DebugTracer;
-import org.opends.messages.Category;
-import org.opends.messages.Message;
-import org.opends.messages.Severity;
 import org.opends.server.protocols.internal.InternalClientConnection;
 import org.opends.server.protocols.internal.InternalSearchOperation;
-import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.replication.common.ServerStatus;
 import org.opends.server.replication.plugin.LDAPReplicationDomain;
-import org.opends.server.replication.protocol.DoneMsg;
-import org.opends.server.replication.protocol.EntryMsg;
-import org.opends.server.replication.protocol.ErrorMsg;
-import org.opends.server.replication.protocol.InitializeRequestMsg;
-import org.opends.server.replication.protocol.InitializeTargetMsg;
-import org.opends.server.replication.protocol.ReplicationMsg;
-import org.opends.server.replication.protocol.RoutableMsg;
+import org.opends.server.replication.protocol.*;
 import org.opends.server.replication.server.ReplServerFakeConfiguration;
 import org.opends.server.replication.server.ReplicationServer;
+import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.schema.DirectoryStringSyntax;
-import org.opends.server.types.AttributeType;
-import org.opends.server.types.DN;
-import org.opends.server.types.Entry;
-import org.opends.server.types.ResultCode;
-import org.opends.server.types.SearchFilter;
-import org.opends.server.types.SearchScope;
+import org.opends.server.types.*;
 import org.opends.server.util.Base64;
 import org.opends.server.util.StaticUtils;
 import org.testng.annotations.AfterClass;
@@ -107,7 +83,7 @@
  * InitializeTargetConfigErrors : Tests configuration errors of the
  * InitializeTarget task
  */
-
+@SuppressWarnings("javadoc")
 public class InitOnLineTest extends ReplicationTestCase
  {
   /**
@@ -708,22 +684,11 @@
     }
   }
 
-  private int getChangelogPort(int changelogID)
+  private int getChangelogPort(int changelogID) throws Exception
   {
     if (replServerPort[changelogID] == 0)
     {
-      try
-      {
-        // Find  a free port for the replicationServer
-        ServerSocket socket = TestCaseUtils.bindFreePort();
-        replServerPort[changelogID] = socket.getLocalPort();
-        socket.close();
-      }
-      catch(Exception e)
-      {
-        fail("Cannot retrieve a free port for replication server."
-          + e.getMessage());
-      }
+      replServerPort[changelogID] = TestCaseUtils.findFreePort();
     }
     return replServerPort[changelogID];
   }
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ProtocolWindowTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ProtocolWindowTest.java
index 22e765d..d2a2a46 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ProtocolWindowTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ProtocolWindowTest.java
@@ -25,21 +25,17 @@
  *      Copyright 2006-2009 Sun Microsystems, Inc.
  *      Portions copyright 2013 ForgeRock AS.
  */
-
 package org.opends.server.replication;
 
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.testng.Assert.*;
 
-import org.opends.server.replication.service.ReplicationBroker;
-
-import java.net.ServerSocket;
 import java.net.SocketTimeoutException;
 import java.util.Iterator;
 import java.util.List;
-
 import java.util.NoSuchElementException;
+
 import org.opends.messages.Category;
 import org.opends.messages.Message;
 import org.opends.messages.Severity;
@@ -55,18 +51,17 @@
 import org.opends.server.replication.protocol.ReplicationMsg;
 import org.opends.server.replication.server.ReplServerFakeConfiguration;
 import org.opends.server.replication.server.ReplicationServer;
+import org.opends.server.replication.service.ReplicationBroker;
+import org.opends.server.types.*;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
-import org.opends.server.types.*;
-
-import static org.opends.server.TestCaseUtils.*;
-import static org.testng.Assert.assertNotNull;
 
 /**
  * Test the constructors, encoders and decoders of the Replication AckMsg,
  * ModifyMsg, ModifyDnMsg, AddMsg and Delete MSG
  */
+@SuppressWarnings("javadoc")
 public class ProtocolWindowTest extends ReplicationTestCase
 {
   private static final int WINDOW_SIZE = 10;
@@ -79,7 +74,7 @@
   private int replServerPort;
 
 
-  // the base DN used for this test
+  /** the base DN used for this test */
   private DN baseDn;
   private ReplicationServer replicationServer;
 
@@ -298,10 +293,7 @@
 
     baseDn = DN.decode(TEST_ROOT_DN_STRING);
 
-    // find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replServerPort = socket.getLocalPort();
-    socket.close();
+    replServerPort = TestCaseUtils.findFreePort();
 
     // configure the replication Server.
     replicationServer = new ReplicationServer(new ReplServerFakeConfiguration(
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReSyncTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReSyncTest.java
index 13f0664..bd1c796 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReSyncTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReSyncTest.java
@@ -23,13 +23,15 @@
  *
  *
  *      Copyright 2007-2009 Sun Microsystems, Inc.
+ *      Portions copyright 2013 ForgeRock AS
  */
 package org.opends.server.replication;
 
-import static org.testng.Assert.fail;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
+import static org.testng.Assert.*;
 
 import java.io.File;
-import java.net.ServerSocket;
 import java.util.UUID;
 
 import org.opends.messages.Category;
@@ -46,9 +48,6 @@
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
 
 /**
  * Test re-synchronization after after backup/restore and LDIF import.
@@ -89,10 +88,7 @@
     * - Do some changes.
     */
 
-    // find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    int replServerPort = socket.getLocalPort();
-    socket.close();
+    int replServerPort = TestCaseUtils.findFreePort();
 
     // This test uses restore task which does not work with memory backend
     // (like the test backend we use in every tests): backend is disabled then
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/SchemaReplicationTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/SchemaReplicationTest.java
index 245c47b..080f20f 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/SchemaReplicationTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/SchemaReplicationTest.java
@@ -23,43 +23,34 @@
  *
  *
  *      Copyright 2008-2010 Sun Microsystems, Inc.
- *      Portions copyright 2012 ForgeRock AS.
+ *      Portions copyright 2012-2013 ForgeRock AS.
  */
 package org.opends.server.replication;
 
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.testng.Assert.*;
 
 import java.io.File;
 import java.io.FileInputStream;
-import java.net.ServerSocket;
 import java.util.ArrayList;
 import java.util.List;
 
-import org.opends.server.TestCaseUtils;
-import org.opends.messages.Message;
 import org.opends.messages.Category;
+import org.opends.messages.Message;
 import org.opends.messages.Severity;
+import org.opends.server.TestCaseUtils;
 import org.opends.server.admin.std.server.SynchronizationProviderCfg;
 import org.opends.server.api.SynchronizationProvider;
 import org.opends.server.core.DirectoryServer;
 import org.opends.server.core.ModifyOperation;
 import org.opends.server.core.ModifyOperationBasis;
 import org.opends.server.protocols.internal.InternalClientConnection;
-import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.replication.common.ChangeNumberGenerator;
 import org.opends.server.replication.plugin.EntryHistorical;
 import org.opends.server.replication.protocol.ModifyMsg;
 import org.opends.server.replication.protocol.ReplicationMsg;
-import org.opends.server.types.Attribute;
-import org.opends.server.types.Attributes;
-import org.opends.server.types.DN;
-import org.opends.server.types.Modification;
-import org.opends.server.types.ModificationType;
-import org.opends.server.types.Operation;
-import org.opends.server.types.RawModification;
-import org.opends.server.types.ResultCode;
+import org.opends.server.replication.service.ReplicationBroker;
+import org.opends.server.types.*;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
@@ -79,17 +70,14 @@
    * @throws Exception
    *           If the environment could not be set up.
    */
+  @Override
   @BeforeClass
   public void setUp() throws Exception
   {
     super.setUp();
 
     // This test suite depends on having the schema available.
-
-    // find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replServerPort = socket.getLocalPort();
-    socket.close();
+    replServerPort = TestCaseUtils.findFreePort();
 
     // Create an internal connection
     connection = InternalClientConnection.getRootConnection();
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/StressTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/StressTest.java
index 735f515..62a90bf 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/StressTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/StressTest.java
@@ -25,22 +25,19 @@
  *      Copyright 2006-2010 Sun Microsystems, Inc.
  *      Portions copyright 2013 ForgeRock As.
  */
-
 package org.opends.server.replication;
 
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.testng.Assert.*;
 
-import java.net.ServerSocket;
 import java.util.LinkedList;
 import java.util.List;
 
-import org.opends.server.TestCaseUtils;
 import org.opends.messages.Category;
-import org.opends.messages.Severity;
 import org.opends.messages.Message;
+import org.opends.messages.Severity;
+import org.opends.server.TestCaseUtils;
 import org.opends.server.admin.std.server.MonitorProviderCfg;
 import org.opends.server.api.MonitorProvider;
 import org.opends.server.config.ConfigException;
@@ -48,25 +45,17 @@
 import org.opends.server.core.DirectoryServer;
 import org.opends.server.core.ModifyOperation;
 import org.opends.server.protocols.internal.InternalClientConnection;
-import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.replication.protocol.AddMsg;
 import org.opends.server.replication.protocol.ReplicationMsg;
-import org.opends.server.types.Attribute;
-import org.opends.server.types.Attributes;
-import org.opends.server.types.DN;
-import org.opends.server.types.Entry;
-import org.opends.server.types.InitializationException;
-import org.opends.server.types.Modification;
-import org.opends.server.types.Operation;
-import org.opends.server.types.OperationType;
-import org.opends.server.types.ResultCode;
+import org.opends.server.replication.service.ReplicationBroker;
+import org.opends.server.types.*;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
-import static org.opends.server.TestCaseUtils.*;
 
 /**
  * Stress test for the synchronization code using the ReplicationBroker API.
  */
+@SuppressWarnings("javadoc")
 public class StressTest extends ReplicationTestCase
 {
   private static final String REPLICATION_STRESS_TEST =
@@ -175,6 +164,7 @@
    * @throws Exception
    *           If the environment could not be set up.
    */
+  @Override
   @BeforeClass
   public void setUp() throws Exception
   {
@@ -192,10 +182,7 @@
         + "entryUUID: 11111111-1111-1111-1111-111111111111\n";
     TestCaseUtils.addEntry(topEntry);
 
-    // find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replServerPort = socket.getLocalPort();
-    socket.close();
+    replServerPort = TestCaseUtils.findFreePort();
 
     // Change log
     String replServerLdif =
@@ -245,7 +232,6 @@
 
     /**
      * Creates a new Stress Test Reader
-     * @param count
      */
     public BrokerWriter(int count)
     {
@@ -284,7 +270,6 @@
 
     /**
      * Creates a new Stress Test Reader
-     * @param broker
      */
     public BrokerReader(ReplicationBroker broker)
     {
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java
index a406eb6..5f0e33c 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java
@@ -23,33 +23,22 @@
  *
  *
  *      Copyright 2006-2010 Sun Microsystems, Inc.
- *      Portions Copyright 2011 ForgeRock AS
+ *      Portions Copyright 2011-2013 ForgeRock AS
  */
-
 package org.opends.server.replication;
 
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.testng.Assert.*;
 
-import java.net.ServerSocket;
 import java.util.ArrayList;
 import java.util.List;
 
-import org.opends.server.TestCaseUtils;
-import org.opends.messages.Message;
 import org.opends.messages.Category;
+import org.opends.messages.Message;
 import org.opends.messages.Severity;
-import org.opends.server.core.AddOperationBasis;
-import org.opends.server.core.DeleteOperationBasis;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.ModifyDNOperationBasis;
-import org.opends.server.core.ModifyOperation;
-import org.opends.server.core.ModifyOperationBasis;
+import org.opends.server.TestCaseUtils;
+import org.opends.server.core.*;
 import org.opends.server.extensions.DummyAlertHandler;
 import org.opends.server.plugins.ShortCircuitPlugin;
 import org.opends.server.protocols.internal.InternalClientConnection;
@@ -57,29 +46,22 @@
 import org.opends.server.protocols.ldap.LDAPModification;
 import org.opends.server.replication.common.ChangeNumber;
 import org.opends.server.replication.common.ChangeNumberGenerator;
-import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.replication.plugin.LDAPReplicationDomain;
-import org.opends.server.replication.protocol.AddMsg;
-import org.opends.server.replication.protocol.DeleteMsg;
-import org.opends.server.replication.protocol.HeartbeatThread;
-import org.opends.server.replication.protocol.ModifyDNMsg;
-import org.opends.server.replication.protocol.ModifyMsg;
-import org.opends.server.replication.protocol.OperationContext;
-import org.opends.server.replication.protocol.ReplicationMsg;
+import org.opends.server.replication.protocol.*;
+import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.schema.DirectoryStringSyntax;
 import org.opends.server.types.*;
 import org.opends.server.util.StaticUtils;
+import org.opends.server.util.TimeThread;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import static org.opends.server.TestCaseUtils.*;
-import org.opends.server.util.TimeThread;
-
 
 /**
  * Test synchronization of update operations on the directory server and through
  * the replication server broker interface.
  */
+@SuppressWarnings("javadoc")
 public class  UpdateOperationTest extends ReplicationTestCase
 {
   /**
@@ -95,9 +77,7 @@
   private String baseUUID;
 
   private String user1dn;
-
   private String user1entrysecondUUID;
-
   private String user1entryUUID;
 
   /**
@@ -115,7 +95,7 @@
   private Entry domain2;
   private Entry domain3;
 
-  int domainSid = 55;
+  private int domainSid = 55;
 
   /**
    * Set up the environment for performing the tests in this Class.
@@ -138,10 +118,7 @@
 
     baseUUID = getEntryUUID(DN.decode("ou=People," + TEST_ROOT_DN_STRING));
 
-    // find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replServerPort = socket.getLocalPort();
-    socket.close();
+    replServerPort = TestCaseUtils.findFreePort();
 
     // replication server
     String replServerLdif =
@@ -1335,11 +1312,7 @@
   private boolean assertConflictAttribute(Entry entry)
   {
     List<Attribute> attrs = entry.getAttribute("ds-sync-confict");
-
-    if (attrs == null)
-      return false;
-    else
-      return true;
+    return attrs != null;
   }
 
   @DataProvider(name="assured")
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/AssuredReplicationPluginTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/AssuredReplicationPluginTest.java
index b018f5c..f06f6b4 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/AssuredReplicationPluginTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/AssuredReplicationPluginTest.java
@@ -53,10 +53,9 @@
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
-import static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
 import static org.testng.Assert.*;
 
 /**
@@ -65,6 +64,7 @@
  * DS (timeout, wait for acks, error handling...)
  * Also check for monitoring values for assured replication
  */
+@SuppressWarnings("javadoc")
 public class AssuredReplicationPluginTest extends ReplicationTestCase
 {
 
@@ -118,10 +118,7 @@
   {
     super.setUp();
 
-    // Find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replServerPort = socket.getLocalPort();
-    socket.close();
+    replServerPort = TestCaseUtils.findFreePort();
 
     // Create base dns for each tested modes
     String topEntry = "dn: " + SAFE_DATA_DN + "\n" + "objectClass: top\n" +
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/FractionalReplicationTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/FractionalReplicationTest.java
index 210e3f5..b32a6b6 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/FractionalReplicationTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/FractionalReplicationTest.java
@@ -31,7 +31,6 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
-import java.net.ServerSocket;
 import java.util.*;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.LinkedBlockingQueue;
@@ -151,10 +150,7 @@
   {
     super.setUp();
 
-    // Find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replServerPort = socket.getLocalPort();
-    socket.close();
+    replServerPort = TestCaseUtils.findFreePort();
   }
 
   /**
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/GroupIdHandshakeTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/GroupIdHandshakeTest.java
index a0b31c9..08ad454 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/GroupIdHandshakeTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/GroupIdHandshakeTest.java
@@ -23,40 +23,38 @@
  *
  *
  *      Copyright 2008-2009 Sun Microsystems, Inc.
- *      Portions Copyright 2011 ForgeRock AS
+ *      Portions Copyright 2011-2013 ForgeRock AS
  */
 package org.opends.server.replication.plugin;
 
-import org.opends.server.util.StaticUtils;
-import org.opends.server.core.DirectoryServer;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
+import static org.opends.server.util.StaticUtils.*;
+import static org.testng.Assert.*;
+
 import java.io.File;
 import java.io.IOException;
-import java.net.ServerSocket;
 import java.util.SortedSet;
 import java.util.TreeSet;
 
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
-import org.opends.server.types.DirectoryException;
-import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
-
 import org.opends.messages.Category;
 import org.opends.messages.Message;
 import org.opends.messages.Severity;
 import org.opends.server.TestCaseUtils;
+import org.opends.server.core.DirectoryServer;
 import org.opends.server.loggers.debug.DebugTracer;
 import org.opends.server.replication.ReplicationTestCase;
 import org.opends.server.replication.server.ReplServerFakeConfiguration;
 import org.opends.server.replication.server.ReplicationServer;
 import org.opends.server.types.DN;
+import org.opends.server.types.DirectoryException;
+import org.opends.server.util.StaticUtils;
 import org.testng.annotations.Test;
-import static org.testng.Assert.*;
-import static org.opends.server.TestCaseUtils.*;
 
 /**
  * Some real connections from clients that should end up with a server with
- * the right groupid if available.
+ * the right groupId if available.
  */
 public class GroupIdHandshakeTest extends ReplicationTestCase
 {
@@ -86,12 +84,7 @@
     }
   }
 
-  private void debugInfo(String message, Exception e)
-  {
-    debugInfo(message + stackTraceToSingleLineString(e));
-  }
-
-  private void initTest()
+  private void initTest() throws Exception
   {
     rs1Port = -1;
     rs2Port = -1;
@@ -127,36 +120,26 @@
       fail("Error deleting reference to domain: " + TEST_ROOT_DN_STRING);
     }
 
-    if (rs1 != null)
-    {
-      rs1.clearDb();
-      rs1.remove();
-      StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(),
-                 rs1.getDbDirName()));
-      rs1 = null;
-    }
-
-    if (rs2 != null)
-    {
-      rs2.clearDb();
-      rs2.remove();
-      StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(),
-                 rs2.getDbDirName()));
-     rs2 = null;
-    }
-    if (rs3 != null)
-    {
-      rs3.clearDb();
-      rs3.remove();
-      StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(),
-                 rs3.getDbDirName()));
-      rs3 = null;
-    }
+    rs1 = clear(rs1);
+    rs2 = clear(rs2);
+    rs3 = clear(rs3);
     rs1Port = -1;
     rs2Port = -1;
     rs3Port = -1;
   }
 
+  private ReplicationServer clear(ReplicationServer rs)
+  {
+    if (rs != null)
+    {
+      rs.clearDb();
+      rs.remove();
+      StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(),
+          rs.getDbDirName()));
+    }
+    return null;
+  }
+
 
   /**
    * Check connection of the provided replication domain to the provided
@@ -254,24 +237,13 @@
   /**
    * Find needed free TCP ports.
    */
-  private void findFreePorts()
+  private void findFreePorts() throws IOException
   {
-    try
-    {
-      ServerSocket socket1 = TestCaseUtils.bindFreePort();
-      ServerSocket socket2 = TestCaseUtils.bindFreePort();
-      ServerSocket socket3 = TestCaseUtils.bindFreePort();
-      rs1Port = socket1.getLocalPort();
-      rs2Port = socket2.getLocalPort();
-      rs3Port = socket3.getLocalPort();
-      socket1.close();
-      socket2.close();
-      socket3.close();
-    } catch (IOException e)
-    {
-      fail("Unable to determinate some free ports " +
-        stackTraceToSingleLineString(e));
-    }
+    int[] ports = TestCaseUtils.findFreePorts(3);
+    int i = 0;
+    rs1Port = ports[i++];
+    rs2Port = ports[i++];
+    rs3Port = ports[i++];
   }
 
   /**
@@ -372,11 +344,9 @@
   private LDAPReplicationDomain createReplicationDomain(int serverId,
     int groupId, String testCase)
   {
-
-    SortedSet<String> replServers = null;
     try
     {
-      replServers = createRSListForTestCase(testCase);
+      SortedSet<String> replServers = createRSListForTestCase(testCase);
       DN baseDn = DN.decode(TEST_ROOT_DN_STRING);
       DomainFakeCfg domainConf =
         new DomainFakeCfg(baseDn, serverId, replServers, groupId);
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalCsnOrderingTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalCsnOrderingTest.java
index 9832ec3..ebaae41 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalCsnOrderingTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalCsnOrderingTest.java
@@ -23,20 +23,15 @@
  *
  *
  *      Copyright 2008-2010 Sun Microsystems, Inc.
- *      Portions Copyright 2011-2012 ForgeRock AS
+ *      Portions Copyright 2011-2013 ForgeRock AS
  */
 package org.opends.server.replication.plugin;
 
-import java.io.File;
-import static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.testng.Assert.*;
 
-import java.io.IOException;
-import java.net.ServerSocket;
+import java.io.File;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.SortedSet;
@@ -51,21 +46,11 @@
 import org.opends.server.core.DirectoryServer;
 import org.opends.server.replication.ReplicationTestCase;
 import org.opends.server.replication.common.ChangeNumber;
-import org.opends.server.replication.protocol.AddMsg;
-import org.opends.server.replication.protocol.DeleteMsg;
-import org.opends.server.replication.protocol.LDAPUpdateMsg;
-import org.opends.server.replication.protocol.ModifyMsg;
-import org.opends.server.replication.protocol.ReplicationMsg;
+import org.opends.server.replication.protocol.*;
 import org.opends.server.replication.server.ReplServerFakeConfiguration;
 import org.opends.server.replication.server.ReplicationServer;
 import org.opends.server.replication.service.ReplicationBroker;
-import org.opends.server.types.Attribute;
-import org.opends.server.types.AttributeType;
-import org.opends.server.types.AttributeValue;
-import org.opends.server.types.ByteString;
-import org.opends.server.types.DN;
-import org.opends.server.types.DirectoryException;
-import org.opends.server.types.Entry;
+import org.opends.server.types.*;
 import org.opends.server.util.StaticUtils;
 import org.opends.server.util.TimeThread;
 import org.testng.annotations.Test;
@@ -73,27 +58,29 @@
 /**
  * Test the usage of the historical data of the replication.
  */
-public class HistoricalCsnOrderingTest
-       extends ReplicationTestCase
+@SuppressWarnings("javadoc")
+public class HistoricalCsnOrderingTest extends ReplicationTestCase
 {
-  final int serverId = 123;
 
-  public class TestBroker extends ReplicationBroker
+  private final int serverId = 123;
+  private SortedSet<String> replServers = new TreeSet<String>();
+
+  public static class TestBroker extends ReplicationBroker
   {
-    LinkedList<ReplicationMsg> list = null;
+    List<ReplicationMsg> list = null;
 
     public TestBroker(LinkedList<ReplicationMsg> list)
     {
-      super(null, null, null, 0, 0, (long) 0, (long) 0, null, (byte) 0, (long) 0);
+      super(null, null, null, 0, 0, 0, 0, null, (byte) 0, 0);
       this.list = list;
     }
 
+    @Override
     public void publishRecovery(ReplicationMsg msg)
     {
       list.add(msg);
     }
 
-
   }
 
   /**
@@ -343,31 +330,17 @@
     }
   }
 
-  SortedSet<String> replServers = new TreeSet<String>();
-  private ReplicationServer createReplicationServer() throws ConfigException
+  private ReplicationServer createReplicationServer() throws Exception
   {
-    int rsPort;
-    try
-    {
-      ServerSocket socket1 = TestCaseUtils.bindFreePort();
-      rsPort = socket1.getLocalPort();
-      socket1.close();
-      replServers.add("localhost:" + rsPort);
+    int rsPort = TestCaseUtils.findFreePort();
+    replServers.add("localhost:" + rsPort);
 
-
-      ReplServerFakeConfiguration conf =
-        new ReplServerFakeConfiguration(rsPort, "HistoricalCsnOrdering",
-            0, 1, 0, 100, replServers, 1, 1000, 5000);
-      ReplicationServer replicationServer = new ReplicationServer(conf);
-      replicationServer.clearDb();
-      return replicationServer;
-    }
-    catch (IOException e)
-    {
-      fail("Unable to determinate some free ports " +
-          stackTraceToSingleLineString(e));
-      return null;
-    }
+    ReplServerFakeConfiguration conf =
+        new ReplServerFakeConfiguration(rsPort, "HistoricalCsnOrdering", 0, 1,
+            0, 100, replServers, 1, 1000, 5000);
+    ReplicationServer replicationServer = new ReplicationServer(conf);
+    replicationServer.clearDb();
+    return replicationServer;
   }
 
   private LDAPReplicationDomain createReplicationDomain(int dsId)
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalTest.java
index 9c39663..d7d60cb 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/HistoricalTest.java
@@ -25,10 +25,8 @@
  *      Copyright 2008-2010 Sun Microsystems, Inc.
  *      Portions Copyright 2011-2013 ForgeRock AS
  */
-
 package org.opends.server.replication.plugin;
 
-
 import static org.opends.server.TestCaseUtils.*;
 import static org.testng.Assert.*;
 
@@ -48,7 +46,6 @@
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-import java.net.ServerSocket;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
@@ -76,10 +73,7 @@
     // Create an internal connection.
     connection = InternalClientConnection.getRootConnection();
 
-    // find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replServerPort = socket.getLocalPort();
-    socket.close();
+    replServerPort = TestCaseUtils.findFreePort();
 
     // The replication server.
     String replServerStringDN = "cn=Replication Server, " + SYNCHRO_PLUGIN_DN;
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/IsolationTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/IsolationTest.java
index a133491..fed056b 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/IsolationTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/IsolationTest.java
@@ -23,17 +23,16 @@
  *
  *
  *      Copyright 2008-2009 Sun Microsystems, Inc.
- *      Portions Copyright 2011 ForgeRock AS
+ *      Portions Copyright 2011-2013 ForgeRock AS
  */
 package org.opends.server.replication.plugin;
 
+import static org.opends.server.TestCaseUtils.*;
+import static org.testng.Assert.*;
 
-import java.net.ServerSocket;
 import java.util.SortedSet;
 import java.util.TreeSet;
 
-import static org.testng.Assert.*;
-
 import org.opends.server.TestCaseUtils;
 import org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.IsolationPolicy;
 import org.opends.server.core.ModifyOperation;
@@ -42,7 +41,6 @@
 import org.opends.server.types.DN;
 import org.opends.server.types.ResultCode;
 import org.testng.annotations.Test;
-import static org.opends.server.TestCaseUtils.*;
 
 /**
  * Test behavior of an LDAP server that is not able to connect
@@ -69,12 +67,9 @@
       // configure and start replication of TEST_ROOT_DN_STRING on the server
       // using a replication server that is not started
 
-      // find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort = socket.getLocalPort();
-      socket.close();
+      int replServerPort = TestCaseUtils.findFreePort();
       SortedSet<String> replServers = new TreeSet<String>();
-          replServers.add("localhost:" + replServerPort);
+      replServers.add("localhost:" + replServerPort);
       DomainFakeCfg domainConf =
         new DomainFakeCfg(baseDn, serverId, replServers);
       domainConf.setHeartbeatInterval(100000);
@@ -91,7 +86,7 @@
       assertEquals(ResultCode.UNWILLING_TO_PERFORM, op.getResultCode());
 
       // now configure the domain to accept changes even though it is not
-      // connectetd to any replication server.
+      // connected to any replication server.
       domainConf.setIsolationPolicy(IsolationPolicy.ACCEPT_ALL_UPDATES);
       domain.applyConfigurationChange(domainConf);
 
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerFailoverTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerFailoverTest.java
index dd1b9ed..de90544 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerFailoverTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerFailoverTest.java
@@ -23,21 +23,18 @@
  *
  *
  *      Copyright 2006-2009 Sun Microsystems, Inc.
- *      Portions Copyright 2011 ForgeRock AS
+ *      Portions Copyright 2011-2013 ForgeRock AS
  */
 package org.opends.server.replication.plugin;
 
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.util.StaticUtils;
-import java.io.File;
-import java.io.IOException;
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
-import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
+import static org.opends.server.util.StaticUtils.*;
 import static org.testng.Assert.*;
 
-import java.net.ServerSocket;
+import java.io.File;
+import java.io.IOException;
 import java.util.SortedSet;
 import java.util.TreeSet;
 
@@ -45,14 +42,15 @@
 import org.opends.messages.Message;
 import org.opends.messages.Severity;
 import org.opends.server.TestCaseUtils;
+import org.opends.server.core.DirectoryServer;
 import org.opends.server.loggers.debug.DebugTracer;
 import org.opends.server.replication.ReplicationTestCase;
 import org.opends.server.replication.server.ReplServerFakeConfiguration;
 import org.opends.server.replication.server.ReplicationServer;
 import org.opends.server.types.DN;
 import org.opends.server.types.DirectoryException;
+import org.opends.server.util.StaticUtils;
 import org.testng.annotations.Test;
-import static org.opends.server.TestCaseUtils.*;
 
 /**
  * Test if the replication domain is able to switch of replication server
@@ -72,7 +70,7 @@
   private ReplicationServer rs1 = null;
   private ReplicationServer rs2 = null;
 
-  // The tracer object for the debug logger
+  /** The tracer object for the debug logger */
   private static final DebugTracer TRACER = getTracer();
 
   private void debugInfo(String s)
@@ -84,7 +82,7 @@
     }
   }
 
-  private void initTest()
+  private void initTest() throws IOException
   {
     rs1Port = -1;
     rs2Port = -1;
@@ -118,29 +116,25 @@
       fail("Error deleting reference to domain: " + TEST_ROOT_DN_STRING);
     }
 
-    if (rs1 != null)
-    {
-      rs1.clearDb();
-      rs1.remove();
-      StaticUtils.recursiveDelete
-              (new File(DirectoryServer.getInstanceRoot(),
-               rs1.getDbDirName()));
-      rs1 = null;
-    }
+    rs1 = clear(rs1);
+    rs2 = clear(rs2);
 
-    if (rs2 != null)
-    {
-      rs2.clearDb();
-      rs2.remove();
-      StaticUtils.recursiveDelete
-              (new File(DirectoryServer.getInstanceRoot(),
-               rs2.getDbDirName()));
-      rs2 = null;
-    }
     rs1Port = -1;
     rs2Port = -1;
   }
 
+  private ReplicationServer clear(ReplicationServer rs)
+  {
+    if (rs != null)
+    {
+      rs.clearDb();
+      rs.remove();
+      StaticUtils.recursiveDelete(new File(DirectoryServer.getInstanceRoot(),
+          rs.getDbDirName()));
+    }
+    return null;
+  }
+
   /**
    * Test the failover feature when one RS fails:
    * 1 DS (DS1) and 2 RS (RS1 and RS2) in topology.
@@ -392,21 +386,11 @@
   /**
    * Find needed free TCP ports.
    */
-  private void findFreePorts()
+  private void findFreePorts() throws IOException
   {
-    try
-    {
-      ServerSocket socket1 = TestCaseUtils.bindFreePort();
-      ServerSocket socket2 = TestCaseUtils.bindFreePort();
-      rs1Port = socket1.getLocalPort();
-      rs2Port = socket2.getLocalPort();
-      socket1.close();
-      socket2.close();
-    } catch (IOException e)
-    {
-      fail("Unable to determinate some free ports " +
-        stackTraceToSingleLineString(e));
-    }
+    int[] ports = TestCaseUtils.findFreePorts(2);
+    rs1Port = ports[0];
+    rs2Port = ports[1];
   }
 
   /**
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerLoadBalancingTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerLoadBalancingTest.java
index b8b6d4e..b73585f 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerLoadBalancingTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/ReplicationServerLoadBalancingTest.java
@@ -33,7 +33,6 @@
 import static org.testng.Assert.*;
 
 import java.io.File;
-import java.net.ServerSocket;
 import java.util.*;
 
 import org.opends.messages.Category;
@@ -65,7 +64,7 @@
   private static final int NRS = 4;
   private final LDAPReplicationDomain rd[] = new LDAPReplicationDomain[NDS];
   private final ReplicationServer rs[] = new ReplicationServer[NRS];
-  private final int[] rsPort = new int[NRS];
+  private int[] rsPort;
 
   private static final int RS1_ID = 501;
   private static final int RS2_ID = 502;
@@ -87,27 +86,8 @@
   {
     Arrays.fill(rd, null);
     Arrays.fill(rs, null);
-    Arrays.fill(rsPort, -1);
 
-    findFreePorts();
-  }
-
-  /**
-   * Find needed free TCP ports.
-   */
-  private void findFreePorts() throws Exception
-  {
-    ServerSocket[] ss = new ServerSocket[NRS];
-
-    for (int i = 0; i < NRS; i++)
-    {
-      ss[i] = TestCaseUtils.bindFreePort();
-      rsPort[i] = ss[i].getLocalPort();
-    }
-    for (int i = 0; i < NRS; i++)
-    {
-      ss[i].close();
-    }
+    rsPort = TestCaseUtils.findFreePorts(NRS);
   }
 
   private void endTest()
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/StateMachineTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/StateMachineTest.java
index 6f8996c..d04f470 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/StateMachineTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/StateMachineTest.java
@@ -23,15 +23,17 @@
  *
  *
  *      Copyright 2009-2010 Sun Microsystems, Inc.
- *      Portions Copyright 2011 ForgeRock AS
+ *      Portions Copyright 2011-2013 ForgeRock AS
  */
 package org.opends.server.replication.plugin;
 
-import org.opends.server.util.StaticUtils;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
+import static org.opends.server.util.StaticUtils.*;
+import static org.testng.Assert.*;
+
 import java.io.File;
 import java.io.IOException;
-import java.net.ServerSocket;
-import java.net.SocketException;
 import java.net.SocketTimeoutException;
 import java.util.ArrayList;
 import java.util.List;
@@ -39,12 +41,6 @@
 import java.util.TreeSet;
 import java.util.concurrent.atomic.AtomicBoolean;
 
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
-import org.opends.server.types.DirectoryException;
-import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
-
 import org.opends.messages.Category;
 import org.opends.messages.Message;
 import org.opends.messages.Severity;
@@ -55,34 +51,29 @@
 import org.opends.server.core.DirectoryServer;
 import org.opends.server.loggers.debug.DebugTracer;
 import org.opends.server.replication.ReplicationTestCase;
-import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.replication.common.ChangeNumberGenerator;
 import org.opends.server.replication.common.DSInfo;
 import org.opends.server.replication.common.ServerState;
 import org.opends.server.replication.common.ServerStatus;
-import org.opends.server.replication.protocol.AddMsg;
-import org.opends.server.replication.protocol.DoneMsg;
-import org.opends.server.replication.protocol.EntryMsg;
-import org.opends.server.replication.protocol.InitializeTargetMsg;
-import org.opends.server.replication.protocol.ReplSessionSecurity;
-import org.opends.server.replication.protocol.ReplicationMsg;
-import org.opends.server.replication.protocol.ResetGenerationIdMsg;
-import org.opends.server.replication.protocol.RoutableMsg;
+import org.opends.server.replication.protocol.*;
 import org.opends.server.replication.server.ReplServerFakeConfiguration;
 import org.opends.server.replication.server.ReplicationServer;
+import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.types.Attribute;
 import org.opends.server.types.DN;
+import org.opends.server.types.DirectoryException;
 import org.opends.server.types.Entry;
+import org.opends.server.util.StaticUtils;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
-import static org.testng.Assert.*;
 
 /**
  * Some tests to go through the DS state machine and validate we get the
  * expected status according to the actions we perform.
  */
+@SuppressWarnings("javadoc")
 public class StateMachineTest extends ReplicationTestCase
 {
 
@@ -97,7 +88,7 @@
   private ReplicationBroker ds2 = null;
   private ReplicationBroker ds3 = null;
   private ReplicationServer rs1 = null;
-  // The tracer object for the debug logger
+  /** The tracer object for the debug logger */
   private static final DebugTracer TRACER = getTracer();
   private int initWindow = 100;
 
@@ -110,18 +101,13 @@
     }
   }
 
-  private void debugInfo(String message, Exception e)
-  {
-    debugInfo(message + stackTraceToSingleLineString(e));
-  }
-
-  private void initTest()
+  private void initTest() throws IOException
   {
     rs1Port = -1;
     ds1 = null;
     ds2 = null;
     ds3 = null;
-    findFreePorts();
+    rs1Port = TestCaseUtils.findFreePort();
   }
 
   private void endTest()
@@ -165,15 +151,9 @@
     rs1Port = -1;
   }
 
-  private void sleep(long time)
+  private void sleep(long time) throws InterruptedException
   {
-    try
-    {
-      Thread.sleep(time);
-    } catch (InterruptedException ex)
-    {
-      fail("Error sleeping " + stackTraceToSingleLineString(ex));
-    }
+    Thread.sleep(time);
   }
 
   /**
@@ -241,44 +221,18 @@
   }
 
   /**
-   * Find needed free TCP ports.
-   */
-  private void findFreePorts()
-  {
-    try
-    {
-      ServerSocket socket1 = TestCaseUtils.bindFreePort();
-      rs1Port = socket1.getLocalPort();
-      socket1.close();
-    } catch (IOException e)
-    {
-      fail("Unable to determinate some free ports " +
-        stackTraceToSingleLineString(e));
-    }
-  }
-
-  /**
    * Creates a new ReplicationServer.
    */
   private ReplicationServer createReplicationServer(String testCase,
-    int degradedStatusThreshold)
+      int degradedStatusThreshold) throws Exception
   {
-    try
-    {
-      SortedSet<String> replServers = new TreeSet<String>();
+    SortedSet<String> replServers = new TreeSet<String>();
 
-      String dir = "stateMachineTest" + RS1_ID + testCase + "Db";
-      ReplServerFakeConfiguration conf =
+    String dir = "stateMachineTest" + RS1_ID + testCase + "Db";
+    ReplServerFakeConfiguration conf =
         new ReplServerFakeConfiguration(rs1Port, dir, 0, RS1_ID, 0, 100,
-        replServers, 1, 1000, degradedStatusThreshold);
-      ReplicationServer replicationServer = new ReplicationServer(conf);
-      return replicationServer;
-
-    } catch (Exception e)
-    {
-      fail("createReplicationServer " + stackTraceToSingleLineString(e));
-    }
-    return null;
+            replServers, 1, 1000, degradedStatusThreshold);
+    return new ReplicationServer(conf);
   }
 
   /**
@@ -287,67 +241,45 @@
    */
   @SuppressWarnings("unchecked")
   private LDAPReplicationDomain createReplicationDomain(int dsId)
+      throws Exception
   {
-    try
-    {
-      SortedSet<String> replServers = new TreeSet<String>();
-      replServers.add("localhost:" + rs1Port);
+    SortedSet<String> replServers = new TreeSet<String>();
+    replServers.add("localhost:" + rs1Port);
 
-      DN baseDn = DN.decode(EXAMPLE_DN);
-      DomainFakeCfg domainConf =
-        new DomainFakeCfg(baseDn, dsId, replServers);
-      LDAPReplicationDomain replicationDomain =
-        MultimasterReplication.createNewDomain(domainConf);
-      replicationDomain.start();
-      SynchronizationProvider<SynchronizationProviderCfg> provider =
+    DN baseDn = DN.decode(EXAMPLE_DN);
+    DomainFakeCfg domainConf = new DomainFakeCfg(baseDn, dsId, replServers);
+    LDAPReplicationDomain replicationDomain = MultimasterReplication.createNewDomain(domainConf);
+    replicationDomain.start();
+    SynchronizationProvider<SynchronizationProviderCfg> provider =
         DirectoryServer.getSynchronizationProviders().get(0);
-      if (provider instanceof ConfigurationChangeListener)
-      {
-        ConfigurationChangeListener<MultimasterReplicationFakeConf> mmr =
-          (ConfigurationChangeListener<MultimasterReplicationFakeConf>) provider;
-        mmr.applyConfigurationChange(new MultimasterReplicationFakeConf());
-      }
-
-      return replicationDomain;
-
-    } catch (Exception e)
+    if (provider instanceof ConfigurationChangeListener)
     {
-      fail("createReplicationDomain " + stackTraceToSingleLineString(e));
+      ConfigurationChangeListener<MultimasterReplicationFakeConf> mmr =
+          (ConfigurationChangeListener<MultimasterReplicationFakeConf>) provider;
+      mmr.applyConfigurationChange(new MultimasterReplicationFakeConf());
     }
-    return null;
+
+    return replicationDomain;
   }
 
   /**
-   * Create and connect a replication broker to the replication server with
-   * the given state and generation id (uses passed window for received changes)
+   * Create and connect a replication broker to the replication server with the
+   * given state and generation id
    */
   private ReplicationBroker createReplicationBroker(int dsId,
-    ServerState state, long generationId, int window)
-    throws Exception, SocketException
+      ServerState state, long generationId) throws Exception
   {
     ReplicationBroker broker = new ReplicationBroker(null,
       state, EXAMPLE_DN, dsId, 100, generationId, 0,
       new ReplSessionSecurity(null, null, null, true), (byte) 1, 500);
-    ArrayList<String> servers = new ArrayList<String>(1);
+    List<String> servers = new ArrayList<String>(1);
     servers.add("localhost:" + rs1Port);
     broker.start(servers);
     checkConnection(30, broker, rs1Port);
-
     return broker;
   }
 
   /**
-   * Create and connect a replication broker to the replication server with
-   * the given state and generation id (uses 100 as window for received changes)
-   */
-  private ReplicationBroker createReplicationBroker(int dsId,
-    ServerState state, long generationId)
-    throws Exception, SocketException
-  {
-    return createReplicationBroker(dsId, state, generationId, 100);
-  }
-
-  /**
    * Make simple state machine test.
    *
    * NC = Not connected status
@@ -396,7 +328,7 @@
     }
   }
 
-  // Returns various init values for test testStateMachineStatusAnalyzer
+  /** Returns various init values for test testStateMachineStatusAnalyzer */
   @DataProvider(name="stateMachineStatusAnalyzerTestProvider")
   public Object [][] stateMachineStatusAnalyzerTestProvider() throws Exception
   {
@@ -443,7 +375,7 @@
        * changes sent to DS. (window value reached: a window msg needed by RS for
        * following sending changes to DS)
        */
-      ds2 = createReplicationBroker(DS2_ID, new ServerState(), EMPTY_DN_GENID, 10);
+      ds2 = createReplicationBroker(DS2_ID, new ServerState(), EMPTY_DN_GENID);
       checkConnection(30, DS2_ID);
 
       /**
@@ -898,14 +830,6 @@
     private BrokerReader reader = null;
 
     /**
-     * Creates a broker initializer with a reader
-     */
-    public BrokerInitializer(ReplicationBroker rb, int serverId)
-    {
-      this(rb, serverId, true);
-    }
-
-    /**
      * Creates a broker initializer. Also creates a reader according to request
      */
     public BrokerInitializer(ReplicationBroker rb, int serverId,
@@ -974,10 +898,8 @@
       // file so need \n\n to separate LDIF entries to conform to LDIF file format
 
       // Create an entry message
-      EntryMsg entryMsg = new EntryMsg(serverId, destId,
-        entryWithUUIDldif.getBytes(), (int)userId);
-
-      return entryMsg;
+      return new EntryMsg(serverId, destId, entryWithUUIDldif.getBytes(),
+          (int) userId);
     }
 
     /**
@@ -1019,14 +941,17 @@
     private int serverId = -1;
     private long userId = 0;
     private AtomicBoolean shutdown = new AtomicBoolean(false);
-    // The writer starts suspended
+    /** The writer starts suspended */
     private AtomicBoolean suspended = new AtomicBoolean(true);
-    // Tells a sending session is finished
-    // A session is sending messages between the follow and the pause calls,
-    // or the time a followAndPause method runs.
+    /**
+     * Tells a sending session is finished. A session is sending messages
+     * between the follow and the pause calls, or the time a followAndPause
+     * method runs.
+     */
     private AtomicBoolean sessionDone = new AtomicBoolean(true);
     private boolean careAboutAmountOfChanges = false;
-    private int nChangesSent = 0; // Number of sent changes
+    /** Number of sent changes */
+    private int nChangesSent = 0;
     private int nChangesSentLimit = 0;
     ChangeNumberGenerator gen = null;
     private Object sleeper = new Object();
@@ -1039,13 +964,7 @@
      */
     private BrokerReader reader = null;
 
-    /* Creates a broker writer with a reader */
-    public BrokerWriter(ReplicationBroker rb, int serverId)
-    {
-      this(rb, serverId, true);
-    }
-
-    /* Creates a broker writer. Also creates a reader according to request */
+    /** Creates a broker writer. Also creates a reader according to request */
     public BrokerWriter(ReplicationBroker rb, int serverId,
       boolean createReader)
     {
@@ -1070,6 +989,7 @@
      * Loops sending changes: add operations creating users with different ids
      * This starts paused and has to be resumed calling a follow method.
      */
+    @Override
     public void run()
     {
       boolean dbg1Written = false, dbg2Written;
@@ -1118,7 +1038,10 @@
         }
         // Mark session is finished
         if (startedNewSession)
+        {
           sessionDone.set(true);
+        }
+
         try
         {
           // Writer in pause, sleep a while to let other threads work
@@ -1186,7 +1109,7 @@
      */
     public boolean isPaused()
     {
-      return (sessionDone.get());
+      return sessionDone.get();
     }
 
     /**
@@ -1199,28 +1122,6 @@
     }
 
     /**
-     * Resumes the writer and suspends it after a given amount of ms
-     * If the writer was working it will be paused anyway after the given amount
-     * of time.
-     * -> blocking call
-     */
-    public void followAndPause(long time)
-    {
-      debugInfo("Requested broker writer " + serverId + " to write for " + time + " ms.");
-      pause(); // If however we were already working
-      sessionDone.set(false);
-      suspended.set(false);
-      try
-      {
-        Thread.sleep(time);
-      } catch (InterruptedException ex)
-      {
-        /* Don't care */
-      }
-      pause();
-    }
-
-    /**
      * Resumes the writer and suspends it after a given amount of changes has been
      * sent. If the writer was working it will be paused anyway after the given
      * amount of changes, starting from the current call time.
@@ -1285,14 +1186,12 @@
       }
 
       // Create an update message to add an entry.
-      AddMsg addMsg = new AddMsg(gen.newChangeNumber(),
+      return new AddMsg(gen.newChangeNumber(),
         personWithUUIDEntry.getDN().toString(),
         userEntryUUID,
         null,
         personWithUUIDEntry.getObjectClassAttribute(),
         personWithUUIDEntry.getAttributes(), new ArrayList<Attribute>());
-
-      return addMsg;
     }
   }
 
@@ -1319,7 +1218,9 @@
       this.serverId = serverId;
       start();
     }
-    // Loop reading and throwing update messages
+
+    /** Loop reading and throwing update messages */
+    @Override
     public void run()
     {
       while (!shutdown)
@@ -1340,8 +1241,10 @@
       debugInfo("Broker " + serverId + " reader thread is dying");
     }
 
-    // Returns last received message from reader
-    // When read, last value is cleared
+    /**
+     * Returns last received message from reader When read, last value is
+     * cleared
+     */
     public ReplicationMsg getLastMsg()
     {
       ReplicationMsg toReturn = lastMsg;
@@ -1349,7 +1252,7 @@
       return toReturn;
     }
 
-    // Stops reader thread
+    /** Stops reader thread */
     public void shutdown()
     {
       shutdown = true;
@@ -1391,7 +1294,7 @@
   {
     int nSec = 0;
 
-    if ((testedValue == null) || (expectedValue == null))
+    if (testedValue == null || expectedValue == null)
       fail("sleepAssertStatusEquals: null parameters");
 
     // Go out of the loop only if equality is obtained or if timeout occurs
@@ -1418,9 +1321,8 @@
       if (nSec == secTimeout)
       {
         // Timeout reached, end with error
-        fail("sleepAssertStatusEquals: got <" +
-          testedValue.getStatus().toString() + "> where expected <" +
-          expectedValue.toString() + ">");
+        fail("sleepAssertStatusEquals: got <" + testedValue.getStatus()
+          + "> where expected <" + expectedValue + ">");
       }
     }
   }
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java
index 3934ac7..bb8c5fc 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/plugin/TopologyViewTest.java
@@ -27,27 +27,16 @@
  */
 package org.opends.server.replication.plugin;
 
-import java.net.UnknownHostException;
-import static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
-import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.fail;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
+import static org.opends.server.util.StaticUtils.*;
+import static org.testng.Assert.*;
 
 import java.io.File;
-import java.io.IOException;
 import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
+import java.net.UnknownHostException;
+import java.util.*;
 
 import org.opends.messages.Category;
 import org.opends.messages.Message;
@@ -167,7 +156,7 @@
     }
   }
 
-  private void initTest()
+  private void initTest() throws Exception
   {
     rs1Port = -1;
     rs2Port = -1;
@@ -380,24 +369,13 @@
   /**
    * Find needed free TCP ports.
    */
-  private void findFreePorts()
+  private void findFreePorts() throws Exception
   {
-    try
-    {
-      ServerSocket socket1 = TestCaseUtils.bindFreePort();
-      ServerSocket socket2 = TestCaseUtils.bindFreePort();
-      ServerSocket socket3 = TestCaseUtils.bindFreePort();
-      rs1Port = socket1.getLocalPort();
-      rs2Port = socket2.getLocalPort();
-      rs3Port = socket3.getLocalPort();
-      socket1.close();
-      socket2.close();
-      socket3.close();
-    } catch (IOException e)
-    {
-      fail("Unable to determinate some free ports " +
-        stackTraceToSingleLineString(e));
-    }
+    int[] ports = TestCaseUtils.findFreePorts(3);
+    int i = 0;
+    rs1Port = ports[i++];
+    rs2Port = ports[i++];
+    rs3Port = ports[i++];
   }
 
   /**
@@ -1169,6 +1147,7 @@
       this.rsList = rsList;
     }
 
+    @Override
     public boolean equals(Object obj)
     {
       assertNotNull(obj);
@@ -1217,6 +1196,7 @@
       return true;
     }
 
+    @Override
     public String toString()
     {
       String dsStr = "";
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/AssuredReplicationServerTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/AssuredReplicationServerTest.java
index b48ac28..5ef3fbc 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/AssuredReplicationServerTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/AssuredReplicationServerTest.java
@@ -36,7 +36,6 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.InetSocketAddress;
-import java.net.ServerSocket;
 import java.net.Socket;
 import java.net.SocketTimeoutException;
 import java.util.*;
@@ -201,19 +200,12 @@
   {
     super.setUp();
 
-    // Find  a free port for the replication servers
-    ServerSocket socket1 = TestCaseUtils.bindFreePort();
-    ServerSocket socket2 = TestCaseUtils.bindFreePort();
-    ServerSocket socket3 = TestCaseUtils.bindFreePort();
-    ServerSocket socket4 = TestCaseUtils.bindFreePort();
-    rs1Port = socket1.getLocalPort();
-    rs2Port = socket2.getLocalPort();
-    rs3Port = socket3.getLocalPort();
-    rs4Port = socket4.getLocalPort();
-    socket1.close();
-    socket2.close();
-    socket3.close();
-    socket4.close();
+    int[] ports = TestCaseUtils.findFreePorts(4);
+    int i = 0;
+    rs1Port = ports[i++];
+    rs2Port = ports[i++];
+    rs3Port = ports[i++];
+    rs4Port = ports[i++];
   }
 
   private void initTest()
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/DraftCNDbHandlerTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/DraftCNDbHandlerTest.java
index d0c5e55..a2360db 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/DraftCNDbHandlerTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/DraftCNDbHandlerTest.java
@@ -30,7 +30,6 @@
 import static org.testng.Assert.*;
 
 import java.io.File;
-import java.net.ServerSocket;
 
 import org.opends.server.TestCaseUtils;
 import org.opends.server.replication.ReplicationTestCase;
@@ -68,10 +67,7 @@
     {
       TestCaseUtils.startServer();
 
-      //  find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int changelogPort = socket.getLocalPort();
-      socket.close();
+      int changelogPort = TestCaseUtils.findFreePort();
 
       // configure a ReplicationServer.
       ReplServerFakeConfiguration conf =
@@ -196,10 +192,7 @@
     {
       TestCaseUtils.startServer();
 
-      //  find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int changelogPort = socket.getLocalPort();
-      socket.close();
+      int changelogPort = TestCaseUtils.findFreePort();
 
       // configure a ReplicationServer.
       ReplServerFakeConfiguration conf =
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/MonitorTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/MonitorTest.java
index 1ee23e9..74610db 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/MonitorTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/MonitorTest.java
@@ -50,27 +50,25 @@
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
-import java.net.ServerSocket;
 import java.net.SocketException;
 import java.util.ArrayList;
 import java.util.SortedSet;
 import java.util.TreeSet;
 import java.util.UUID;
 
-import static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;
-import static org.opends.server.loggers.ErrorLogger.logError;
-import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
-import static org.opends.server.loggers.debug.DebugLogger.getTracer;
-import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
+import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.loggers.ErrorLogger.*;
+import static org.opends.server.loggers.debug.DebugLogger.*;
+import static org.opends.server.util.StaticUtils.*;
 import static org.testng.Assert.*;
 
 /**
  * Tests for the replicationServer code.
  */
-
+@SuppressWarnings("javadoc")
 public class MonitorTest extends ReplicationTestCase
 {
-  // The tracer object for the debug logger
+  /** The tracer object for the debug logger */
   private static final DebugTracer TRACER = getTracer();
 
   private static final String baseDnStr = TEST_ROOT_DN_STRING;
@@ -92,8 +90,8 @@
   private ReplicationServer replServer1 = null;
   private ReplicationServer replServer2 = null;
   private ReplicationServer replServer3 = null;
-  LDAPReplicationDomain replDomain = null;
-  protected String[] updatedEntries;
+  private LDAPReplicationDomain replDomain = null;
+  private String[] updatedEntries;
 
   private static int[] replServerPort = new int[30];
 
@@ -105,7 +103,8 @@
       TRACER.debugInfo("** TEST **" + s);
     }
   }
-  protected void debugInfo(String message, Exception e)
+
+  private void debugInfo(String message, Exception e)
   {
     debugInfo(message + stackTraceToSingleLineString(e));
   }
@@ -116,6 +115,7 @@
    * @throws Exception
    *           If the environment could not be set up.
    */
+  @Override
   @BeforeClass
   public void setUp() throws Exception
   {
@@ -126,12 +126,11 @@
     updatedEntries = newLDIFEntries();
   }
 
-  /*
+  /**
    * Creates entries necessary to the test.
    */
   private String[] newLDIFEntries()
   {
-
     return new String[]{
         "dn: " + baseDn + "\n"
             + "objectClass: top\n"
@@ -249,13 +248,11 @@
     }
   }
 
-  /*
+  /**
    * Disconnect DS from the replicationServer
    */
-  private void disconnectFromReplServer(int changelogID)
+  private void disconnectFromReplServer() throws Exception
   {
-    try
-    {
       // suffix synchronized
       String synchroServerStringDN = "cn=" + testName + ", cn=domains," +
       SYNCHRO_PLUGIN_DN;
@@ -265,30 +262,13 @@
       deleteEntry(synchroServerDN);
       synchroServerEntry = null;
       configEntryList.remove(configEntryList.indexOf(synchroServerDN));
-
-    }
-    catch(Exception e)
-    {
-      fail("disconnectFromReplServer", e);
-    }
   }
 
-  private int getChangelogPort(int changelogID)
+  private int getChangelogPort(int changelogID) throws Exception
   {
     if (replServerPort[changelogID] == 0)
     {
-      try
-      {
-        // Find  a free port for the replicationServer
-        ServerSocket socket = TestCaseUtils.bindFreePort();
-        replServerPort[changelogID] = socket.getLocalPort();
-        socket.close();
-      }
-      catch(Exception e)
-      {
-        fail("Cannot retrieve a free port for replication server."
-            + e.getMessage());
-      }
+      replServerPort[changelogID] = TestCaseUtils.findFreePort();
     }
     return replServerPort[changelogID];
   }
@@ -312,8 +292,7 @@
         + "userPassword: password\n" + "initials: AA\n";
   }
 
-  static protected ReplicationMsg createAddMsg(ChangeNumber cn,
-      int serverId)
+  static private ReplicationMsg createAddMsg(ChangeNumber cn)
   {
     Entry personWithUUIDEntry = null;
     String user1entryUUID;
@@ -433,14 +412,13 @@
 
       for (int i = 0; i < 10; i++)
       {
-        broker3.publish(createAddMsg(gen.newChangeNumber(), server3ID));
+        broker3.publish(createAddMsg(gen.newChangeNumber()));
       }
 
       searchMonitor();
 
-      debugInfo(
-        "Disconnect DS from replServer1 (required in order to DEL entries).");
-      disconnectFromReplServer(changelog1ID);
+      debugInfo("Disconnect DS from replServer1 (required in order to DEL entries).");
+      disconnectFromReplServer();
 
 
       debugInfo("Successfully ending " + testCase);
@@ -454,7 +432,7 @@
   /**
    * Disconnect broker and remove entries from the local DB
    */
-  protected void postTest()
+  private void postTest()
   {
     debugInfo("Post test cleaning.");
 
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerDynamicConfTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerDynamicConfTest.java
index 4624ab1..bff873f 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerDynamicConfTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerDynamicConfTest.java
@@ -23,24 +23,23 @@
  *
  *
  *      Copyright 2006-2009 Sun Microsystems, Inc.
+ *      Portions copyright 2013 ForgeRock AS
  */
 package org.opends.server.replication.server;
 
-import static org.testng.Assert.assertTrue;
-
-import java.net.ServerSocket;
+import static org.opends.server.TestCaseUtils.*;
+import static org.testng.Assert.*;
 
 import org.opends.server.TestCaseUtils;
 import org.opends.server.replication.ReplicationTestCase;
 import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.types.DN;
 import org.testng.annotations.Test;
-import static org.opends.server.TestCaseUtils.*;
 
 /**
  * Tests that we can dynamically modify the configuration of replicationServer
  */
-
+@SuppressWarnings("javadoc")
 public class ReplicationServerDynamicConfTest extends ReplicationTestCase
 {
   /**
@@ -55,13 +54,9 @@
     TestCaseUtils.startServer();
 
     try {
-      // find two free ports for the replication Server port
-      ServerSocket socket1 = TestCaseUtils.bindFreePort();
-      int replicationServerPort = socket1.getLocalPort();
-      ServerSocket socket2 = TestCaseUtils.bindFreePort();
-      int newReplicationServerPort = socket2.getLocalPort();
-      socket1.close();
-      socket2.close();
+      int[] ports = TestCaseUtils.findFreePorts(2);
+      int replicationServerPort = ports[0];
+      int newReplicationServerPort = ports[1];
 
       // instantiate a Replication server using the first port number.
       ReplServerFakeConfiguration conf =
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerTest.java
index aa77ded..a2eef90 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/server/ReplicationServerTest.java
@@ -38,16 +38,9 @@
 import java.io.File;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.ServerSocket;
 import java.net.Socket;
 import java.net.SocketTimeoutException;
-import java.util.ArrayList;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import java.util.UUID;
+import java.util.*;
 
 import org.opends.server.TestCaseUtils;
 import org.opends.server.api.SynchronizationProvider;
@@ -60,14 +53,14 @@
 import org.opends.server.protocols.ldap.LDAPControl;
 import org.opends.server.protocols.ldap.LDAPFilter;
 import org.opends.server.replication.ReplicationTestCase;
-import org.opends.server.replication.protocol.*;
-import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.replication.common.ChangeNumber;
 import org.opends.server.replication.common.ChangeNumberGenerator;
 import org.opends.server.replication.common.ServerState;
 import org.opends.server.replication.common.ServerStatus;
 import org.opends.server.replication.plugin.MultimasterReplication;
 import org.opends.server.replication.plugin.ReplicationServerListener;
+import org.opends.server.replication.protocol.*;
+import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.tools.LDAPModify;
 import org.opends.server.tools.LDAPSearch;
 import org.opends.server.types.*;
@@ -81,9 +74,10 @@
 /**
  * Tests for the replicationServer code.
  */
+@SuppressWarnings("javadoc")
 public class ReplicationServerTest extends ReplicationTestCase
 {
-  // The tracer object for the debug logger
+  /** The tracer object for the debug logger */
   private static final DebugTracer TRACER = getTracer();
   /**
    * The replicationServer that will be used in this test.
@@ -126,10 +120,7 @@
    */
   protected void configure() throws Exception
   {
-    //  find  a free port for the replicationServer
-    ServerSocket socket = TestCaseUtils.bindFreePort();
-    replicationServerPort = socket.getLocalPort();
-    socket.close();
+    replicationServerPort = TestCaseUtils.findFreePort();
 
     TestCaseUtils.dsconfig(
         "create-replication-server",
@@ -742,18 +733,13 @@
       int[] changelogPorts = new int[2];
       int[] changelogIds = new int[2];
       int[] brokerIds = new int[2];
-      ServerSocket socket = null;
 
       // Find 2 free ports
       for (int i = 0; i <= 1; i++)
       {
-        // find  a free port
-        socket = TestCaseUtils.bindFreePort();
-        changelogPorts[i] = socket.getLocalPort();
+        changelogPorts[i] = TestCaseUtils.findFreePort();
         changelogIds[i] = i + 80;
         brokerIds[i] = 100 + i;
-        if ((itest==0) || (i ==0))
-          socket.close();
       }
 
       for (int i = 0; i <= ((itest == 0) ? 1 : 0); i++)
@@ -840,8 +826,6 @@
 
         if (itest > 0)
         {
-          socket.close();
-
           SortedSet<String> servers = new TreeSet<String>();
           servers.add("localhost:"+changelogPorts[0]);
           ReplServerFakeConfiguration conf =
@@ -1713,17 +1697,13 @@
        int[] changelogPorts = new int[2];
        int[] changelogIds = new int[2];
        int[] brokerIds = new int[2];
-       ServerSocket socket = null;
 
        // Find 2 free ports
        for (int i = 0; i <= 1; i++)
        {
-         // find  a free port
-         socket = TestCaseUtils.bindFreePort();
-         changelogPorts[i] = socket.getLocalPort();
+         changelogPorts[i] = TestCaseUtils.findFreePort();
          changelogIds[i] = i + 90;
          brokerIds[i] = 100+i;
-         socket.close();
        }
 
        for (int i = 0; i <= 1; i++)
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/service/ReplicationDomainTest.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/service/ReplicationDomainTest.java
index 301d242..64b8640 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/service/ReplicationDomainTest.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/service/ReplicationDomainTest.java
@@ -23,23 +23,18 @@
  *
  *
  *      Copyright 2008-2010 Sun Microsystems, Inc.
- *      Portions Copyright 2011 ForgeRock AS
+ *      Portions Copyright 2011-2013 ForgeRock AS
  */
 package org.opends.server.replication.service;
 
-import java.io.File;
 import static org.testng.Assert.*;
 
-import java.util.List;
-import java.util.Map;
-import java.util.TreeSet;
-
-import java.util.concurrent.LinkedBlockingQueue;
-
-import java.net.ServerSocket;
-import java.util.ArrayList;
+import java.io.File;
+import java.util.*;
 import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
+
 import org.opends.server.TestCaseUtils;
 import org.opends.server.core.DirectoryServer;
 import org.opends.server.replication.ReplicationTestCase;
@@ -57,6 +52,7 @@
 /**
  * Test the Generic Replication Service.
  */
+@SuppressWarnings("javadoc")
 public class ReplicationDomainTest extends ReplicationTestCase
 {
   /**
@@ -92,19 +88,14 @@
 
     try
     {
-      // find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort1 = socket.getLocalPort();
-      socket.close();
+      int[] ports = TestCaseUtils.findFreePorts(2);
+      int replServerPort1 = ports[0];
+      int replServerPort2 = ports[1];
 
-      socket = TestCaseUtils.bindFreePort();
-      int replServerPort2 = socket.getLocalPort();
-      socket.close();
-
-      TreeSet<String> replserver1 = new TreeSet<String>();
+      SortedSet<String> replserver1 = new TreeSet<String>();
       replserver1.add("localhost:" + replServerPort1);
 
-      TreeSet<String> replserver2 = new TreeSet<String>();
+      SortedSet<String> replserver2 = new TreeSet<String>();
       replserver2.add("localhost:" + replServerPort2);
 
       ReplServerFakeConfiguration conf1 =
@@ -117,16 +108,16 @@
             replServerPort2, "ReplicationDomainTestDb2",
             0, replServerID2, 0, 100, replserver1);
 
-      replServer1 = new ReplicationServer(conf1);;
+      replServer1 = new ReplicationServer(conf1);
       replServer2 = new ReplicationServer(conf2);
-      ArrayList<String> servers = new ArrayList<String>(1);
+      List<String> servers = new ArrayList<String>(1);
       servers.add("localhost:" + replServerPort1);
 
       BlockingQueue<UpdateMsg> rcvQueue1 = new LinkedBlockingQueue<UpdateMsg>();
       domain1 = new FakeReplicationDomain(
           testService, domain1ServerId, servers, 100, 1000, rcvQueue1);
 
-      ArrayList<String> servers2 = new ArrayList<String>(1);
+      List<String> servers2 = new ArrayList<String>(1);
       servers2.add("localhost:" + replServerPort2);
 
       BlockingQueue<UpdateMsg> rcvQueue2 = new LinkedBlockingQueue<UpdateMsg>();
@@ -268,13 +259,9 @@
 
     try
     {
-      // find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort = socket.getLocalPort();
-      socket.close();
+      int replServerPort = TestCaseUtils.findFreePort();
 
-
-      TreeSet<String> replserver = new TreeSet<String>();
+      SortedSet<String> replserver = new TreeSet<String>();
       replserver.add("localhost:" + replServerPort);
 
       ReplServerFakeConfiguration conf1 =
@@ -282,8 +269,8 @@
             replServerPort, "ReplicationDomainTestDb",
             0, replServerID1, 0, 100000, replserver);
 
-      replServer1 = new ReplicationServer(conf1);;
-      ArrayList<String> servers = new ArrayList<String>(1);
+      replServer1 = new ReplicationServer(conf1);
+      List<String> servers = new ArrayList<String>(1);
       servers.add("localhost:" + replServerPort);
 
       BlockingQueue<UpdateMsg> rcvQueue1 = new LinkedBlockingQueue<UpdateMsg>();
@@ -361,10 +348,7 @@
 
     try
     {
-      // find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort = socket.getLocalPort();
-      socket.close();
+      int replServerPort = TestCaseUtils.findFreePort();
 
       ReplServerFakeConfiguration conf =
         new ReplServerFakeConfiguration(
@@ -372,7 +356,7 @@
             0, replServerID, 0, 100, null);
 
       replServer = new ReplicationServer(conf);
-      ArrayList<String> servers = new ArrayList<String>(1);
+      List<String> servers = new ArrayList<String>(1);
       servers.add("localhost:" + replServerPort);
 
       StringBuilder exportedDataBuilder = new StringBuilder();
@@ -451,19 +435,14 @@
 
     try
     {
-      // find  a free port for the replicationServer
-      ServerSocket socket = TestCaseUtils.bindFreePort();
-      int replServerPort1 = socket.getLocalPort();
-      socket.close();
+      int[] ports = TestCaseUtils.findFreePorts(2);
+      int replServerPort1 = ports[0];
+      int replServerPort2 = ports[1];
 
-      socket = TestCaseUtils.bindFreePort();
-      int replServerPort2 = socket.getLocalPort();
-      socket.close();
-
-      TreeSet<String> replserver1 = new TreeSet<String>();
+      SortedSet<String> replserver1 = new TreeSet<String>();
       replserver1.add("localhost:" + replServerPort1);
 
-      TreeSet<String> replserver2 = new TreeSet<String>();
+      SortedSet<String> replserver2 = new TreeSet<String>();
       replserver2.add("localhost:" + replServerPort2);
 
       ReplServerFakeConfiguration conf1 =
@@ -479,10 +458,10 @@
       replServer1 = new ReplicationServer(conf1);
       replServer2 = new ReplicationServer(conf2);
 
-      ArrayList<String> servers1 = new ArrayList<String>(1);
+      List<String> servers1 = new ArrayList<String>(1);
       servers1.add("localhost:" + replServerPort1);
 
-      ArrayList<String> servers2 = new ArrayList<String>(1);
+      List<String> servers2 = new ArrayList<String>(1);
       servers2.add("localhost:" + replServerPort2);
 
       StringBuilder exportedDataBuilder = new StringBuilder();
@@ -571,7 +550,7 @@
 
     try
     {
-      TreeSet<String> servers = new TreeSet<String>();
+      SortedSet<String> servers = new TreeSet<String>();
       servers.add(HOST1 + SENDERPORT);
       servers.add(HOST2 + RECEIVERPORT);
 
@@ -616,7 +595,7 @@
 
     try
     {
-      TreeSet<String> servers = new TreeSet<String>();
+      SortedSet<String> servers = new TreeSet<String>();
       servers.add(HOST1 + SENDERPORT);
       servers.add(HOST2 + RECEIVERPORT);
 
diff --git a/opends/tests/unit-tests-testng/src/server/org/opends/server/snmp/SNMPConnectionManager.java b/opends/tests/unit-tests-testng/src/server/org/opends/server/snmp/SNMPConnectionManager.java
index f462b8c..779b38c 100644
--- a/opends/tests/unit-tests-testng/src/server/org/opends/server/snmp/SNMPConnectionManager.java
+++ b/opends/tests/unit-tests-testng/src/server/org/opends/server/snmp/SNMPConnectionManager.java
@@ -240,10 +240,8 @@
    */
   protected void enableSnmp() throws Exception
   {
-
-    // Get a free port
-    this.snmpPort = TestCaseUtils.bindFreePort().getLocalPort();
-    this.trapSnmpPort = TestCaseUtils.bindFreePort().getLocalPort();
+    this.snmpPort = TestCaseUtils.findFreePort();
+    this.trapSnmpPort = TestCaseUtils.findFreePort();
 
     ArrayList<Modification> mods = new ArrayList<Modification>();
 

--
Gitblit v1.10.0