From ccfdb0cbf1507615061d630b57f1f1e0fc361d56 Mon Sep 17 00:00:00 2001
From: Jean-Noel Rouvignac <jean-noel.rouvignac@forgerock.com>
Date: Wed, 09 Oct 2013 14:45:35 +0000
Subject: [PATCH] *Test.java: More code cleanups.

---
 opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReplicationTestCase.java |  251 ++++++++++++------------------
 opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java |  214 +++++++++++---------------
 2 files changed, 195 insertions(+), 270 deletions(-)

diff --git a/opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReplicationTestCase.java b/opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReplicationTestCase.java
index 9e92221..5f2b87b 100644
--- a/opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReplicationTestCase.java
+++ b/opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/ReplicationTestCase.java
@@ -27,10 +27,10 @@
  */
 package org.opends.server.replication;
 
-import java.net.SocketException;
 import java.util.*;
 import java.util.concurrent.locks.Lock;
 
+import org.assertj.core.api.Assertions;
 import org.opends.messages.Category;
 import org.opends.messages.Message;
 import org.opends.messages.Severity;
@@ -56,7 +56,6 @@
 import org.opends.server.replication.server.changelog.je.JEChangelogDB;
 import org.opends.server.replication.service.ReplicationBroker;
 import org.opends.server.replication.service.ReplicationDomain;
-import org.opends.server.schema.DirectoryStringSyntax;
 import org.opends.server.schema.IntegerSyntax;
 import org.opends.server.types.*;
 import org.testng.annotations.AfterClass;
@@ -66,7 +65,7 @@
 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.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.schema.DirectoryStringSyntax.*;
 import static org.opends.server.types.ResultCode.*;
 import static org.opends.server.types.SearchScope.*;
 import static org.testng.Assert.*;
@@ -117,38 +116,38 @@
   private long lastCount;
 
   /**
-   * schema check flag
+   * Call the paranoiaCheck at test cleanup or not.
+   * <p>
+   * Must not been touched except if sub class has its own clean up code, for
+   * instance:
+   *
+   * <pre>
+   * &#064;AfterClass
+   * public void classCleanUp() throws Exception
+   * {
+   *   callParanoiaCheck = false;
+   *   super.classCleanUp();
+   *
+   *   // Clear my own stuff that I have setup (in my own setup() method for instance)
+   *   // This removes the replication changes backend
+   *   myReplServerInstantiatedWithConstructor.remove();
+   *
+   *   // Now call paramoiaCheck myself
+   *   paranoiaCheck();
+   * }
+   *
+   * </pre>
    */
-  protected boolean schemaCheck;
-
-  // Call the paranoiaCheck at test cleanup or not.
-  // Must not been touched except if sub class has its own clean up code,
-  // for instance:
-  // @AfterClass
-  // public void classCleanUp() throws Exception
-  // {
-  //   callParanoiaCheck = false;
-  //   super.classCleanUp();
-  //
-  //  // Clear my own stuff that I have setup (in my own setup() method for instance)
-  //  myReplServerInstantiatedWithConstructor.remove(); // This removes the replication changes backend
-  //
-  //  // Now call paramoiaCheck myself
-  //  paranoiaCheck();
-  // }
   protected boolean callParanoiaCheck = true;
 
   /**
    * The replication plugin entry
    */
-  protected final String SYNCHRO_PLUGIN_DN =
+  protected static final String SYNCHRO_PLUGIN_DN =
     "cn=Multimaster Synchronization, cn=Synchronization Providers,cn=config";
 
   /**
    * Set up the environment for performing the tests in this suite.
-   *
-   * @throws Exception
-   *         If the environment could not be set up.
    */
   @BeforeClass
   public void setUp() throws Exception
@@ -194,10 +193,9 @@
    * The generation is read from the replicationDomain object. If it
    * does not exist, take the 'empty backend' generationID.
    */
-  protected ReplicationBroker openReplicationSession(
-      final DN baseDN, int serverId, int window_size,
-      int port, int timeout, boolean emptyOldChanges)
-          throws Exception, SocketException
+  protected ReplicationBroker openReplicationSession(final DN baseDN,
+      int serverId, int window_size, int port, int timeout,
+      boolean emptyOldChanges) throws Exception
   {
     return openReplicationSession(baseDN, serverId, window_size,
         port, timeout, emptyOldChanges, getGenerationId(baseDN), null);
@@ -207,11 +205,9 @@
    * Open a replicationServer session to the local ReplicationServer
    * providing the generationId.
    */
-  protected ReplicationBroker openReplicationSession(
-        final DN baseDN, int serverId, int window_size,
-        int port, int timeout, boolean emptyOldChanges,
-        long generationId)
-  throws Exception, SocketException
+  protected ReplicationBroker openReplicationSession(final DN baseDN,
+      int serverId, int window_size, int port, int timeout,
+      boolean emptyOldChanges, long generationId) throws Exception
   {
     return openReplicationSession(baseDN, serverId, window_size,
         port, timeout, emptyOldChanges, generationId, null);
@@ -221,11 +217,10 @@
    * Open a replicationServer session to the local ReplicationServer
    * providing the generationId.
    */
-  protected ReplicationBroker openReplicationSession(
-        final DN baseDN, int serverId, int window_size,
-        int port, int timeout, boolean emptyOldChanges,
-        long generationId, ReplicationDomain replicationDomain)
-  throws Exception, SocketException
+  protected ReplicationBroker openReplicationSession(final DN baseDN,
+      int serverId, int window_size, int port, int timeout,
+      boolean emptyOldChanges, long generationId,
+      ReplicationDomain replicationDomain) throws Exception
   {
     ServerState state = new ServerState();
 
@@ -283,10 +278,9 @@
    * Open a replicationServer session to the local ReplicationServer
    * with a default value generationId.
    */
-  protected ReplicationBroker openReplicationSession(
-      final DN baseDN, int serverId, int window_size,
-      int port, int timeout, ServerState state)
-    throws Exception, SocketException
+  protected ReplicationBroker openReplicationSession(final DN baseDN,
+      int serverId, int window_size, int port, int timeout, ServerState state)
+      throws Exception
   {
     return openReplicationSession(baseDN, serverId, window_size,
         port, timeout, state, getGenerationId(baseDN));
@@ -296,10 +290,9 @@
    * Open a new session to the ReplicationServer
    * starting with a given ServerState.
    */
-  protected ReplicationBroker openReplicationSession(
-      final DN baseDN, int serverId, int window_size,
-      int port, int timeout, ServerState state, long generationId)
-          throws Exception, SocketException
+  protected ReplicationBroker openReplicationSession(final DN baseDN,
+      int serverId, int window_size, int port, int timeout, ServerState state,
+      long generationId) throws Exception
   {
     ReplicationBroker broker = new ReplicationBroker(null,
         state, baseDN, serverId, window_size, generationId,
@@ -521,7 +514,6 @@
     }
   }
 
-
   /**
    * Get the value of the specified attribute for a given replication
    * domain from the monitor entry.
@@ -563,11 +555,7 @@
     do
     {
       final Lock lock = LockManager.lockRead(dn);
-      if (lock == null)
-      {
-        throw new Exception("could not lock entry " + dn);
-      }
-
+      assertNotNull(lock, "could not lock entry " + dn);
       try
       {
         final Entry newEntry = DirectoryServer.getEntry(dn);
@@ -615,11 +603,7 @@
     }
 
     final Lock lock = LockManager.lockRead(dn);
-    if (lock == null)
-    {
-      throw new Exception("could not lock entry " + dn);
-    }
-
+    assertNotNull(lock, "could not lock entry " + dn);
     try
     {
       Entry entry = DirectoryServer.getEntry(dn);
@@ -647,18 +631,14 @@
    * Get the delta between the current / last monitor counts.
    * @return The delta between the current and last monitor count.
    */
-  protected long getMonitorDelta() {
-    long delta = 0;
-    try {
-      long currentCount = getMonitorAttrValue(monitorDN, monitorAttr);
-      delta = (currentCount - lastCount);
-      lastCount = currentCount;
-    } catch (Exception ex) {
-      ex.printStackTrace();
-      fail();
-    }
+  protected long getMonitorDelta() throws Exception
+  {
+    long currentCount = getMonitorAttrValue(monitorDN, monitorAttr);
+    long delta = (currentCount - lastCount);
+    lastCount = currentCount;
     return delta;
   }
+
   /**
    * Generate a new modification replace with the given information.
    *
@@ -683,8 +663,6 @@
   {
     Entry taskEntry = TestCaseUtils.makeEntry(task);
 
-    InternalClientConnection connection = getRootConnection();
-
     // Add the task.
     AddOperation addOperation = connection.processAdd(taskEntry);
     assertEquals(addOperation.getResultCode(), ResultCode.SUCCESS,
@@ -693,8 +671,7 @@
     // Wait until the task completes.
     AttributeType completionTimeType = DirectoryServer.getAttributeType(
          ATTR_TASK_COMPLETION_TIME.toLowerCase());
-    SearchFilter filter =
-         SearchFilter.createFilterFromString("(objectclass=*)");
+    SearchFilter filter = SearchFilter.createFilterFromString("(objectclass=*)");
     Entry resultEntry = null;
     String completionTime = null;
     long startMillisecs = System.currentTimeMillis();
@@ -704,17 +681,12 @@
            connection.processSearch(taskEntry.getDN(),
                                     SearchScope.BASE_OBJECT,
                                     filter);
-      try
-      {
-        resultEntry = searchOperation.getSearchEntries().getFirst();
-      } catch (Exception e)
+      if (searchOperation.getSearchEntries().isEmpty())
       {
         continue;
       }
-      completionTime =
-           resultEntry.getAttributeValue(completionTimeType,
-                                         DirectoryStringSyntax.DECODER);
-
+      resultEntry = searchOperation.getSearchEntries().get(0);
+      completionTime = resultEntry.getAttributeValue(completionTimeType, DECODER);
       if (completionTime == null)
       {
         if (System.currentTimeMillis() - startMillisecs > 1000*30)
@@ -730,9 +702,7 @@
     // Check that the task state is as expected.
     AttributeType taskStateType =
          DirectoryServer.getAttributeType(ATTR_TASK_STATE.toLowerCase());
-    String stateString =
-         resultEntry.getAttributeValue(taskStateType,
-                                       DirectoryStringSyntax.DECODER);
+    String stateString = resultEntry.getAttributeValue(taskStateType, DECODER);
     TaskState taskState = TaskState.fromString(stateString);
     assertEquals(taskState, TaskState.COMPLETED_SUCCESSFULLY,
                  "The task completed in an unexpected state");
@@ -767,36 +737,33 @@
   protected void addTask(Entry taskEntry, ResultCode expectedResult,
       Message errorMessage) throws Exception
   {
+    TRACER.debugInfo("AddTask/" + taskEntry);
+
+    // Change config of DS to launch the total update task
+    AddOperation addOperation = connection.processAdd(taskEntry);
+    assertEquals(addOperation.getResultCode(), expectedResult,
+        "Result of ADD operation of the task is: "
+            + addOperation.getResultCode() + " Expected:" + expectedResult
+            + " Details:" + addOperation.getErrorMessage()
+            + addOperation.getAdditionalLogItems());
+
+    if (expectedResult != ResultCode.SUCCESS)
     {
-      TRACER.debugInfo("AddTask/" + taskEntry);
-
-      // Change config of DS to launch the total update task
-      AddOperation addOperation = getRootConnection().processAdd(taskEntry);
-
-      assertEquals(addOperation.getResultCode(), expectedResult,
-          "Result of ADD operation of the task is: "
-          + addOperation.getResultCode()
-          + " Expected:"
-          + expectedResult + " Details:" + addOperation.getErrorMessage()
-          + addOperation.getAdditionalLogItems());
-
-      if (expectedResult != ResultCode.SUCCESS)
-      {
-        assertTrue(addOperation.getErrorMessage().toString().startsWith(errorMessage.toString()),
-            "Error MsgID of the task <" + addOperation.getErrorMessage() + "> equals <" + errorMessage + ">");
-        TRACER.debugInfo("Create config task: <"+ errorMessage.getDescriptor().getId()
-                + addOperation.getErrorMessage() + ">");
-      }
-      else
-      {
-        waitTaskState(taskEntry, TaskState.RUNNING, null);
-      }
-
-      // Entry will be removed at the end of the test
-      entriesToCleanup.add(taskEntry.getDN());
-
-      TRACER.debugInfo("AddedTask/" + taskEntry.getDN());
+      Assertions.assertThat(addOperation.getErrorMessage().toString())
+          .startsWith(errorMessage.toString());
+      TRACER.debugInfo("Create config task: <"
+          + errorMessage.getDescriptor().getId()
+          + addOperation.getErrorMessage() + ">");
     }
+    else
+    {
+      waitTaskState(taskEntry, TaskState.RUNNING, null);
+    }
+
+    // Entry will be removed at the end of the test
+    entriesToCleanup.add(taskEntry.getDN());
+
+    TRACER.debugInfo("AddedTask/" + taskEntry.getDN());
   }
 
   protected void waitTaskState(Entry taskEntry, TaskState expectedTaskState,
@@ -816,28 +783,27 @@
       // Check that the task state is as expected.
       AttributeType taskStateType =
           DirectoryServer.getAttributeType(ATTR_TASK_STATE.toLowerCase());
-      String stateString =
-          resultEntry.getAttributeValue(taskStateType, DirectoryStringSyntax.DECODER);
+      String stateString = resultEntry.getAttributeValue(taskStateType, DECODER);
       taskState = TaskState.fromString(stateString);
 
       Thread.sleep(500);
       cpt--;
     }
-    while ((taskState != expectedTaskState)
-        && (taskState != TaskState.STOPPED_BY_ERROR)
-        && (taskState != TaskState.COMPLETED_SUCCESSFULLY) && (cpt > 0));
+    while (taskState != expectedTaskState
+        && taskState != TaskState.STOPPED_BY_ERROR
+        && taskState != TaskState.COMPLETED_SUCCESSFULLY
+        && cpt > 0);
 
     // Check that the task contains some log messages.
     AttributeType logMessagesType =
         DirectoryServer.getAttributeType(ATTR_TASK_LOG_MESSAGES.toLowerCase());
     List<String> logMessages = new ArrayList<String>();
-    resultEntry.getAttributeValues(logMessagesType,
-        DirectoryStringSyntax.DECODER, logMessages);
+    resultEntry.getAttributeValues(logMessagesType, DECODER, logMessages);
 
-    if ((taskState != TaskState.COMPLETED_SUCCESSFULLY)
-        && (taskState != TaskState.RUNNING))
+    if (taskState != TaskState.COMPLETED_SUCCESSFULLY
+        && taskState != TaskState.RUNNING)
     {
-      assertTrue(logMessages.size() != 0,
+      assertFalse(logMessages.isEmpty(),
           "No log messages were written to the task entry on a failed task");
     }
     if (logMessages.size() != 0)
@@ -850,8 +816,8 @@
       }
     }
 
-    if ((expectedTaskState == TaskState.RUNNING)
-        && (taskState == TaskState.COMPLETED_SUCCESSFULLY))
+    if (expectedTaskState == TaskState.RUNNING
+        && taskState == TaskState.COMPLETED_SUCCESSFULLY)
     {
       // We usually wait the running state after adding the task
       // and if the task is fast enough then it may be already done
@@ -869,25 +835,19 @@
    */
   protected void addTestEntriesToDB(String... ldifEntries) throws Exception
   {
+    // Change config of DS to launch the total update task
+    for (String ldifEntry : ldifEntries)
     {
-      // Change config of DS to launch the total update task
-      InternalClientConnection connection =
-        InternalClientConnection.getRootConnection();
-
-      for (String ldifEntry : ldifEntries)
+      Entry entry = TestCaseUtils.entryFromLdifString(ldifEntry);
+      AddOperation addOp = connection.processAdd(entry);
+      if (addOp.getResultCode() != ResultCode.SUCCESS)
       {
-        Entry entry = TestCaseUtils.entryFromLdifString(ldifEntry);
-        AddOperation addOp = connection.processAdd(entry);
-        if (addOp.getResultCode() != ResultCode.SUCCESS)
-        {
-          TRACER.debugInfo("Failed to add entry " + entry.getDN() +
-              "Result code = : " + addOp.getResultCode());
-        }
-        else
-        {
-          TRACER.debugInfo(entry.getDN() +
-              " added " + addOp.getResultCode());
-        }
+        TRACER.debugInfo("Failed to add entry " + entry.getDN()
+            + "Result code = : " + addOp.getResultCode());
+      }
+      else
+      {
+        TRACER.debugInfo(entry.getDN() + " added " + addOp.getResultCode());
       }
     }
   }
@@ -902,16 +862,12 @@
   {
     int count = 10;
     String found = null;
-    while ((count> 0) && (found == null))
+    while (count > 0 && found == null)
     {
       Thread.sleep(100);
 
       final Lock lock = LockManager.lockRead(dn);
-      if (lock == null)
-      {
-        throw new Exception("could not lock entry " + dn);
-      }
-
+      assertNotNull(lock, "could not lock entry " + dn);
       try
       {
         Entry newEntry = DirectoryServer.getEntry(dn);
@@ -931,8 +887,7 @@
       }
       count --;
     }
-    if (found == null)
-      throw new Exception("Entry: " + dn + " Could not be found.");
+    assertNotNull(found, "Entry: " + dn + " Could not be found.");
     return found;
   }
 
diff --git a/opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java b/opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java
index f310387..42f330f 100644
--- a/opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java
+++ b/opendj-sdk/opends/tests/unit-tests-testng/src/server/org/opends/server/replication/UpdateOperationTest.java
@@ -590,7 +590,7 @@
         DN.decode("cn=something,ou=People," + TEST_ROOT_DN_STRING), mods,
         user1entryUUID);
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    int AlertCount = DummyAlertHandler.getAlertCount();
+      int alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(modMsg);
 
     // check that the modify has been applied as if the entry had been renamed.
@@ -598,11 +598,7 @@
                            "telephonenumber", "01 02 45", 10000, true);
       assertTrue(found, "The modification has not been correctly replayed.");
     assertEquals(getMonitorDelta(), 1);
-
-    // check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
+      assertConflictAutomaticallyResolved(alertCount);
 
     /*
      * Test that modify conflict resolution is able to detect that
@@ -618,7 +614,7 @@
         user1entryUUID);
 
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(modMsg);
 
     // check that the modify has been applied.
@@ -649,7 +645,7 @@
     modMsg = new ModifyMsg(gen.newCSN(),
         user1dn, mods, "10000000-9abc-def0-1234-1234567890ab");
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(modMsg);
 
     // check that the modify has not been applied
@@ -659,12 +655,7 @@
       assertFalse(found,
           "The modification has been replayed while it should not.");
     assertEquals(getMonitorDelta(), 1);
-
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
-
+      assertConflictAutomaticallyResolved(alertCount);
 
 
     /*
@@ -679,17 +670,14 @@
     DN delDN = DN.decode("cn=anotherdn,ou=People," + TEST_ROOT_DN_STRING);
     DeleteMsg delMsg = new DeleteMsg(delDN, gen.newCSN(), user1entryUUID);
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(delMsg);
 
     // check that the delete operation has been applied
     assertNull(getEntry(personWithUUIDEntry.getDN(), 10000, false),
         "The DELETE replication message was not replayed");
     assertEquals(getMonitorDelta(), 1);
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
+      assertConflictAutomaticallyResolved(alertCount);
 
     /*
      * Test that two adds with the same DN but a different unique ID result
@@ -705,7 +693,7 @@
 
     //  create an entry with the same DN and another unique ID
     updateMonitorCount(baseDN, unresolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
       broker.publish(addMsg(gen, personWithSecondUniqueID, user1entrysecondUUID, baseUUID));
 
     //  Check that the entry has been renamed and created in the local DS.
@@ -715,11 +703,8 @@
     assertNotNull(resultEntry,
         "The ADD replication message was not applied");
     assertEquals(getMonitorDelta(), 1);
-    assertConflictAttribute(resultEntry);
-    // Check that there was an administrative alert generated
-    // because the conflict has not been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount+1,
-        "An alert was not generated when resolving conflicts");
+      assertConflictAttributeExists(resultEntry);
+      assertNewAlertsGenerated(alertCount, 1);
 
 
     //  delete the entries to clean the database.
@@ -747,7 +732,7 @@
         personWithUUIDEntry.getObjectClassAttribute(),
         personWithUUIDEntry.getAttributes(), new ArrayList<Attribute>());
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(addMsg);
 
     //  Check that the entry has been created in the local DS.
@@ -755,10 +740,7 @@
       assertNotNull(getEntry(newPersonDN, 10000, true),
           "The ADD replication message was not applied");
     assertEquals(getMonitorDelta(), 1);
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
+      assertConflictAutomaticallyResolved(alertCount);
 
 
     /*
@@ -771,18 +753,14 @@
      */
     delMsg = new DeleteMsg(newPersonDN, gen.newCSN(), "11111111-9abc-def0-1234-1234567890ab");
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(delMsg);
 
     // check that the delete operation has not been applied
       assertNotNull(getEntry(newPersonDN, 10000, true),
           "The DELETE replication message was replayed when it should not");
     assertEquals(getMonitorDelta(), 1);
-
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
+      assertConflictAutomaticallyResolved(alertCount);
 
 
     /*
@@ -793,14 +771,13 @@
      * To simulate this try to rename an entry below an entry that does
      * not exist but giving the unique ID of an existing entry.
      */
-
     ModifyDNMsg  modDnMsg = new ModifyDNMsg(
         newPersonDN, gen.newCSN(),
         user1entryUUID, baseUUID, false,
         "uid=wrong, ou=people," + TEST_ROOT_DN_STRING,
         "uid=newrdn");
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(modDnMsg);
 
     resultEntry = getEntry(
@@ -810,22 +787,17 @@
     assertNotNull(resultEntry,
       "The modify dn was not or badly replayed");
     assertEquals(getMonitorDelta(), 1);
-
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
+      assertConflictAutomaticallyResolved(alertCount);
 
 
     /*
      * same test but by giving a bad entry DN
      */
-
     DN modDN = DN.decode("uid=wrong,ou=People," + TEST_ROOT_DN_STRING);
     modDnMsg = new ModifyDNMsg(modDN, gen.newCSN(),
         user1entryUUID, null, false, null, "uid=reallynewrdn");
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(modDnMsg);
 
     DN reallyNewDN = DN.decode("uid=reallynewrdn,ou=People," + TEST_ROOT_DN_STRING);
@@ -834,11 +806,7 @@
       assertNotNull(getEntry(reallyNewDN, 10000, true),
           "The modify dn was not or badly replayed");
     assertEquals(getMonitorDelta(), 1);
-
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
+      assertConflictAutomaticallyResolved(alertCount);
 
 
     /*
@@ -858,7 +826,7 @@
                                user1entrysecondUUID, baseUUID, false,
                                baseDN.toString(), "uid=reallynewrdn");
     updateMonitorCount(baseDN, unresolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(modDnMsg);
 
       // check that the second entry has been renamed
@@ -867,12 +835,8 @@
       assertNotNull(getEntry(dn, 10000, true),
           "The modifyDN was not or incorrectly replayed");
     assertEquals(getMonitorDelta(), 1);
-    assertConflictAttribute(resultEntry);
-
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount+1,
-        "An alert was not generated when resolving conflicts");
+      assertConflictAttributeExists(resultEntry);
+      assertNewAlertsGenerated(alertCount, 1);
 
 
     // delete the entries to clean the database
@@ -942,7 +906,7 @@
 
     // - publish msg
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(addMsg);
 
     // - check that the DN has been changed to baseDn2
@@ -951,11 +915,7 @@
       assertNotNull(getEntry(DN.decode("uid=new person,ou=baseDn2," + baseDN), 10000, true),
           "The ADD replication message was NOT applied under ou=baseDn2," + baseDN);
     assertEquals(getMonitorDelta(), 1);
-
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
+      assertConflictAutomaticallyResolved(alertCount);
 
 
     //
@@ -979,7 +939,7 @@
         "entryUUID = " + domain3uid + "+dc=domain3,ou=people," + TEST_ROOT_DN_STRING);
 
     updateMonitorCount(baseDN, unresolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
 
     // delete domain1
     delMsg = new DeleteMsg(domain1dn, olderCSN, domain1uid);
@@ -1003,12 +963,7 @@
 
     // check that unresolved conflict count has been incremented
     assertEquals(getMonitorDelta(), 1);
-
-    // Check that an administrative alert was generated
-    // because the conflict has not been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount+2,
-        "An alert was incorrectly generated when resolving conflicts");
-
+      assertNewAlertsGenerated(alertCount, 2);
 
     // delete the resulting entries for the next test
     delEntry(conflictDomain2dn);
@@ -1029,7 +984,7 @@
     domain3uid = getEntryUUID(domain3dn);
 
     updateMonitorCount(baseDN, unresolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
 
     // delete domain1
     delMsg = new DeleteMsg(domain1dn, gen.newCSN(), domain1uid);
@@ -1080,7 +1035,7 @@
         "uid=wrong, ou=people," + TEST_ROOT_DN_STRING,
         "uid=newrdn");
     updateMonitorCount(baseDN, resolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     broker.publish(modDnMsg);
     // unfortunately it is difficult to check that the operation
     // did not do anything.
@@ -1097,18 +1052,14 @@
     // if the monitor counter did not get incremented after 200sec
     // then something got wrong.
     assertTrue(count < 200);
-
-    // Check that there was no administrative alert generated
-    // because the conflict has been automatically resolved.
-    assertEquals(DummyAlertHandler.getAlertCount(), AlertCount,
-        "An alert was incorrectly generated when resolving conflicts");
+      assertConflictAutomaticallyResolved(alertCount);
 
     /*
      * Check that a conflict is detected when an entry is
      * moved below an entry that does not exist.
      */
     updateMonitorCount(baseDN, unresolvedMonitorAttr);
-    AlertCount = DummyAlertHandler.getAlertCount();
+      alertCount = DummyAlertHandler.getAlertCount();
     modDnMsg = new ModifyDNMsg(
         newPersonDN, gen.newCSN(),
         "33333333-3333-3333-3333-333333333333",
@@ -1142,16 +1093,35 @@
   }
 
   /**
+   * Check that there was an administrative alert generated because the conflict
+   * has not been automatically resolved.
+   */
+  private void assertNewAlertsGenerated(int oldAlertCount, int expectedNbNewAlerts)
+  {
+    assertEquals(DummyAlertHandler.getAlertCount(), oldAlertCount + expectedNbNewAlerts,
+        "An alert was not generated when resolving conflicts");
+  }
+
+  /**
+   * Check that there was no administrative alert generated because the conflict
+   * has been automatically resolved.
+   */
+  private void assertConflictAutomaticallyResolved(int expectedAlertCount)
+  {
+    assertEquals(DummyAlertHandler.getAlertCount(), expectedAlertCount,
+        "Expected no new alert to be generated when automatically resolving conflicts");
+  }
+
+  /**
    * Check that the given entry does contain the attribute that mark the
    * entry as conflicting.
    *
    * @param entry The entry that needs to be asserted.
    * @return A boolean indicating if the entry is correctly marked.
    */
-  private boolean assertConflictAttribute(Entry entry)
+  private boolean assertConflictAttributeExists(Entry entry)
   {
-    List<Attribute> attrs = entry.getAttribute("ds-sync-confict");
-    return attrs != null;
+    return entry.getAttribute("ds-sync-confict") != null;
   }
 
   @DataProvider(name="assured")
@@ -1198,31 +1168,12 @@
       assertTrue(DirectoryServer.entryExists(personEntry.getDN()),
       "The Add Entry operation failed");
       assertEquals(addOp.getResultCode(), ResultCode.SUCCESS);
-      {
-        // Check if the client has received the msg
-        ReplicationMsg msg = broker.receive();
-        Assertions.assertThat(msg).isInstanceOf(AddMsg.class);
-        AddMsg addMsg =  (AddMsg) msg;
-
-        Operation receivedOp = addMsg.createOperation(connection);
-        assertEquals(receivedOp.getOperationType(), OperationType.ADD,
-            "The received replication message is not an ADD msg : " + addMsg);
-        assertEquals(addMsg.getDN(), personEntry.getDN(),
-            "The received ADD replication message is not for the excepted DN : " + addMsg);
-      }
+      assertClientReceivesExpectedMsg(broker, AddMsg.class, personEntry.getDN());
 
       // Modify the entry
       List<Modification> mods = generatemods("telephonenumber", "01 02 45");
       connection.processModify(personEntry.getDN(), mods);
-
-      // See if the client has received the msg
-      ReplicationMsg msg = broker.receive();
-      Assertions.assertThat(msg).isInstanceOf(ModifyMsg.class);
-      ModifyMsg modMsg = (ModifyMsg) msg;
-
-      modMsg.createOperation(connection);
-      assertEquals(modMsg.getDN(), personEntry.getDN(),
-      "The received MODIFY replication message is not for the excepted DN : " + modMsg);
+      assertClientReceivesExpectedMsg(broker, ModifyMsg.class, personEntry.getDN());
 
       // Modify the entry DN
       DN newDN = DN.decode("uid= new person,ou=People," + TEST_ROOT_DN_STRING);
@@ -1233,28 +1184,13 @@
       "The MOD_DN operation didn't create the new person entry");
       assertFalse(DirectoryServer.entryExists(personEntry.getDN()),
       "The MOD_DN operation didn't delete the old person entry");
-
-      // See if the client has received the msg
-      msg = broker.receive();
-      Assertions.assertThat(msg).isInstanceOf(ModifyDNMsg.class);
-      ModifyDNMsg moddnMsg = (ModifyDNMsg) msg;
-      moddnMsg.createOperation(connection);
-
-      assertEquals(moddnMsg.getDN(), personEntry.getDN(),
-      "The received MODIFY_DN message is not for the excepted DN : " + moddnMsg);
+      assertClientReceivesExpectedMsg(broker, ModifyDNMsg.class, personEntry.getDN());
 
       // Delete the entry
       connection.processDelete(newDN);
       assertFalse(DirectoryServer.entryExists(newDN),
           "Unable to delete the new person Entry");
-
-      // See if the client has received the msg
-      msg = broker.receive();
-      Assertions.assertThat(msg).isInstanceOf(DeleteMsg.class);
-      DeleteMsg delMsg = (DeleteMsg) msg;
-      delMsg.createOperation(connection);
-      assertEquals(delMsg.getDN(), newDN,
-      "The received DELETE message is not for the excepted DN : " + delMsg);
+      assertClientReceivesExpectedMsg(broker, DeleteMsg.class, newDN);
 
       /*
        * Now check that when we send message to the ReplicationServer
@@ -1276,7 +1212,7 @@
       /*
        * Test the reception of Modify Msg
        */
-      modMsg = new ModifyMsg(gen.newCSN(), personWithUUIDEntry.getDN(),
+      ModifyMsg modMsg = new ModifyMsg(gen.newCSN(), personWithUUIDEntry.getDN(),
           mods, user1entryUUID);
       modMsg.setAssured(assured);
       broker.publish(modMsg);
@@ -1300,7 +1236,7 @@
       /*
        * Test the Reception of Modify Dn Msg
        */
-      moddnMsg = new ModifyDNMsg(personWithUUIDEntry.getDN(),
+      ModifyDNMsg moddnMsg = new ModifyDNMsg(personWithUUIDEntry.getDN(),
           gen.newCSN(),
           user1entryUUID, null,
           true, null, "uid= new person");
@@ -1313,7 +1249,7 @@
       /*
        * Test the Reception of Delete Msg
        */
-      delMsg = new DeleteMsg(newDN, gen.newCSN(), user1entryUUID);
+      DeleteMsg delMsg = new DeleteMsg(newDN, gen.newCSN(), user1entryUUID);
       delMsg.setAssured(assured);
       broker.publish(delMsg);
 
@@ -1326,6 +1262,40 @@
     }
   }
 
+  private void assertClientReceivesExpectedMsg(ReplicationBroker broker,
+      Class<? extends LDAPUpdateMsg> type, DN expectedDN) throws Exception
+  {
+    final ReplicationMsg msg = broker.receive();
+    Assertions.assertThat(msg).isInstanceOf(type);
+    final LDAPUpdateMsg opMsg = (LDAPUpdateMsg) msg;
+    final OperationType opType = getOperationType(opMsg);
+    final Operation receivedOp = opMsg.createOperation(connection);
+    assertEquals(receivedOp.getOperationType(), opType,
+        "The received replication message is not of corrct type. msg : " + opMsg);
+    assertEquals(opMsg.getDN(), expectedDN, "The received " + opType
+        + " replication message is not for the expected DN : " + opMsg);
+  }
+
+  private OperationType getOperationType(LDAPUpdateMsg msg)
+  {
+    if (msg instanceof AddMsg)
+    {
+      return OperationType.ADD;
+    }
+    else if (msg instanceof DeleteMsg)
+    {
+      return OperationType.DELETE;
+    }
+    else if (msg instanceof ModifyMsg)
+    {
+      return OperationType.MODIFY;
+    }
+    else if (msg instanceof ModifyDNMsg)
+    {
+      return OperationType.MODIFY_DN;
+    }
+    throw new RuntimeException("Unhandled type: " + msg.getClass());
+  }
 
   /**
    * Test case for

--
Gitblit v1.10.0