You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2016/10/31 20:51:22 UTC

[1/8] incubator-geode git commit: Convert from ManagementTestCase to ManagementTestRule [Forced Update!]

Repository: incubator-geode
Updated Branches:
  refs/heads/feature/GEODE-1930 a83f8c02f -> 86a3fb5a6 (forced update)


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java
index 2330031..446ea2e 100644
--- a/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java
@@ -16,98 +16,66 @@
  */
 package org.apache.geode.management.bean.stats;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
+import static com.jayway.awaitility.Awaitility.*;
 import static org.junit.Assert.*;
 
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
+import java.lang.management.ManagementFactory;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 
 import javax.management.ObjectName;
 
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.DiskStoreStats;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.ManagementTestBase;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.ManagementTestRule;
+import org.apache.geode.management.Manager;
+import org.apache.geode.management.Member;
 import org.apache.geode.management.MemberMXBean;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.management.internal.beans.MemberMBean;
-import org.apache.geode.management.internal.beans.MemberMBeanBridge;
-import org.apache.geode.test.dunit.Assert;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.junit.categories.DistributedTest;
 
-/**
- */
 @Category(DistributedTest.class)
-public class DistributedSystemStatsDUnitTest extends ManagementTestBase{
-  
-  private static final long serialVersionUID = 1L;
+@SuppressWarnings("serial")
+public class DistributedSystemStatsDUnitTest {
 
-  public DistributedSystemStatsDUnitTest() {
-    super();
-  }
+  @Manager
+  private VM manager;
+
+  @Member
+  private VM[] members;
+
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
   @Test
   public void testDistributedSystemStats() throws Exception {
-    initManagement(true);
+    this.manager.invoke("verifyMBeans", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      assertNotNull(cache);
 
-    for(VM vm : managedNodeList){
-      setDiskStats(vm);
-    }
-    verifyDiskStats(managingNode);
-  }
-  
-  @SuppressWarnings("serial")
-  public void setDiskStats(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Set Member Stats") {
-      public void run() {
-        MemberMBean bean = (MemberMBean) managementService.getMemberMXBean();
-        MemberMBeanBridge bridge = bean.getBridge();
-        DiskStoreStats diskStoreStats = new DiskStoreStats(basicGetSystem(), "test");
-        bridge.addDiskStoreStats(diskStoreStats);
-        diskStoreStats.startRead();
-        diskStoreStats.startWrite();
-        diskStoreStats.startBackup();
-        diskStoreStats.startRecovery();
-        diskStoreStats.incWrittenBytes(20, true);
-        diskStoreStats.startFlush();
-        diskStoreStats.setQueueSize(10);
-      }
-    });
-  }
+      SystemManagementService service = (SystemManagementService) ManagementService.getManagementService(cache);
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      assertNotNull(distributedSystemMXBean);
+
+      Set<DistributedMember> otherMemberSet = cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+      assertEquals(3, otherMemberSet.size());
+
+      for (DistributedMember member : otherMemberSet) {
+        ObjectName memberMXBeanName = service.getMemberMBeanName(member);
+        await().atMost(2, TimeUnit.MINUTES).until(() -> assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered(memberMXBeanName)));
 
-  @SuppressWarnings("serial")
-  public void verifyDiskStats(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Set Member Stats") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-        Set<DistributedMember> otherMemberSet = cache.getDistributionManager()
-            .getOtherNormalDistributionManagerIds();
-         
-        for (DistributedMember member : otherMemberSet) {
-          ObjectName memberMBeanName;
-          try {
-            memberMBeanName = service.getMemberMBeanName(member);
-            waitForProxy(memberMBeanName, MemberMXBean.class);
-            MemberMXBean memberBean = service.getMBeanProxy(memberMBeanName, MemberMXBean.class);
-            waitForRefresh(2, memberMBeanName);
-          } catch (NullPointerException e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          } catch (Exception e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          }
-        }
+        MemberMXBean memberMXBean = service.getMBeanProxy(memberMXBeanName, MemberMXBean.class);
+        assertNotNull(memberMXBean);
 
+        final long lastRefreshTime = service.getLastUpdateTime(memberMXBeanName);
+        await().atMost(1, TimeUnit.MINUTES).until(() -> assertTrue(service.getLastUpdateTime(memberMXBeanName) > lastRefreshTime));
       }
     });
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java
index 7270a2b..1554cd6 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java
@@ -26,7 +26,6 @@ import org.junit.experimental.categories.Category;
 
 import org.apache.geode.test.junit.categories.UnitTest;
 
-
 @Category(UnitTest.class)
 public class QueryDataFunctionApplyLimitClauseTest {
 
@@ -47,8 +46,7 @@ public class QueryDataFunctionApplyLimitClauseTest {
   public void applyLimitClauseDoesNothingIfLimitClauseSpecified() {
     String limitClause = " LIMIT 50";
     String selectQueryWithLimit = selectQuery + limitClause;
-    assertThat(QueryDataFunction.applyLimitClause(selectQueryWithLimit, limit_10, queryResultSetLimit_100))
-      .isEqualTo(selectQueryWithLimit);
+    assertThat(QueryDataFunction.applyLimitClause(selectQueryWithLimit, limit_10, queryResultSetLimit_100)).isEqualTo(selectQueryWithLimit);
   }
 
   @Test
@@ -64,15 +62,13 @@ public class QueryDataFunctionApplyLimitClauseTest {
   @Test // GEODE-1907
   public void applyLimitClauseAddsQueryResultSetLimitIfMissingSpaceAfterFrom() {
     String selectQueryMissingSpaceAfterFrom = "SELECT * FROM/MyRegion";
-    assertThat(QueryDataFunction.applyLimitClause(selectQueryMissingSpaceAfterFrom, limit_0, queryResultSetLimit_100))
-      .isEqualTo(selectQueryMissingSpaceAfterFrom + " LIMIT " + queryResultSetLimit_100);
+    assertThat(QueryDataFunction.applyLimitClause(selectQueryMissingSpaceAfterFrom, limit_0, queryResultSetLimit_100)).isEqualTo(selectQueryMissingSpaceAfterFrom + " LIMIT " + queryResultSetLimit_100);
   }
 
   @Test
   public void applyLimitClauseDoesNotAddQueryResultSetLimitIfMissingSpaceAfterFromButLimitIsPresent() {
     String selectQueryMissingSpaceAfterFromWithLimit = "SELECT * FROM/MyRegion LIMIT " + limit_10;
-    assertThat(QueryDataFunction.applyLimitClause(selectQueryMissingSpaceAfterFromWithLimit, limit_0, queryResultSetLimit_100))
-      .isEqualTo(selectQueryMissingSpaceAfterFromWithLimit);
+    assertThat(QueryDataFunction.applyLimitClause(selectQueryMissingSpaceAfterFromWithLimit, limit_0, queryResultSetLimit_100)).isEqualTo(selectQueryMissingSpaceAfterFromWithLimit);
   }
 
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java
index 16f8f82..a93485d 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java
@@ -58,67 +58,49 @@ import org.apache.geode.test.junit.categories.DistributedTest;
  * This is for testing client IDs
  */
 @Category(DistributedTest.class)
-public class TestClientIdsDUnitTest extends JUnit4DistributedTestCase {
+@SuppressWarnings("serial")
+public class TestClientIdsDUnitTest extends ManagementTestBase {
 
   private static final String k1 = "k1";
   private static final String k2 = "k2";
-
   private static final String client_k1 = "client-k1";
-
   private static final String client_k2 = "client-k2";
-
-  /** name of the test region */
   private static final String REGION_NAME = "ClientHealthStatsDUnitTest_Region";
 
   private static VM server = null;
-
   private static VM client = null;
-
   private static VM client2 = null;
 
-  private static VM managingNode = null;
-
-  private ManagementTestBase helper;
-
-  @Override
-  public final void preSetUp() throws Exception {
-    this.helper = new ManagementTestBase(){};
-  }
-
   @Override
-  public final void postSetUp() throws Exception {
-    final Host host = Host.getHost(0);
-    managingNode = host.getVM(0);
-    server = host.getVM(1);
-    client = host.getVM(2);
-    client2 = host.getVM(3);
+  public final void postSetUpManagementTestBase() throws Exception {
+    server = Host.getHost(0).getVM(1);
+    client = Host.getHost(0).getVM(2);
+    client2 = Host.getHost(0).getVM(3);
   }
 
   @Override
-  public final void preTearDown() throws Exception {
-    helper.closeCache(managingNode);
-    helper.closeCache(server);
-    helper.closeCache(client);
-    helper.closeCache(client2);
+  public final void postTearDownManagementTestBase() throws Exception {
+    closeCache(server);
+    closeCache(client);
+    closeCache(client2);
 
     disconnectFromDS();
   }
 
   @Test
   public void testClientIds() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
+    createManagementCache(managingNode);
+    startManagingNode(managingNode);
     int port = (Integer) createServerCache(server);
-    DistributedMember serverMember = helper.getMember(server);
+    DistributedMember serverMember = getMember(server);
     createClientCache(client, NetworkUtils.getServerHostName(server.getHost()), port);
     createClientCache(client2, NetworkUtils.getServerHostName(server.getHost()), port);
     put(client);
     put(client2);
     verifyClientIds(managingNode, serverMember, port);
-    helper.stopManagingNode(managingNode);
+    stopManagingNode(managingNode);
   }
 
-  @SuppressWarnings("serial")
   private Object createServerCache(VM vm) {
     return vm.invoke(new SerializableCallable("Create Server Cache") {
       public Object call() {
@@ -132,7 +114,6 @@ public class TestClientIdsDUnitTest extends JUnit4DistributedTestCase {
     });
   }
 
-  @SuppressWarnings("serial")
   private void createClientCache(VM vm, final String host, final Integer port1) {
     vm.invoke(new SerializableCallable("Create Client Cache") {
 
@@ -158,7 +139,7 @@ public class TestClientIdsDUnitTest extends JUnit4DistributedTestCase {
   }
 
   private Integer createServerCache(DataPolicy dataPolicy) throws Exception {
-    Cache cache = helper.createCache(false);
+    Cache cache = createCache(false);
     AttributesFactory factory = new AttributesFactory();
     factory.setScope(Scope.DISTRIBUTED_ACK);
     factory.setDataPolicy(dataPolicy);
@@ -202,7 +183,6 @@ public class TestClientIdsDUnitTest extends JUnit4DistributedTestCase {
   /**
    * get member id
    */
-  @SuppressWarnings("serial")
   protected static DistributedMember getMember() throws Exception {
     GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
     return cache.getDistributedSystem().getDistributedMember();
@@ -213,7 +193,6 @@ public class TestClientIdsDUnitTest extends JUnit4DistributedTestCase {
    * 
    * @param vm
    */
-  @SuppressWarnings("serial")
   protected void verifyClientIds(final VM vm,
       final DistributedMember serverMember, final int serverPort) {
     SerializableRunnable verifyCacheServerRemote = new SerializableRunnable(
@@ -262,7 +241,6 @@ public class TestClientIdsDUnitTest extends JUnit4DistributedTestCase {
    * 
    * @param vm
    */
-  @SuppressWarnings("serial")
   protected void put(final VM vm) {
     SerializableRunnable put = new SerializableRunnable("put") {
       public void run() {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java
index a94cc93..380b741 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java
@@ -17,6 +17,9 @@
 package org.apache.geode.management.internal.pulse;
 
 import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.NetworkUtils.*;
+import static org.apache.geode.test.dunit.Wait.*;
 import static org.junit.Assert.*;
 
 import java.util.Properties;
@@ -34,275 +37,175 @@ import org.apache.geode.cache.Scope;
 import org.apache.geode.cache.client.PoolManager;
 import org.apache.geode.cache.client.internal.PoolImpl;
 import org.apache.geode.cache.server.CacheServer;
-import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.internal.AvailablePort;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.management.DistributedSystemMXBean;
 import org.apache.geode.management.ManagementService;
 import org.apache.geode.management.ManagementTestBase;
-import org.apache.geode.test.dunit.Assert;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.NetworkUtils;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
 import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
  * This is for testing subscriptions
  */
 @Category(DistributedTest.class)
-public class TestSubscriptionsDUnitTest extends JUnit4DistributedTestCase {
+@SuppressWarnings("serial")
+public class TestSubscriptionsDUnitTest extends ManagementTestBase {
 
-  private static final String k1 = "k1";
-  private static final String k2 = "k2";
-  private static final String client_k1 = "client-k1";
-
-  private static final String client_k2 = "client-k2";
   private static final String REGION_NAME = TestSubscriptionsDUnitTest.class.getSimpleName() + "_Region";
+
+  private static final String KEY1 = "k1";
+  private static final String KEY2 = "k2";
+  private static final String CLIENT_VALUE1 = "client-k1";
+  private static final String CLIENT_VALUE2 = "client-k2";
+
   private static VM server = null;
   private static VM client = null;
   private static VM client2 = null;
-  private static VM managingNode = null;
-  private ManagementTestBase helper;
-
-  @Override
-  public final void preSetUp() throws Exception {
-    this.helper = new ManagementTestBase(){};
-  }
-
-  @Override
-  public final void postSetUp() throws Exception {
-    final Host host = Host.getHost(0);
-    managingNode = host.getVM(0);
-    server = host.getVM(1);
-    client = host.getVM(2);
-    client2 = host.getVM(3);
-  }
 
   @Override
-  public final void preTearDown() throws Exception {
-    helper.closeCache(managingNode);
-    helper.closeCache(server);
-    helper.closeCache(client);
-    helper.closeCache(client2);
-    disconnectFromDS();
+  public final void postSetUpManagementTestBase() throws Exception {
+    server = getHost(0).getVM(1);
+    client = getHost(0).getVM(2);
+    client2 = getHost(0).getVM(3);
   }
 
   @Test
-  public void testNoOfSubscription() throws Exception {
+  public void testNumSubscriptions() throws Exception {
+    createManagementCache(managingNode);
+    startManagingNode(managingNode);
 
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
+    int port = createServerCache(server);
+    getMember(server);
+
+    createClientCache(client, getServerHostName(server.getHost()), port);
+    createClientCache(client2, getServerHostName(server.getHost()), port);
 
-    int port = (Integer) createServerCache(server);
-    DistributedMember serverMember = helper.getMember(server);
-    createClientCache(client, NetworkUtils.getServerHostName(server.getHost()), port);
-    createClientCache(client2, NetworkUtils.getServerHostName(server.getHost()), port);
     put(client);
     put(client2);
+
     registerInterest(client);
     registerInterest(client2);
-    verifyClientStats(managingNode, serverMember, port);
-    helper.stopManagingNode(managingNode);
+
+    verifyNumSubscriptions(managingNode);
+
+    stopManagingNode(managingNode);
   }
 
-  @SuppressWarnings("serial")
-  private Object createServerCache(VM vm) {
-    return vm.invoke(new SerializableCallable(
-        "Create Server Cache in TestSubscriptionsDUnitTest") {
-
-      public Object call() {
-        try {
-          return createServerCache();
-        } catch (Exception e) {
-          fail("Error while createServerCache in TestSubscriptionsDUnitTest"
-              + e);
-        }
-        return null;
-      }
+  private int createServerCache(VM vm) {
+    return vm.invoke("Create Server Cache in TestSubscriptionsDUnitTest", () -> {
+      return createServerCache();
     });
   }
 
-  @SuppressWarnings("serial")
-  private void createClientCache(VM vm, final String host, final Integer port1) {
-    vm.invoke(new SerializableCallable(
-        "Create Client Cache in TestSubscriptionsDUnitTest") {
-
-      public Object call() {
-        try {
-          createClientCache(host, port1);
-        } catch (Exception e) {
-          fail("Error while createClientCache in TestSubscriptionsDUnitTest "
-              + e);
-        }
-        return null;
-      }
+  private void createClientCache(VM vm, final String host, final int port1) {
+    vm.invoke("Create Client Cache in TestSubscriptionsDUnitTest", () -> {
+      createClientCache(host, port1);
     });
   }
 
   private Cache createCache(Properties props) throws Exception {
     DistributedSystem ds = getSystem(props);
-    ds.disconnect();
-    ds = getSystem(props);
-    assertNotNull(ds);
-    Cache cache = (GemFireCacheImpl) CacheFactory.create(ds);
-    assertNotNull(cache);
+    Cache cache = CacheFactory.create(ds);
     return cache;
   }
 
-  private Integer createServerCache(DataPolicy dataPolicy) throws Exception {
-    Cache cache = helper.createCache(false);
+  private int createServerCache(DataPolicy dataPolicy) throws Exception {
+    Cache cache = createCache(false);
+
     AttributesFactory factory = new AttributesFactory();
     factory.setScope(Scope.DISTRIBUTED_ACK);
     factory.setDataPolicy(dataPolicy);
-    RegionAttributes attrs = factory.create();
-    cache.createRegion(REGION_NAME, attrs);
-    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+
+    cache.createRegion(REGION_NAME, factory.create());
+
     CacheServer server1 = cache.addCacheServer();
-    server1.setPort(port);
+    server1.setPort(0);
     server1.setNotifyBySubscription(true);
     server1.start();
-    return new Integer(server1.getPort());
+
+    return server1.getPort();
   }
 
-  public Integer createServerCache() throws Exception {
+  private int createServerCache() throws Exception {
     return createServerCache(DataPolicy.REPLICATE);
   }
 
-  public Cache createClientCache(String host, Integer port1) throws Exception {
-
+  private Cache createClientCache(String host, int port1) throws Exception {
     Properties props = new Properties();
     props.setProperty(MCAST_PORT, "0");
     props.setProperty(LOCATORS, "");
+
     Cache cache = createCache(props);
+
     PoolImpl p = (PoolImpl) PoolManager.createFactory()
-        .addServer(host, port1.intValue()).setSubscriptionEnabled(true)
-        .setThreadLocalConnections(true).setMinConnections(1)
-        .setReadTimeout(20000).setPingInterval(10000).setRetryAttempts(1)
-        .setSubscriptionEnabled(true).setStatisticInterval(1000)
-        .create("TestSubscriptionsDUnitTest");
+                                       .addServer(host, port1)
+                                       .setSubscriptionEnabled(true)
+                                       .setThreadLocalConnections(true)
+                                       .setMinConnections(1)
+                                       .setReadTimeout(20000)
+                                       .setPingInterval(10000)
+                                       .setRetryAttempts(1)
+                                       .setSubscriptionEnabled(true)
+                                       .setStatisticInterval(1000)
+                                       .create("TestSubscriptionsDUnitTest");
 
     AttributesFactory factory = new AttributesFactory();
     factory.setScope(Scope.DISTRIBUTED_ACK);
     factory.setPoolName(p.getName());
 
     RegionAttributes attrs = factory.create();
-    Region region = cache.createRegion(REGION_NAME, attrs);
-    return cache;
+    cache.createRegion(REGION_NAME, attrs);
 
+    return cache;
   }
 
-  /**
-   * get member id
-   */
-  @SuppressWarnings("serial")
-  protected static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
-  }
+  private void verifyNumSubscriptions(final VM vm) {
+    vm.invoke("TestSubscriptionsDUnitTest Verify Cache Server Remote", () -> {
+      final GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
 
-  /**
-   * Verify the Cache Server details
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void verifyClientStats(final VM vm,
-      final DistributedMember serverMember, final int serverPort) {
-    SerializableRunnable verifyCacheServerRemote = new SerializableRunnable(
-        "TestSubscriptionsDUnitTest Verify Cache Server Remote") {
-      public void run() {
-        final GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        try {
-          final WaitCriterion waitCriteria = new WaitCriterion() {
-            @Override
-            public boolean done() {
-              ManagementService service = ManagementService
-                  .getExistingManagementService(cache);
-              final DistributedSystemMXBean dsBean = service
-                  .getDistributedSystemMXBean();
-              if (dsBean != null) {
-                if (dsBean.getNumSubscriptions() > 1) {
-                  return true;
-                }
-              }
-              return false;
-            }
-
-            @Override
-            public String description() {
-              return "TestSubscriptionsDUnitTest wait for getDistributedSystemMXBean to complete and get results";
-            }
-          };
-          Wait.waitForCriterion(waitCriteria, 2 * 60 * 1000, 3000, true);
-          final DistributedSystemMXBean dsBean = ManagementService
-              .getExistingManagementService(cache).getDistributedSystemMXBean();
-          assertNotNull(dsBean);
-          LogWriterUtils.getLogWriter().info(
-              "TestSubscriptionsDUnitTest dsBean.getNumSubscriptions() ="
-                  + dsBean.getNumSubscriptions());
-          assertTrue(dsBean.getNumSubscriptions() == 2 ? true : false);
-        } catch (Exception e) {
-          fail("TestSubscriptionsDUnitTest Error while verifying subscription "
-              + e.getMessage());
+      waitForCriterion(new WaitCriterion() {
+        @Override
+        public boolean done() {
+          ManagementService service = ManagementService.getExistingManagementService(cache);
+          DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+          return distributedSystemMXBean != null & distributedSystemMXBean.getNumSubscriptions() > 1;
+        }
+        @Override
+        public String description() {
+          return "TestSubscriptionsDUnitTest wait for getDistributedSystemMXBean to complete and get results";
         }
+      }, 2 * 60 * 1000, 3000, true);
 
-      }
-    };
-    vm.invoke(verifyCacheServerRemote);
+      DistributedSystemMXBean distributedSystemMXBean = ManagementService.getExistingManagementService(cache).getDistributedSystemMXBean();
+      assertNotNull(distributedSystemMXBean);
+      assertEquals(2, distributedSystemMXBean.getNumSubscriptions());
+    });
   }
 
-  /**
-   * Verify the Cache Server details
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void registerInterest(final VM vm) {
-    SerializableRunnable put = new SerializableRunnable(
-        "TestSubscriptionsDUnitTest registerInterest") {
-      public void run() {
-        try {
-          Cache cache = GemFireCacheImpl.getInstance();
-          Region<Object, Object> r1 = cache.getRegion(Region.SEPARATOR
-              + REGION_NAME);
-          assertNotNull(r1);
-          r1.registerInterest(k1);
-          r1.registerInterest(k2);
-        } catch (Exception ex) {
-          Assert.fail("TestSubscriptionsDUnitTest failed while register Interest", ex);
-        }
-      }
+  private void registerInterest(final VM vm) {
+    vm.invoke("TestSubscriptionsDUnitTest registerInterest", () -> {
+      Cache cache = GemFireCacheImpl.getInstance();
+      Region<Object, Object> region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+      assertNotNull(region);
 
-    };
-    vm.invoke(put);
+      region.registerInterest(KEY1);
+      region.registerInterest(KEY2);
+    });
   }
 
-  @SuppressWarnings("serial")
-  protected void put(final VM vm) {
-    SerializableRunnable put = new SerializableRunnable("put") {
-      public void run() {
-        try {
-          Cache cache = GemFireCacheImpl.getInstance();
-          Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-          assertNotNull(r1);
-          r1.put(k1, client_k1);
-          assertEquals(r1.getEntry(k1).getValue(), client_k1);
-          r1.put(k2, client_k2);
-          assertEquals(r1.getEntry(k2).getValue(), client_k2);
-        } catch (Exception ex) {
-          Assert.fail("failed while put", ex);
-        }
-      }
+  private void put(final VM vm) {
+    vm.invoke("put", () -> {
+      Cache cache = GemFireCacheImpl.getInstance();
+      Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+      assertNotNull(region);
 
-    };
-    vm.invoke(put);
-  }
+      region.put(KEY1, CLIENT_VALUE1);
+      assertEquals(CLIENT_VALUE1, region.getEntry(KEY1).getValue());
 
+      region.put(KEY2, CLIENT_VALUE2);
+      assertEquals(CLIENT_VALUE2, region.getEntry(KEY2).getValue());
+    });
+  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java b/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java
index 5b65e32..808da37 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java
@@ -332,6 +332,61 @@ public class AsyncInvocation<V> implements Future<V> {
   }
 
   /**
+   * Waits if necessary for at most the given time for the computation
+   * to complete.
+   *
+   * @param  timeout the maximum time to wait
+   * @param  unit the time unit of the timeout argument
+   *
+   * @return this {@code AsyncInvocation}
+   *
+   * @throws AssertionError wrapping any {@code Exception} thrown by this
+   *         {@code AsyncInvocation}.
+   *
+   * @throws CancellationException if the computation was cancelled
+   *
+   * @throws ExecutionException if the computation threw an exception
+   *
+   * @throws InterruptedException if the current thread is interrupted.
+   *
+   * @throws TimeoutException if the wait timed out
+   */
+  public AsyncInvocation<V> await(final long timeout, final TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
+    long millis = unit.toMillis(timeout);
+    join(millis);
+    timeoutIfAlive(millis);
+    checkException();
+    return this;
+  }
+
+  /**
+   * Waits if necessary for at most the given time for the computation
+   * to complete.
+   *
+   * @return this {@code AsyncInvocation}
+   *
+   * @throws AssertionError wrapping any {@code Exception} thrown by this
+   *         {@code AsyncInvocation}.
+   *
+   * @throws AssertionError wrapping a {@code TimeoutException} if this
+   *         {@code AsyncInvocation} fails to complete within the default
+   *         timeout of 60 seconds as defined by {@link #DEFAULT_JOIN_MILLIS}.
+   *
+   * @throws CancellationException if the computation was cancelled
+   *
+   * @throws ExecutionException if the computation threw an exception
+   *
+   * @throws InterruptedException if the current thread is interrupted.
+   */
+  public AsyncInvocation<V> await() throws ExecutionException, InterruptedException {
+    try {
+      return await(DEFAULT_JOIN_MILLIS, TimeUnit.MILLISECONDS);
+    } catch (TimeoutException timeoutException) {
+      throw new AssertionError(timeoutException);
+    }
+  }
+
+  /**
    * Waits if necessary for the work to complete, and then returns the result
    * of this {@code AsyncInvocation}.
    *
@@ -371,10 +426,6 @@ public class AsyncInvocation<V> implements Future<V> {
    * @throws AssertionError wrapping any {@code Exception} thrown by this
    *         {@code AsyncInvocation}.
    *
-   * @throws AssertionError wrapping a {@code TimeoutException} if this
-   *         {@code AsyncInvocation} fails to complete within the default
-   *         timeout of 60 seconds as defined by {@link #DEFAULT_JOIN_MILLIS}.
-   *
    * @throws CancellationException if the computation was cancelled
    *
    * @throws ExecutionException if the computation threw an exception

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java b/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java
index 1ceb433..7ed1477 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java
@@ -24,13 +24,13 @@ import java.util.Map;
  * <code>DistributedTest</code> to invoke a <code>SerializableRunnable</code>
  * or <code>SerializableCallable</code> in a remote test <code>VM</code>.
  * 
- * These methods can be used directly: <code>Invoke.invokeInEveryVM(...)</code>, 
+ * These methods can be used directly: <code>Invoke.invokeInEveryVMAndController(...)</code>,
  * however, they are intended to be referenced through static import:
  *
  * <pre>
  * import static org.apache.geode.test.dunit.Invoke.*;
  *    ...
- *    invokeInEveryVM(...);
+ *    invokeInEveryVMAndController(...);
  * </pre>
  *
  * Extracted from DistributedTestCase.

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java b/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java
index ad43a77..4bc9f3e 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java
@@ -26,6 +26,7 @@ import java.util.concurrent.Callable;
 import com.jayway.awaitility.Awaitility;
 import hydra.MethExecutorResult;
 
+import org.apache.geode.internal.process.PidUnavailableException;
 import org.apache.geode.internal.process.ProcessUtils;
 import org.apache.geode.test.dunit.standalone.BounceResult;
 import org.apache.geode.test.dunit.standalone.RemoteDUnitVMIF;
@@ -95,7 +96,11 @@ public class VM implements Serializable {
    * Returns the process id of this {@code VM}.
    */
   public int getPid() {
-    return this.pid;
+//    try {
+      return invoke(() -> ProcessUtils.identifyPid());
+//    } catch (PidUnavailableException e) {
+//      return this.pid;
+//    }
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java b/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java
index eb0a475..338350b 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java
@@ -19,6 +19,8 @@ package org.apache.geode.test.dunit;
 import static org.apache.geode.test.dunit.Jitter.*;
 import static org.junit.Assert.*;
 
+import java.io.Serializable;
+
 import org.apache.logging.log4j.Logger;
 
 import org.apache.geode.internal.cache.LocalRegion;

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java b/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
index 40d0aba..921f2af 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
@@ -238,6 +238,11 @@ public abstract class JUnit4CacheTestCase extends JUnit4DistributedTestCase impl
     return getCache(false, factory);
   }
 
+  public final Cache getCache(final Properties properties) {
+    getSystem(properties);
+    return getCache();
+  }
+
   public final Cache getCache(final boolean client) {
     return getCache(client, null);
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java b/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
index 86971d4..bf8c7d5 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
@@ -114,7 +114,7 @@ public abstract class JUnit4DistributedTestCase implements DistributedTestFixtur
   }
 
   @Rule
-  public SerializableTestName testName = new SerializableTestName();
+  public SerializableTestName testNameForDistributedTestCase = new SerializableTestName();
 
   @BeforeClass
   public static final void initializeDistributedTestCase() {
@@ -125,7 +125,7 @@ public abstract class JUnit4DistributedTestCase implements DistributedTestFixtur
     if (this.distributedTestFixture != this) {
       return this.distributedTestFixture.getName();
     }
-    return this.testName.getMethodName();
+    return this.testNameForDistributedTestCase.getMethodName();
   }
 
   public final Class<? extends DistributedTestFixture> getTestClass() {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
index 44787fa..d41b756 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
@@ -45,14 +45,14 @@ public class DistributedDisconnectRule extends DistributedExternalResource {
   @Override
   protected void before() throws Throwable {
     if (this.disconnectBefore) {
-      invoker().invokeEverywhere(serializableRunnable());
+      invoker().invokeInEveryVMAndController(serializableRunnable());
     }
   }
 
   @Override
   protected void after() {
     if (this.disconnectAfter) {
-      invoker().invokeEverywhere(serializableRunnable());
+      invoker().invokeInEveryVMAndController(serializableRunnable());
     }
   }
 

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
index 62acec8..94ee903 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
@@ -47,7 +47,7 @@ public class DistributedRestoreSystemProperties extends RestoreSystemProperties
   @Override
   protected void before() throws Throwable {
     super.before();
-    this.invoker.remoteInvokeInEveryVMAndLocator(new SerializableRunnable() {
+    this.invoker.invokeInEveryVMAndController(new SerializableRunnable() {
       @Override
       public void run() { 
         originalProperties = getProperties();
@@ -59,7 +59,7 @@ public class DistributedRestoreSystemProperties extends RestoreSystemProperties
   @Override
   protected void after() {
     super.after();
-    this.invoker.remoteInvokeInEveryVMAndLocator(new SerializableRunnable() {
+    this.invoker.invokeInEveryVMAndController(new SerializableRunnable() {
       @Override
       public void run() { 
         setProperties(originalProperties);

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java
new file mode 100644
index 0000000..5ab479b
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.junit.Rule;
+
+/**
+ * Annotates a field or method as a type of {@link Rule} that can be invoked
+ * across multiple VMs in a {@code DistributedTest}.
+ *
+ * If there are multiple annotated {@code DistributedRule}s on a class, they
+ * will be applied in order of fields first, then methods. Furthermore, if
+ * there are multiple fields (or methods) they will be applied in an order that
+ * depends on your JVM's implementation of the reflection API, which is
+ * undefined. Rules defined by fields will always be applied before Rules
+ * defined by methods. You can use a {@link org.junit.rules.RuleChain} or
+ * {@link org.apache.geode.test.junit.rules.RuleList} if you want to have
+ * control over the order in which the Rules are applied.
+ *
+ * <p>
+ * For example, here is a test class that makes a unique
+ * {@link org.junit.rules.TemporaryFolder} available to each DUnit VM:
+ * <pre>
+ * {@literal @}Category(DistributedTest.class)
+ * public class EachVMHasItsOwnTemporaryFolder {
+ *
+ *   {@literal @}DistributedRule
+ *   public TemporaryFolder folder = new TemporaryFolder();
+ *
+ *   {@literal @}Rule
+ *   public DistributedTestRule distributedTestRule = DistributedTestRule.builder().build();
+ *
+ *   {@literal @}Test
+ *   public void eachVMHasItsOwnTemporaryFolder() throws Exception {
+ *     Host.getHost(0).getVM(0).invoke(() -> {
+ *       File gemfireProps = folder.newFile({@literal "}gemfire.properties{@literal "});
+ *       File diskDirs = folder.newFolder({@literal "}diskDirs{@literal "});
+ *       ...
+ *     }
+ *   }
+ * }
+ * </pre>
+ *
+ * @see org.apache.geode.test.junit.rules.serializable.SerializableTestRule
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD, ElementType.METHOD})
+public @interface DistributedRule {
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRunRules.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRunRules.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRunRules.java
new file mode 100644
index 0000000..7490acd
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRunRules.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import java.io.Serializable;
+
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.SerializableRunnable;
+
+/**
+ * Runs Rules in specified DUnit VMs.
+ */
+public class DistributedRunRules extends Statement implements Serializable {
+  private final Statement statement;
+  private final WhichVMs whichVMs;
+
+  public DistributedRunRules(final Statement base, final Iterable<TestRule> rules, final Description description, final WhichVMs whichVMs) {
+    this.statement = applyAll(base, rules, description);
+    this.whichVMs = whichVMs;
+  }
+
+  @Override
+  public void evaluate() throws Throwable {
+    if (this.whichVMs.controllerVM()) {
+      this.statement.evaluate();
+    }
+    if (this.whichVMs.everyVM()) {
+      for (int i = 0; i < Host.getHost(0).getVMCount(); i++) {
+        Host.getHost(0).getVM(i).invoke(runnable());
+      }
+    }
+    if (this.whichVMs.locatorVM()) {
+      Host.getHost(0).getLocator().invoke(runnable());
+    }
+  }
+
+  private Statement applyAll(Statement result, final Iterable<TestRule> rules, final Description description) {
+    for (TestRule each : rules) {
+      result = each.apply(result, description);
+    }
+    return result;
+  }
+
+  private SerializableRunnable runnable() {
+    return new SerializableRunnable() {
+      @Override
+      public void run() {
+        try {
+          DistributedRunRules.this.statement.evaluate();
+        } catch (Error | RuntimeException e) {
+          throw e;
+        } catch (Throwable t) {
+          throw new RuntimeException(t);
+        }
+      }
+    };
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java
new file mode 100644
index 0000000..1c78d00
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import java.io.Serializable;
+
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.SerializableRunnable;
+import org.apache.geode.test.junit.rules.serializable.SerializableStatement;
+
+/**
+ * Invokes Statement in specified DUnit VMs.
+ */
+public class DistributedStatement extends SerializableStatement {
+  private final SerializableStatement next;
+  private final WhichVMs whichVMs;
+
+  /**
+   * Construct a new {@code DistributedStatement} statement.
+   * @param next the next {@code Statement} in the execution chain
+   * @param whichVMs specifies which VMs should invoke the statement
+   */
+  public DistributedStatement(final SerializableStatement next, final WhichVMs whichVMs) {
+    this.next = next;
+    this.whichVMs = whichVMs;
+  }
+
+  /**
+   * Invoke the {@link Statement} in the specified VMs.
+   */
+  @Override
+  public void evaluate() throws Throwable {
+    if (this.whichVMs.controllerVM()) {
+      this.next.evaluate();
+    }
+    if (this.whichVMs.everyVM()) {
+      for (int i = 0; i < Host.getHost(0).getVMCount(); i++) {
+        Host.getHost(0).getVM(i).invoke(runnable());
+      }
+    }
+    if (this.whichVMs.locatorVM()) {
+      Host.getHost(0).getLocator().invoke(runnable());
+    }
+  }
+
+  private SerializableRunnable runnable() {
+    return new SerializableRunnable() {
+      @Override
+      public void run() {
+        try {
+          next.evaluate();
+        } catch (Error | RuntimeException e) {
+          throw e;
+        } catch (Throwable t) {
+          throw new RuntimeException(t);
+        }
+      }
+    };
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
new file mode 100644
index 0000000..9516cb3
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
@@ -0,0 +1,192 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.rules.MethodRule;
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.Statement;
+import org.junit.runners.model.TestClass;
+
+import org.apache.geode.test.dunit.standalone.DUnitLauncher;
+
+/**
+ * Launches the DUnit framework for a {@code DistributedTest}.
+ *
+ * <p>Enables use of {@link DistributedRule} annotations on any Rules.
+ *
+ * <pre>
+ * {@literal @}Category(DistributedTest.class)
+ * public class QueryDataDUnitTest {
+ *
+ *   {@literal @}DistributedRule
+ *   public UseJacksonForJsonPathRule useJacksonForJsonPathRule = new UseJacksonForJsonPathRule();
+ *
+ *   {@literal @}Rule
+ *   public DistributedTestRule distributedTestRule = DistributedTestRule.builder().build();
+ *
+ *   ...
+ * }
+ * </pre>
+ * <p>Use the {@code Builder} to specify which {@code VM}s should invoke any
+ * {@code Rule} annotated with {@literal @}DistributedRule. By default,
+ * {@code controllerVM} is {@code true}, {@code everyVM} is {@code true} and
+ * {@code locatorVM} is {@code false}.
+ */
+public class DistributedTestRule implements MethodRule, Serializable {
+
+  public static Builder builder() {
+    return new Builder();
+  }
+
+  private TestClass testClass;
+
+  private final List<?> rules = new ArrayList<>(); // types are TestRule or MethodRule
+
+  private final RemoteInvoker invoker;
+
+  private final WhichVMs whichVMs;
+
+  // TODO: add ability to specify ordering of DistributedRules
+
+  protected DistributedTestRule(final Builder builder) {
+    this(new RemoteInvoker(), builder);
+  }
+
+  protected DistributedTestRule(final RemoteInvoker invoker, final Builder builder) {
+    this.invoker = invoker;
+
+    this.whichVMs = new WhichVMs();
+    if (builder.controllerVM) {
+      this.whichVMs.addControllerVM();
+    }
+    if (builder.everyVM) {
+      this.whichVMs.addEveryVM();
+    }
+    if (builder.locatorVM) {
+      this.whichVMs.addLocatorVM();
+    }
+  }
+
+  @Override
+  public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
+    this.testClass = new TestClass(target.getClass());
+    Statement statement = base;
+    statement = withRules(method, target, statement);
+    statement = withDUnit(method, target, statement);
+    return statement;
+  }
+
+  protected Statement withDUnit(final FrameworkMethod method, final Object target, final Statement statement) {
+    return new Statement() {
+      @Override
+      public void evaluate() throws Throwable {
+        setUpDUnit();
+        try {
+          statement.evaluate();
+        } finally {
+          tearDownDUnit();
+        }
+      }
+    };
+  }
+
+  protected void setUpDUnit() throws Exception {
+    DUnitLauncher.launchIfNeeded();
+    // TODO: customize based on fields
+  }
+
+  protected void tearDownDUnit() throws Exception {
+  }
+
+  protected Statement withRules(final FrameworkMethod method, final Object target, final Statement statement) {
+    List<TestRule> testRules = this.testRules(target);
+    Statement result = statement;
+//    result = withMethodRules(method, testRules, target, result);
+    result = withTestRules(method, testRules, result);
+
+    return result;
+  }
+
+//  protected Statement withMethodRules(final FrameworkMethod method, final List<TestRule> testRules, final Object target, final Statement result) {
+//    Statement statement = result;
+//    for (MethodRule rule : methodRules(target)) {
+//      if (!testRules.contains(rule)) {
+//        statement = new DistributedStatement(rule.apply((result, method, target), this.whichVMs);
+//      }
+//    }
+//    return statement;
+//  }
+
+  protected Statement withTestRules(final FrameworkMethod method, final List<TestRule> testRules, final Statement statement) {
+    Description description = Description.createTestDescription(this.testClass.getJavaClass(), method.getName(), method.getAnnotations());
+    return testRules.isEmpty() ? statement : new DistributedRunRules(statement, testRules, description, this.whichVMs);
+  }
+
+  protected List<MethodRule> methodRules(final Object target) {
+    List<MethodRule> rules = this.testClass.getAnnotatedMethodValues(target, DistributedRule.class, MethodRule.class);
+    rules.addAll(this.testClass.getAnnotatedFieldValues(target, DistributedRule.class, MethodRule.class));
+    return rules;
+  }
+
+  protected List<TestRule> testRules(final Object target) {
+    List<TestRule> result = this.testClass.getAnnotatedMethodValues(target, DistributedRule.class, TestRule.class);
+    result.addAll(this.testClass.getAnnotatedFieldValues(target, DistributedRule.class, TestRule.class));
+    return result;
+  }
+
+  /**
+   * Builds an instance of {@link DistributedTestRule}.
+   *
+   * <p>By default, {@code controllerVM} is {@code true}, {@code everyVM} is
+   * {@code true} and {@code locatorVM} is {@code false}.
+   */
+  public static class Builder {
+
+    private boolean everyVM = true;
+    private boolean locatorVM = false;
+    private boolean controllerVM = true;
+
+    protected Builder() {
+    }
+
+    public Builder everyVM(final boolean everyVM) {
+      this.everyVM = everyVM;
+      return this;
+    }
+
+    public Builder locatorVM(final boolean locatorVM) {
+      this.locatorVM = locatorVM;
+      return this;
+    }
+
+    public Builder controllerVM(final boolean locatorVM) {
+      this.locatorVM = locatorVM;
+      return this;
+    }
+
+    public DistributedTestRule build() {
+      return new DistributedTestRule(this);
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
new file mode 100644
index 0000000..78841fc
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import org.apache.geode.test.junit.rules.UseJacksonForJsonPathRule;
+
+public class DistributedUseJacksonForJsonPathRule extends UseJacksonForJsonPathRule {
+
+  private static UseJacksonForJsonPathRule instance = new UseJacksonForJsonPathRule();
+
+  private final RemoteInvoker invoker;
+
+  public DistributedUseJacksonForJsonPathRule() {
+    this(new RemoteInvoker());
+  }
+
+  public DistributedUseJacksonForJsonPathRule(final RemoteInvoker invoker) {
+    this.invoker = invoker;
+  }
+
+  @Override
+  public void before() {
+    this.invoker.invokeInEveryVMAndController(DistributedUseJacksonForJsonPathRule::invokeBefore);
+  }
+
+  @Override
+  public void after() {
+    this.invoker.invokeInEveryVMAndController(DistributedUseJacksonForJsonPathRule::invokeAfter);
+  }
+
+  private static void invokeBefore() {
+    instance.before();
+  }
+  private static void invokeAfter() {
+    instance.after();
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.java
new file mode 100644
index 0000000..45311e1
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.test.junit.rules.UseJacksonForJsonPathRule;
+import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
+import org.apache.geode.test.junit.rules.serializable.SerializableStatement;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestRule;
+
+public class DistributedWrapperRule implements SerializableTestRule {
+
+  private static SerializableTestRule instance;
+
+  private final RemoteInvoker invoker;
+  private final WhichVMs whichVMs;
+
+  public DistributedWrapperRule(final SerializableTestRule testRule) {
+    this(testRule, new WhichVMs().addControllerVM().addEveryVM());
+  }
+
+  public DistributedWrapperRule(final SerializableTestRule testRule, final WhichVMs whichVMs) {
+    this(new RemoteInvoker(), testRule, whichVMs);
+  }
+
+  public DistributedWrapperRule(final RemoteInvoker invoker, final SerializableTestRule testRule, final WhichVMs whichVMs) {
+    this.invoker = invoker;
+    instance = testRule;
+    this.whichVMs = whichVMs;
+  }
+
+  @Override
+  public Statement apply(Statement base, Description description){
+    return new DistributedStatement((SerializableStatement) base, whichVMs);
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java
index 66378c7..c9f0902 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java
@@ -20,7 +20,8 @@ import static org.apache.geode.test.dunit.Invoke.*;
 
 import java.io.Serializable;
 
-import org.apache.geode.test.dunit.SerializableRunnable;
+import org.apache.geode.test.dunit.Invoke;
+import org.apache.geode.test.dunit.SerializableRunnableIF;
 
 /**
  * Provides remote invocation support to a {@code TestRule}. These methods
@@ -31,18 +32,21 @@ class RemoteInvoker implements Serializable {
 
   private static final long serialVersionUID = -1759722991299584649L;
 
-  public void invokeEverywhere(final SerializableRunnable runnable) {
+  // controller VM
+  // dunit VMs
+  // locator VM
+
+  public void invokeInEveryVMAndController(final SerializableRunnableIF runnable) {
     try {
       runnable.run();
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
-    invokeInEveryVM(runnable);
-    invokeInLocator(runnable);
+    Invoke.invokeInEveryVM(runnable);
   }
 
-  public void remoteInvokeInEveryVMAndLocator(final SerializableRunnable runnable) {
-    invokeInEveryVM(runnable);
+  public void invokeInEveryVMAndLocator(final SerializableRunnableIF runnable) {
+    Invoke.invokeInEveryVM(runnable);
     invokeInLocator(runnable);
   }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java
new file mode 100644
index 0000000..4ee6020
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import java.io.Serializable;
+
+/**
+ * Specifies which DUnit VMs will invoke a Rule.
+ *
+ * TODO: add ability to specify specific VMs
+ *
+ * TODO: add ability to specify order
+ */
+public class WhichVMs implements Serializable{
+  private boolean controllerVM;
+  private boolean everyVM;
+  private boolean locatorVM;
+
+  public WhichVMs() {
+  }
+
+  public WhichVMs addControllerVM() {
+    this.controllerVM = true;
+    return this;
+  }
+  public WhichVMs addEveryVM() {
+    this.everyVM = true;
+    return this;
+  }
+  public WhichVMs addLocatorVM() {
+    this.locatorVM = true;
+    return this;
+  }
+
+  public boolean controllerVM() {
+    return this.controllerVM;
+  }
+  public boolean everyVM() {
+    return this.everyVM;
+  }
+  public boolean locatorVM() {
+    return this.locatorVM;
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.java
new file mode 100644
index 0000000..8352db2
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.dunit.rules.tests;
+
+import java.io.Serializable;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExternalResource;
+
+import org.apache.geode.test.dunit.rules.DistributedRule;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
+import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
+
+public class DistributedTestRuleTest {
+
+  @DistributedRule
+  public SimpleRule simpleRule = new SimpleRule();
+
+  @Rule
+  public DistributedTestRule distributedTestRule = DistributedTestRule.builder().build();
+
+  @Test
+  public void test() throws Exception {
+    System.out.println("KIRK:test");
+  }
+
+  private static class SimpleRule extends SerializableExternalResource {
+    @Override
+    protected void before() throws Throwable {
+      System.out.println("KIRK:before");
+    }
+
+    @Override
+    protected void after() {
+      System.out.println("KIRK:after");
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java b/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java
index 6618d2a..a044409 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java
@@ -23,6 +23,7 @@ import org.apache.geode.distributed.internal.DistributionConfig;
 import org.apache.geode.distributed.internal.InternalLocator;
 import org.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLeave;
 import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.logging.LogService;
 import org.apache.geode.test.dunit.DUnitEnv;
 import org.apache.geode.test.dunit.Host;
@@ -74,7 +75,9 @@ public class DUnitLauncher {
   private static final int DEBUGGING_VM_NUM = -1;
   private static final int LOCATOR_VM_NUM = -2;
 
-  static final long STARTUP_TIMEOUT = 30 * 1000;
+  static final long STARTUP_TIMEOUT = 300 * 1000; // TODO: restore to 30
+  private static final String STARTUP_TIMEOUT_MESSAGE = "VMs did not start up within " + (STARTUP_TIMEOUT/1000) + " seconds";
+
   private static final String SUSPECT_FILENAME = "dunit_suspect.log";
   private static File DUNIT_SUSPECT_FILE;
 
@@ -192,7 +195,7 @@ public class DUnitLauncher {
 
     //wait for the VM to start up
     if(!processManager.waitForVMs(STARTUP_TIMEOUT)) {
-      throw new RuntimeException("VMs did not start up with 30 seconds");
+      throw new RuntimeException("VMs did not start up within 30 seconds");
     }
 
     locatorPort = startLocator(registry);
@@ -207,7 +210,7 @@ public class DUnitLauncher {
 
     //wait for the VMS to start up
     if(!processManager.waitForVMs(STARTUP_TIMEOUT)) {
-      throw new RuntimeException("VMs did not start up with 30 seconds");
+      throw new RuntimeException("VMs did not start up within 30 seconds");
     }
 
     //populate the Host class with our stubs. The tests use this host class

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-junit/build.gradle
----------------------------------------------------------------------
diff --git a/geode-junit/build.gradle b/geode-junit/build.gradle
index 3e4eb22..e7de0e2 100755
--- a/geode-junit/build.gradle
+++ b/geode-junit/build.gradle
@@ -16,6 +16,7 @@
  */
 
 dependencies {
+  compile 'com.jayway.jsonpath:json-path:' + project.'json-path.version'
   testCompile 'commons-lang:commons-lang:' + project.'commons-lang.version'
   compile ('junit:junit:' + project.'junit.version') {
     exclude module: 'hamcrest-core'

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/UseJacksonForJsonPathRule.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/UseJacksonForJsonPathRule.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/UseJacksonForJsonPathRule.java
new file mode 100644
index 0000000..03d5a60
--- /dev/null
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/UseJacksonForJsonPathRule.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.junit.rules;
+
+import java.util.EnumSet;
+import java.util.Set;
+
+import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.Configuration.Defaults;
+import com.jayway.jsonpath.Option;
+import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
+import com.jayway.jsonpath.spi.json.JsonProvider;
+import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
+import com.jayway.jsonpath.spi.mapper.MappingProvider;
+
+import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
+
+/**
+ * JUnit Rule that configures json-path to use the {@code JacksonJsonProvider}
+ *
+ * <p>UseJacksonForJsonPathRule can be used in tests that need to use json-path-assert:
+ * <pre>
+ * {@literal @}ClassRule
+ * public static UseJacksonForJsonPathRule useJacksonForJsonPathRule = new UseJacksonForJsonPathRule();
+ *
+ * {@literal @}Test
+ * public void hasAssertionsUsingJsonPathMatchers() {
+ *   ...
+ *   assertThat(json, isJson());
+ *   assertThat(json, hasJsonPath("$.result"));
+ * }
+ * </pre>
+ */
+@SuppressWarnings({ "serial", "unused" })
+public class UseJacksonForJsonPathRule extends SerializableExternalResource {
+
+  private boolean hadDefaults;
+  private JsonProvider jsonProvider;
+  private MappingProvider mappingProvider;
+  private Set<Option> options;
+
+  /**
+   * Override to set up your specific external resource.
+   */
+  @Override
+  public void before() {
+    saveDefaults();
+    Configuration.setDefaults(new Defaults() {
+
+      private final JsonProvider jsonProvider = new JacksonJsonProvider();
+      private final MappingProvider mappingProvider = new JacksonMappingProvider();
+
+      @Override
+      public JsonProvider jsonProvider() {
+        return jsonProvider;
+      }
+
+      @Override
+      public MappingProvider mappingProvider() {
+        return mappingProvider;
+      }
+
+      @Override
+      public Set<Option> options() {
+        return EnumSet.noneOf(Option.class);
+      }
+
+    });
+  }
+
+  /**
+   * Override to tear down your specific external resource.
+   */
+  @Override
+  public void after() {
+    restoreDefaults();
+  }
+
+  private void saveDefaults() {
+    try {
+      Configuration defaultConfiguration = Configuration.defaultConfiguration();
+      this.jsonProvider = defaultConfiguration.jsonProvider();
+      this.mappingProvider = defaultConfiguration.mappingProvider();
+      this.options = defaultConfiguration.getOptions();
+      this.hadDefaults = true;
+    } catch (NoClassDefFoundError ignore) {
+      this.hadDefaults = false;
+    }
+  }
+
+  private void restoreDefaults() {
+    if (!this.hadDefaults) {
+      return;
+    }
+    Configuration.setDefaults(new Defaults() {
+
+      @Override
+      public JsonProvider jsonProvider() {
+        return jsonProvider;
+      }
+
+      @Override
+      public MappingProvider mappingProvider() {
+        return mappingProvider;
+      }
+
+      @Override
+      public Set<Option> options() {
+        return options;
+      }
+
+    });
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java
index ad974b6..f4db5bd 100755
--- a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java
@@ -16,10 +16,32 @@
  */
 package org.apache.geode.test.junit.rules.serializable;
 
+import java.io.Serializable;
+
 import org.junit.rules.ExternalResource;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
 
 /**
  * Serializable subclass of {@link org.junit.rules.ExternalResource ExternalResource}.
  */
 public abstract class SerializableExternalResource extends ExternalResource implements SerializableTestRule {
+
+  public Statement apply(Statement base, Description description) {
+    return statement(base);
+  }
+
+  private Statement statement(final Statement base) {
+    return new SerializableStatement() {
+      @Override
+      public void evaluate() throws Throwable {
+        before();
+        try {
+          base.evaluate();
+        } finally {
+          after();
+        }
+      }
+    };
+  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java
new file mode 100644
index 0000000..3f07421
--- /dev/null
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.test.junit.rules.serializable;
+
+import java.io.Serializable;
+
+import org.junit.runners.model.Statement;
+
+/**
+ * Serializable subclass of {@link Statement}.
+ */
+public abstract class SerializableStatement extends Statement implements Serializable {
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java
index d5f6508..53c2b58 100644
--- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java
@@ -144,12 +144,12 @@ public class LuceneManagementDUnitTest extends ManagementTestBase {
     }
   }
 
-  private static void verifyMBean() {
+  private void verifyMBean() {
     getMBean();
   }
 
-  private static LuceneServiceMXBean getMBean() {
-    ObjectName objectName = MBeanJMXAdapter.getCacheServiceMBeanName(ds.getDistributedMember(), "LuceneService");
+  private LuceneServiceMXBean getMBean() {
+    ObjectName objectName = MBeanJMXAdapter.getCacheServiceMBeanName(getSystem().getDistributedMember(), "LuceneService");
     assertNotNull(getManagementService().getMBeanInstance(objectName, LuceneServiceMXBean.class));
     return getManagementService().getMBeanInstance(objectName, LuceneServiceMXBean.class);
   }
@@ -177,14 +177,14 @@ public class LuceneManagementDUnitTest extends ManagementTestBase {
     createPartitionRegion(vm, regionName);
   }
 
-  private static void createIndexes(String regionName, int numIndexes) {
-    LuceneService luceneService = LuceneServiceProvider.get(cache);
+  private void createIndexes(String regionName, int numIndexes) {
+    LuceneService luceneService = LuceneServiceProvider.get(getCache());
     for (int i=0; i<numIndexes; i++) {
       luceneService.createIndex(INDEX_NAME+"_"+i, regionName, "field"+i);
     }
   }
 
-  private static void verifyAllMBeanIndexMetrics(String regionName, int numRegionIndexes, int numTotalIndexes) {
+  private void verifyAllMBeanIndexMetrics(String regionName, int numRegionIndexes, int numTotalIndexes) {
     LuceneServiceMXBean mbean = getMBean();
     verifyMBeanIndexMetrics(mbean, regionName, numRegionIndexes, numTotalIndexes);
   }
@@ -206,17 +206,17 @@ public class LuceneManagementDUnitTest extends ManagementTestBase {
     }
   }
 
-  private static void putEntries(String regionName, int numEntries) {
+  private void putEntries(String regionName, int numEntries) {
     for (int i=0; i<numEntries; i++) {
-      Region region = cache.getRegion(regionName);
+      Region region = getCache().getRegion(regionName);
       String key = String.valueOf(i);
       Object value = new TestObject(key);
       region.put(key, value);
     }
   }
 
-  private static void queryEntries(String regionName, String indexName) throws LuceneQueryException {
-    LuceneService service = LuceneServiceProvider.get(cache);
+  private void queryEntries(String regionName, String indexName) throws LuceneQueryException {
+    LuceneService service = LuceneServiceProvider.get(getCache());
     LuceneQuery query = service.createLuceneQueryFactory().create(indexName, regionName, "field0:0", null);
     query.findValues();
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/gradle/dependency-versions.properties
----------------------------------------------------------------------
diff --git a/gradle/dependency-versions.properties b/gradle/dependency-versions.properties
index 0abe690..f249e4e 100644
--- a/gradle/dependency-versions.properties
+++ b/gradle/dependency-versions.properties
@@ -68,7 +68,8 @@ jline.version = 2.12
 jmock.version = 2.8.2
 jna.version = 4.0.0
 jopt-simple.version = 5.0.1
-json-path.version = 1.2.0
+json-path.version = 2.2.0
+json-path-assert.version = 2.2.0
 json4s.version = 3.2.4
 jsr305.version = 3.0.1
 junit.version = 4.12


[3/8] incubator-geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java
index f4b135e..7f93c0d 100644
--- a/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java
@@ -16,866 +16,655 @@
  */
 package org.apache.geode.management;
 
-import static org.apache.geode.cache.query.Utils.createPortfoliosAndPositions;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
+import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;
+import static java.util.concurrent.TimeUnit.*;
+import static org.apache.geode.cache.FixedPartitionAttributes.*;
+import static org.apache.geode.cache.query.Utils.*;
+import static org.apache.geode.management.internal.ManagementConstants.*;
+import static org.apache.geode.management.internal.ManagementStrings.*;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.assertThat;
+
+import java.io.Serializable;
 import java.util.ArrayList;
+import java.util.Calendar;
 import java.util.Date;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeoutException;
+
+import javax.management.ObjectName;
+
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
 
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.CacheException;
-import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.EntryOperation;
 import org.apache.geode.cache.FixedPartitionAttributes;
 import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.PartitionResolver;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
 import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.query.data.Portfolio;
-import org.apache.geode.cache.query.dunit.QueryUsingFunctionContextDUnitTest;
-import org.apache.geode.cache30.CacheSerializableRunnable;
+import org.apache.geode.cache.query.data.Portfolio; // TODO
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.internal.cache.BucketRegion;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.cache.PartitionedRegion;
 import org.apache.geode.internal.cache.PartitionedRegionHelper;
-import org.apache.geode.internal.cache.partitioned.fixed.SingleHopQuarterPartitionResolver;
-import org.apache.geode.management.internal.ManagementConstants;
-import org.apache.geode.management.internal.ManagementStrings;
+import org.apache.geode.internal.cache.partitioned.fixed.SingleHopQuarterPartitionResolver; // TODO
 import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.management.internal.beans.BeanUtilFuncs;
 import org.apache.geode.management.internal.cli.json.TypedJson;
 import org.apache.geode.pdx.PdxInstance;
 import org.apache.geode.pdx.PdxInstanceFactory;
 import org.apache.geode.pdx.internal.PdxInstanceFactoryImpl;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableRunnable;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.DistributedUseJacksonForJsonPathRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
 
 /**
- * 
- * 
+ * Distributed tests for {@link DistributedSystemMXBean#queryData(String, String, int)}.
+ * <p>
+ * <pre>
+ * Test Basic Json Strings for Partitioned Regions
+ * Test Basic Json Strings for Replicated Regions
+ * Test for all Region Types
+ * Test for primitive types
+ * Test for Nested Objects
+ * Test for Enums
+ * Test for collections
+ * Test for huge collection
+ * Test PDX types
+ * Test different projects type e.g. SelectResult, normal bean etc..
+ * Test Colocated Regions
+ * Test for Limit ( both row count and Depth)
+ * ORDER by orders
+ * Test all attributes are covered in an complex type
+ * </pre>
  */
-
-// 1) Test Basic Json Strings for Partitioned Regions
-// Test Basic Json Strings for Replicated Regions
-// Test for all Region Types
-// Test for primitive types
-// Test for Nested Objects
-// Test for Enums
-// Test for collections
-// Test for huge collection
-// Test PDX types
-// Test different projects type e.g. SelectResult, normal bean etc..
-// Test Colocated Regions
-// Test for Limit ( both row count and Depth)
-// ORDER by orders
-// Test all attributes are covered in an complex type
-
 @Category(DistributedTest.class)
-public class QueryDataDUnitTest extends ManagementTestBase {
-
-  private static final long serialVersionUID = 1L;
-
-  private static final int MAX_WAIT = 100 * 1000;
-
-  private static final int cntDest = 30;
-
-  private static final int cnt = 0;
-
-  // PR 5 is co-located with 4
-  static String PartitionedRegionName1 = "TestPartitionedRegion1"; // default
-                                                                   // name
-  static String PartitionedRegionName2 = "TestPartitionedRegion2"; // default
-                                                                   // name
-  static String PartitionedRegionName3 = "TestPartitionedRegion3"; // default
-                                                                   // name
-  static String PartitionedRegionName4 = "TestPartitionedRegion4"; // default
-                                                                   // name
-  static String PartitionedRegionName5 = "TestPartitionedRegion5"; // default
-                                                                   // name
-
-  
-  static String repRegionName = "TestRepRegion"; // default name
-  static String repRegionName2 = "TestRepRegion2"; // default name
-  static String repRegionName3 = "TestRepRegion3"; // default name
-  static String repRegionName4 = "TestRepRegion4"; // default name
-  static String localRegionName = "TestLocalRegion"; // default name
-
-  public static String[] queries = new String[] {
-      "select * from /" + PartitionedRegionName1 + " where ID>=0",
-      "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName2 + " r2 where r1.ID = r2.ID",
-      "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName2
-          + " r2 where r1.ID = r2.ID AND r1.status = r2.status",
-      "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName2 + " r2, /"
-          + PartitionedRegionName3 + " r3 where r1.ID = r2.ID and r2.ID = r3.ID",
-      "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName2 + " r2, /"
-          + PartitionedRegionName3 + " r3  , /" + repRegionName
-          + " r4 where r1.ID = r2.ID and r2.ID = r3.ID and r3.ID = r4.ID",
-      "Select * from /" + PartitionedRegionName4 + " r4 , /" + PartitionedRegionName5 + " r5 where r4.ID = r5.ID" };
-
-  public static String[] nonColocatedQueries = new String[] {
-      "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName4 + " r4 where r1.ID = r4.ID",
-      "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName4 + " r4 , /"
-          + PartitionedRegionName5 + " r5 where r1.ID = r42.ID and r4.ID = r5.ID" };
-
-  public static String[] queriesForRR = new String[] { "<trace> select * from /" + repRegionName + " where ID>=0",
-      "Select * from /" + repRegionName + " r1, /" + repRegionName2 + " r2 where r1.ID = r2.ID",
-      "select * from /" + repRegionName3 + " where ID>=0" };
-  
-  public static String[] queriesForLimit = new String[] { "select * from /" + repRegionName4 };
-
-
-  public QueryDataDUnitTest() {
-    super();
-  }
-
-  @Override
-  protected final void postSetUpManagementTestBase() throws Exception {
-    initManagement(false);
-  }
-
-  private void initCommonRegions(){
-    createRegionsInNodes();
-    fillValuesInRegions();
-  }
+@SuppressWarnings({ "serial", "unused" })
+public class QueryDataDUnitTest implements Serializable {
 
-  /**
-   * This function puts portfolio objects into the created Region (PR or Local)
-   * *
-   */
-  public CacheSerializableRunnable getCacheSerializableRunnableForPRPuts(final String regionName,
-      final Object[] portfolio, final int from, final int to) {
-    SerializableRunnable puts = new CacheSerializableRunnable("Region Puts") {
-      @Override
-      public void run2() throws CacheException {
-        Cache cache = CacheFactory.getAnyInstance();
-        Region region = cache.getRegion(regionName);
-        for (int j = from; j < to; j++)
-          region.put(new Integer(j), portfolio[j]);
-        LogWriterUtils.getLogWriter()
-            .info(
-                "PRQueryDUnitHelper#getCacheSerializableRunnableForPRPuts: Inserted Portfolio data on Region "
-                    + regionName);
-      }
-    };
-    return (CacheSerializableRunnable) puts;
-  }
+  private static final int NUM_OF_BUCKETS = 20;
 
-  /**
-   * This function puts PDX objects into the created Region (REPLICATED) *
-   */
-  public CacheSerializableRunnable getCacheSerializableRunnableForPDXPuts(final String regionName) {
-    SerializableRunnable puts = new CacheSerializableRunnable("Region Puts") {
-      @Override
-      public void run2() throws CacheException {
-        putPdxInstances(regionName);
+  // PARTITIONED_REGION_NAME5 is co-located with PARTITIONED_REGION_NAME4
+  private static final String PARTITIONED_REGION_NAME1 = "PARTITIONED_REGION_NAME1";
+  private static final String PARTITIONED_REGION_NAME2 = "PARTITIONED_REGION_NAME2";
+  private static final String PARTITIONED_REGION_NAME3 = "PARTITIONED_REGION_NAME3";
+  private static final String PARTITIONED_REGION_NAME4 = "PARTITIONED_REGION_NAME4";
+  private static final String PARTITIONED_REGION_NAME5 = "PARTITIONED_REGION_NAME5";
 
-      }
-    };
-    return (CacheSerializableRunnable) puts;
-  }
-  
-  /**
-   * This function puts big collections to created Region (REPLICATED) *
-   */
-  public CacheSerializableRunnable getCacheSerializableRunnableForBigCollPuts(final String regionName) {
-    SerializableRunnable bigPuts = new CacheSerializableRunnable("Big Coll Puts") {
-      @Override
-      public void run2() throws CacheException {
-        putBigInstances(regionName);
+  private static final String REPLICATE_REGION_NAME1 = "REPLICATE_REGION_NAME1";
+  private static final String REPLICATE_REGION_NAME2 = "REPLICATE_REGION_NAME2";
+  private static final String REPLICATE_REGION_NAME3 = "REPLICATE_REGION_NAME3";
+  private static final String REPLICATE_REGION_NAME4 = "REPLICATE_REGION_NAME4";
 
-      }
-    };
-    return (CacheSerializableRunnable) bigPuts;
-  }
+  private static final String LOCAL_REGION_NAME = "LOCAL_REGION_NAME";
 
-  public void fillValuesInRegions() {
-    // Create common Portflios and NewPortfolios
-    final Portfolio[] portfolio = createPortfoliosAndPositions(cntDest);
+  private static final String BIG_COLLECTION_ELEMENT_ = "BIG_COLLECTION_ELEMENT_";
+  private static final String BIG_COLLECTION_ = "BIG_COLLECTION_";
 
-    // Fill local region
-    managedNode1.invoke(getCacheSerializableRunnableForPRPuts(localRegionName, portfolio, cnt, cntDest));
+  private static final String[] QUERIES = new String[] {
+    "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " WHERE ID >= 0",
+    "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " r1, /" + PARTITIONED_REGION_NAME2 + " r2 WHERE r1.ID = r2.ID",
+    "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " r1, /" + PARTITIONED_REGION_NAME2 + " r2 WHERE r1.ID = r2.ID AND r1.status = r2.status",
+    "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " r1, /" + PARTITIONED_REGION_NAME2 + " r2, /" + PARTITIONED_REGION_NAME3 + " r3 WHERE r1.ID = r2.ID AND r2.ID = r3.ID",
+    "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " r1, /" + PARTITIONED_REGION_NAME2 + " r2, /" + PARTITIONED_REGION_NAME3 + " r3, /" + REPLICATE_REGION_NAME1 + " r4 WHERE r1.ID = r2.ID AND r2.ID = r3.ID AND r3.ID = r4.ID",
+    "SELECT * FROM /" + PARTITIONED_REGION_NAME4 + " r4, /" + PARTITIONED_REGION_NAME5 + " r5 WHERE r4.ID = r5.ID"
+  };
 
-    // Fill replicated region
-    managedNode1.invoke(getCacheSerializableRunnableForPRPuts(repRegionName, portfolio, cnt, cntDest));
-    managedNode2.invoke(getCacheSerializableRunnableForPRPuts(repRegionName2, portfolio, cnt, cntDest));
+  private static final String[] QUERIES_FOR_REPLICATED = new String[] {
+    "<TRACE> SELECT * FROM /" + REPLICATE_REGION_NAME1 + " WHERE ID >= 0",
+    "SELECT * FROM /" + REPLICATE_REGION_NAME1 + " r1, /" + REPLICATE_REGION_NAME2 + " r2 WHERE r1.ID = r2.ID",
+    "SELECT * FROM /" + REPLICATE_REGION_NAME3 + " WHERE ID >= 0"
+  };
 
-    // Fill Partition Region
-    managedNode1.invoke(getCacheSerializableRunnableForPRPuts(PartitionedRegionName1, portfolio, cnt, cntDest));
-    managedNode1.invoke(getCacheSerializableRunnableForPRPuts(PartitionedRegionName2, portfolio, cnt, cntDest));
-    managedNode1.invoke(getCacheSerializableRunnableForPRPuts(PartitionedRegionName3, portfolio, cnt, cntDest));
-    managedNode1.invoke(getCacheSerializableRunnableForPRPuts(PartitionedRegionName4, portfolio, cnt, cntDest));
-    managedNode1.invoke(getCacheSerializableRunnableForPRPuts(PartitionedRegionName5, portfolio, cnt, cntDest));
+  private static final String[] QUERIES_FOR_LIMIT = new String[] {
+    "SELECT * FROM /" + REPLICATE_REGION_NAME4
+  };
 
-    managedNode1.invoke(getCacheSerializableRunnableForPDXPuts(repRegionName3));
+  private DistributedMember member1;
+  private DistributedMember member2;
+  private DistributedMember member3;
 
-  }
+  @Manager
+  private VM managerVM;
 
-  public void putPdxInstances(String regionName) throws CacheException {
-    PdxInstanceFactory pf = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
-    Region r = getCache().getRegion(regionName);
-    pf.writeInt("ID", 111);
-    pf.writeString("status", "active");
-    pf.writeString("secId", "IBM");
-    PdxInstance pi = pf.create();
-    r.put("IBM", pi);
-
-    pf = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
-    pf.writeInt("ID", 222);
-    pf.writeString("status", "inactive");
-    pf.writeString("secId", "YHOO");
-    pi = pf.create();
-    r.put("YHOO", pi);
-
-    pf = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
-    pf.writeInt("ID", 333);
-    pf.writeString("status", "active");
-    pf.writeString("secId", "GOOGL");
-    pi = pf.create();
-    r.put("GOOGL", pi);
-
-    pf = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
-    pf.writeInt("ID", 111);
-    pf.writeString("status", "inactive");
-    pf.writeString("secId", "VMW");
-    pi = pf.create();
-    r.put("VMW", pi);
-  }
-  
-  public void putBigInstances(String regionName) throws CacheException {
-    Region r = getCache().getRegion(regionName);
-
-    for(int i = 0 ; i < 1200 ; i++){
-      List<String> bigColl1 = new ArrayList<String>();
-      for(int j = 0; j< 200 ; j++){
-        bigColl1.add("BigColl_1_ElemenNo_"+j);
-      }
-      r.put("BigColl_1_"+i, bigColl1);
-    }
-    
-  }
+  @Member
+  private VM[] memberVMs;
 
-  private void createRegionsInNodes() {
+  @Rule
+  public DistributedUseJacksonForJsonPathRule useJacksonForJsonPathRule = new DistributedUseJacksonForJsonPathRule();
 
-    // Create local Region on servers
-    managedNode1.invoke(() -> QueryUsingFunctionContextDUnitTest.createLocalRegion());
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().managersFirst(false).start(true).build();
 
-    // Create ReplicatedRegion on servers
-    managedNode1.invoke(() -> QueryUsingFunctionContextDUnitTest.createReplicatedRegion());
-    managedNode2.invoke(() -> QueryUsingFunctionContextDUnitTest.createReplicatedRegion());
-    managedNode3.invoke(() -> QueryUsingFunctionContextDUnitTest.createReplicatedRegion());
-    try {
-      this.createDistributedRegion(managedNode2, repRegionName2);
-      this.createDistributedRegion(managedNode1, repRegionName3);
-      this.createDistributedRegion(managedNode1, repRegionName4);
-    } catch (Exception e1) {
-      fail("Test Failed while creating region " + e1.getMessage());
-    }
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
 
-    // Create two colocated PartitionedRegions On Servers.
-    managedNode1.invoke(() -> QueryUsingFunctionContextDUnitTest.createColocatedPR());
-    managedNode2.invoke(() -> QueryUsingFunctionContextDUnitTest.createColocatedPR());
-    managedNode3.invoke(() -> QueryUsingFunctionContextDUnitTest.createColocatedPR());
-
-    this.managingNode.invoke(new SerializableRunnable("Wait for all Region Proxies to get replicated") {
-
-      public void run() {
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-
-        try {
-          MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName1, 3);
-          MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName2, 3);
-          MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName3, 3);
-          MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName4, 3);
-          MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName5, 3);
-          MBeanUtil.getDistributedRegionMbean("/" + repRegionName, 3);
-          MBeanUtil.getDistributedRegionMbean("/" + repRegionName2, 1);
-          MBeanUtil.getDistributedRegionMbean("/" + repRegionName3, 1);
-          MBeanUtil.getDistributedRegionMbean("/" + repRegionName4, 1);
-        } catch (Exception e) {
-          fail("Region proxies not replicated in time");
-        }
-      }
-    });
+  @Before
+  public void before() throws Exception {
+    this.member1 = this.managementTestRule.getDistributedMember(this.memberVMs[0]);
+    this.member2 = this.managementTestRule.getDistributedMember(this.memberVMs[1]);
+    this.member3 = this.managementTestRule.getDistributedMember(this.memberVMs[2]);
 
+    createRegionsInNodes();
+    generateValuesInRegions();
   }
 
-  // disabled for bug 49698, serialization problems introduced by r44615
   @Test
   public void testQueryOnPartitionedRegion() throws Exception {
-
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
-    
-    initCommonRegions();
-    
-    
-    this.managingNode.invoke(new SerializableRunnable("testQueryOnPartitionedRegion") {
-
-      public void run() {
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-
-        assertNotNull(bean);
-
-        try {
-          for (int i = 0; i < queries.length; i++) {
-            String jsonString = null;
-            if (i == 0) {
-              jsonString = bean.queryData(queries[i], null, 10);
-              if (jsonString.contains("result") && !jsonString.contains("No Data Found")) {
-               
-                //getLogWriter().info("testQueryOnPartitionedRegion" + queries[i] + " is = " + jsonString);
-                JSONObject jsonObj = new JSONObject(jsonString);  
-              } else {
-                fail("Query On Cluster should have result");
-              }
-            } else {
-              jsonString = bean.queryData(queries[i], member1.getId(), 10);
-              if (jsonString.contains("member")) {
-                JSONObject jsonObj = new JSONObject(jsonString);
-                //getLogWriter().info("testQueryOnPartitionedRegion" + queries[i] + " is = " + jsonString);
-              } else {
-                fail("Query On Member should have member");
-              }
-            }
-
-            
-
-          }
-        } catch (JSONException e) {
-          e.printStackTrace();
-          fail(e.getMessage());
-        } catch (Exception e) {
-          e.printStackTrace();
-          fail(e.getMessage());
-        }
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean = this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
+
+      String jsonString = distributedSystemMXBean.queryData(QUERIES[0], null, 10);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
+
+      for (int i = 0; i < QUERIES.length; i++) {
+        jsonString = distributedSystemMXBean.queryData(QUERIES[i], member1.getId(), 10);
+        assertThat(jsonString).contains("result");
+        assertThat(jsonString).contains("member");
+        assertThat("QUERIES[" + i + "]", jsonString, isJson(withJsonPath("$..result", anything())));
+
+        // TODO: better assertions
+        // assertThat("QUERIES[" + i + "]", result,
+        //            isJson(withJsonPath("$..member",
+        //                                equalTo(JsonPath.compile(result)))));
+        //                                //equalTo(new JSONObject().put(String.class.getName(), member1.getId())))));
+        //System.out.println(JsonPath.read(jsonString, "$.result.*"));
+        //System.out.println(JsonPath.read(jsonString, "$['result']['member']"));
+
+        verifyJsonIsValid(jsonString);
       }
     });
   }
 
   @Test
   public void testQueryOnReplicatedRegion() throws Exception {
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean = this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
 
-    
-    initCommonRegions();
-    
-    
-    this.managingNode.invoke(new SerializableRunnable("Query Test For REPL1") {
-
-      
-      public void run() {
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-
-        try {
-          for (int i = 0; i < queriesForRR.length; i++) {
-            String jsonString1 = null;
-            if (i == 0) {
-              jsonString1 = bean.queryData(queriesForRR[i], null, 10);
-              if (jsonString1.contains("result") && !jsonString1.contains("No Data Found")) {
-                JSONObject jsonObj = new JSONObject(jsonString1);
-              } else {
-                fail("Query On Cluster should have result");
-              }
-            } else {
-              jsonString1 = bean.queryData(queriesForRR[i], null, 10);
-              if (jsonString1.contains("result")) {
-                JSONObject jsonObj = new JSONObject(jsonString1);
-              } else {
-                LogWriterUtils.getLogWriter().info("Failed Test String" + queriesForRR[i] + " is = " + jsonString1);
-                fail("Join on Replicated did not work.");
-              }
-            }
-          }
-
-        } catch (JSONException e) {
-          fail(e.getMessage());
-        } catch (IOException e) {
-          fail(e.getMessage());
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+      String jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_REPLICATED[0], null, 10);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
+
+      for (int i = 0; i < QUERIES_FOR_REPLICATED.length; i++) {
+        assertThat(jsonString).contains("result");
+        verifyJsonIsValid(jsonString);
       }
     });
   }
-  
-  @Category(FlakyTest.class) // GEODE-1539
+
   @Test
   public void testMemberWise() throws Exception {
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean = this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
 
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    
-    
-    initCommonRegions();
-    
-    
-    this.managingNode.invoke(new SerializableRunnable("testMemberWise") {
-
-      public void run() {
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-
-        try {
-          byte[] bytes = bean.queryDataForCompressedResult(queriesForRR[0], member1.getId() + "," + member2.getId(), 2);
-          String jsonString = BeanUtilFuncs.decompress(bytes);
-          JSONObject jsonObj = new JSONObject(jsonString);
-          //String memberID = (String)jsonObj.get("member");
-          
-          //getLogWriter().info("testMemberWise " + queriesForRR[2] + " is = " + jsonString);
-
-        } catch (JSONException e) {
-          fail(e.getMessage());
-        } catch (IOException e) {
-          fail(e.getMessage());
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
-      }
+      byte[] bytes = distributedSystemMXBean.queryDataForCompressedResult(QUERIES_FOR_REPLICATED[0], member1.getId() + "," + member2.getId(), 2);
+      String jsonString = BeanUtilFuncs.decompress(bytes);
+
+      verifyJsonIsValid(jsonString);
     });
   }
 
-  
- 
   @Test
   public void testLimitForQuery() throws Exception {
-    
-    initCommonRegions();
-    managedNode1.invoke(getCacheSerializableRunnableForBigCollPuts(repRegionName4));
-    
-    managingNode.invoke(new SerializableRunnable("testLimitForQuery") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-
-        try {
-
-          // Query With Default values
-          assertEquals(TypedJson.DEFAULT_COLLECTION_ELEMENT_LIMIT, bean.getQueryCollectionsDepth());
-          assertEquals(ManagementConstants.DEFAULT_QUERY_LIMIT, bean.getQueryResultSetLimit());
-
-          String jsonString1 = bean.queryData(queriesForLimit[0], null, 0);
-          if (jsonString1.contains("result") && !jsonString1.contains("No Data Found")) {
-            JSONObject jsonObj = new JSONObject(jsonString1);
-            assertTrue(jsonString1.contains("BigColl_1_ElemenNo_"));
-            JSONArray arr = jsonObj.getJSONArray("result");
-            assertEquals(ManagementConstants.DEFAULT_QUERY_LIMIT, arr.length());
-            // Get the first element
-
-            JSONArray array1 = (JSONArray) arr.getJSONArray(0);
-            // Get the ObjectValue
-
-            JSONObject collectionObject = (JSONObject) array1.get(1);
-            assertEquals(100, collectionObject.length());
-
-          } else {
-            fail("Query On Cluster should have result");
-          }
-
-          // Query With Ovverride Values
-          
-          int newQueryCollectionDepth = 150;
-          int newQueryResultSetLimit = 500;
-          bean.setQueryCollectionsDepth(newQueryCollectionDepth);
-          bean.setQueryResultSetLimit(newQueryResultSetLimit);
-          
-          assertEquals(newQueryCollectionDepth, bean.getQueryCollectionsDepth());
-          assertEquals(newQueryResultSetLimit, bean.getQueryResultSetLimit());
-
-          jsonString1 = bean.queryData(queriesForLimit[0], null, 0);
-          if (jsonString1.contains("result") && !jsonString1.contains("No Data Found")) {
-            JSONObject jsonObj = new JSONObject(jsonString1);
-            assertTrue(jsonString1.contains("BigColl_1_ElemenNo_"));
-            JSONArray arr = jsonObj.getJSONArray("result");
-            assertEquals(newQueryResultSetLimit, arr.length());
-            // Get the first element
-
-            JSONArray array1 = (JSONArray) arr.getJSONArray(0);
-            // Get the ObjectValue
-
-            JSONObject collectionObject = (JSONObject) array1.get(1);
-            assertEquals(newQueryCollectionDepth, collectionObject.length());
-
-          } else {
-            fail("Query On Cluster should have result");
-          }
-
-        } catch (JSONException e) {
-          fail(e.getMessage());
-        } catch (IOException e) {
-          fail(e.getMessage());
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+    this.memberVMs[0].invoke("putBigInstances", () -> putBigInstances(REPLICATE_REGION_NAME4));
 
-      }
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean = this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
+
+      // Query With Default values
+      assertThat(distributedSystemMXBean.getQueryCollectionsDepth()).isEqualTo(TypedJson.DEFAULT_COLLECTION_ELEMENT_LIMIT);
+      assertThat(distributedSystemMXBean.getQueryResultSetLimit()).isEqualTo(DEFAULT_QUERY_LIMIT);
+
+      String jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_LIMIT[0], null, 0);
+
+      verifyJsonIsValid(jsonString);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
+      assertThat(jsonString).contains(BIG_COLLECTION_ELEMENT_);
+
+      JSONObject jsonObject = new JSONObject(jsonString);
+      JSONArray jsonArray = jsonObject.getJSONArray("result");
+      assertThat(jsonArray.length()).isEqualTo(DEFAULT_QUERY_LIMIT);
+
+      // Get the first element
+      JSONArray jsonArray1 = jsonArray.getJSONArray(0);
+
+      // Get the ObjectValue
+      JSONObject collectionObject = (JSONObject) jsonArray1.get(1);
+      assertThat(collectionObject.length()).isEqualTo(100);
+
+      // Query With Override Values
+      int newQueryCollectionDepth = 150;
+      int newQueryResultSetLimit = 500;
+
+      distributedSystemMXBean.setQueryCollectionsDepth(newQueryCollectionDepth);
+      distributedSystemMXBean.setQueryResultSetLimit(newQueryResultSetLimit);
+
+      assertThat(distributedSystemMXBean.getQueryCollectionsDepth()).isEqualTo(newQueryCollectionDepth);
+      assertThat(distributedSystemMXBean.getQueryResultSetLimit()).isEqualTo(newQueryResultSetLimit);
+
+      jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_LIMIT[0], null, 0);
+
+      verifyJsonIsValid(jsonString);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
+
+      jsonObject = new JSONObject(jsonString);
+      assertThat(jsonString).contains(BIG_COLLECTION_ELEMENT_);
+
+      jsonArray = jsonObject.getJSONArray("result");
+      assertThat(jsonArray.length()).isEqualTo(newQueryResultSetLimit);
+
+      // Get the first element
+      jsonArray1 = jsonArray.getJSONArray(0);
+
+      // Get the ObjectValue
+      collectionObject = (JSONObject) jsonArray1.get(1);
+      assertThat(collectionObject.length()).isEqualTo(newQueryCollectionDepth);
     });
   }
 
   @Test
-  public void testErrors() throws Exception{
-    
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
-    
-    initCommonRegions();
-    
-    this.managingNode.invoke(new SerializableRunnable("Test Error") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-
-        try {
-          Cache cache = getCache();
-          try {
-            String message = bean.queryData("Select * from TestPartitionedRegion1", null, 2); 
-            
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("message", ManagementStrings.QUERY__MSG__INVALID_QUERY.toLocalizedString("Region mentioned in query probably missing /"));
-            String expectedMessage = jsonObject.toString();
-            assertEquals(expectedMessage,message);
-            
-          } catch (Exception e) {
-            fail(e.getLocalizedMessage());
-          }
-          
-          try {
-            String query = "Select * from /PartitionedRegionName9 r1, PartitionedRegionName2 r2 where r1.ID = r2.ID";
-            String message = bean.queryData(query, null, 2);
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("message", ManagementStrings.QUERY__MSG__REGIONS_NOT_FOUND.toLocalizedString("/PartitionedRegionName9"));
-            String expectedMessage = jsonObject.toString();
-            assertEquals(expectedMessage,message);
-          } catch (Exception e) {
-            fail(e.getLocalizedMessage());
-          
-          }
-          
-          final String testTemp = "testTemp";
-          try {
-            RegionFactory rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-            
-            rf.create(testTemp);
-            String query = "Select * from /"+testTemp;
-            
-            String message = bean.queryData(query, member1.getId(), 2);
-            
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("message", ManagementStrings.QUERY__MSG__REGIONS_NOT_FOUND_ON_MEMBERS.toLocalizedString("/"+testTemp));
-            String expectedMessage = jsonObject.toString();
-            assertEquals(expectedMessage,message);
-          } catch (Exception e) {
-            fail(e.getLocalizedMessage());
-          }
-          
-          try {
-            String query = queries[1];            
-            String message = bean.queryData(query,null, 2);
-            
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("message", ManagementStrings.QUERY__MSG__JOIN_OP_EX.toLocalizedString());
-            String expectedMessage = jsonObject.toString();
-            
-            assertEquals(expectedMessage,message);
-          } catch (Exception e) {
-            fail(e.getLocalizedMessage());
-          }
-
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+  public void testErrors() throws Exception {
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean = this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
 
-      }
+      String invalidQuery = "SELECT * FROM " + PARTITIONED_REGION_NAME1;
+      String invalidQueryResult = distributedSystemMXBean.queryData(invalidQuery, null, 2);
+      assertThat(invalidQueryResult, isJson(withJsonPath("$.message", equalTo(QUERY__MSG__INVALID_QUERY.toLocalizedString("Region mentioned in query probably missing /")))));
+
+      String nonexistentRegionName = this.testName.getMethodName() + "_NONEXISTENT_REGION";
+      String regionsNotFoundQuery = "SELECT * FROM /" + nonexistentRegionName + " r1, PARTITIONED_REGION_NAME2 r2 WHERE r1.ID = r2.ID";
+      String regionsNotFoundResult = distributedSystemMXBean.queryData(regionsNotFoundQuery, null, 2);
+      assertThat(regionsNotFoundResult, isJson(withJsonPath("$.message", equalTo(QUERY__MSG__REGIONS_NOT_FOUND.toLocalizedString("/" + nonexistentRegionName)))));
+
+      String regionName = this.testName.getMethodName() + "_REGION";
+      String regionsNotFoundOnMembersQuery = "SELECT * FROM /" + regionName;
+
+      RegionFactory regionFactory = this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE);
+      regionFactory.create(regionName);
+
+      String regionsNotFoundOnMembersResult = distributedSystemMXBean.queryData(regionsNotFoundOnMembersQuery, member1.getId(), 2);
+      assertThat(regionsNotFoundOnMembersResult, isJson(withJsonPath("$.message", equalTo(QUERY__MSG__REGIONS_NOT_FOUND_ON_MEMBERS.toLocalizedString("/" + regionName)))));
+
+      String joinMissingMembersQuery = QUERIES[1];
+      String joinMissingMembersResult = distributedSystemMXBean.queryData(joinMissingMembersQuery, null, 2);
+      assertThat(joinMissingMembersResult, isJson(withJsonPath("$.message", equalTo(QUERY__MSG__JOIN_OP_EX.toLocalizedString()))));
     });
   }
-  
+
   @Test
-  public void testNormalRegions() throws Exception{
-    
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
-    initCommonRegions();
-    
-    this.managingNode.invoke(new SerializableRunnable("Test Error") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-        final String testNormal = "testNormal";
-        final String testTemp = "testTemp";
-        
-        final String testSNormal = "testSNormal"; // to Reverse order of regions while getting Random region in QueryDataFunction
-        final String testATemp = "testATemp";
-        
-        try {
-          Cache cache = getCache();
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.LOCAL_HEAP_LRU);          
-          rf.create(testNormal);
-          rf.create(testSNormal);
-          
-          
-          Region region = cache.getRegion("/"+testNormal);
-          assertTrue(region.getAttributes().getDataPolicy() == DataPolicy.NORMAL);
-          
-          RegionFactory rf1 = cache.createRegionFactory(RegionShortcut.REPLICATE);
-          rf1.create(testTemp);
-          rf1.create(testATemp);
-          String query1 = "Select * from /testTemp r1,/testNormal r2 where r1.ID = r2.ID";
-          String query2 = "Select * from /testSNormal r1,/testATemp r2 where r1.ID = r2.ID";
-          String query3 = "Select * from /testSNormal";
-          
-          try {
-           
-            bean.queryDataForCompressedResult(query1,null, 2);
-            bean.queryDataForCompressedResult(query2,null, 2);
-            bean.queryDataForCompressedResult(query3,null, 2);
-          } catch (Exception e) {
-            e.printStackTrace();
-          }
-
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+  public void testNormalRegions() throws Exception {
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean = this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
 
-      }
+      String normalRegionName1 = this.testName.getMethodName() + "_NORMAL_REGION_1";
+      String tempRegionName1 = this.testName.getMethodName() + "_TEMP_REGION_1";
+
+      String normalRegionName2 = this.testName.getMethodName() + "_NORMAL_REGION_2"; // to Reverse order of regions while getting Random region in QueryDataFunction [?]
+      String tempRegionName2 = this.testName.getMethodName() + "_TEMP_REGION_2";
+
+      Cache cache = this.managementTestRule.getCache();
+
+      RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.LOCAL_HEAP_LRU);
+      regionFactory.create(normalRegionName1);
+      regionFactory.create(normalRegionName2);
+
+      Region region = cache.getRegion("/" + normalRegionName1);
+      assertThat(region.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.NORMAL);
+
+      RegionFactory regionFactory1 = cache.createRegionFactory(RegionShortcut.REPLICATE);
+      regionFactory1.create(tempRegionName1);
+      regionFactory1.create(tempRegionName2);
+
+      String query1 = "SELECT * FROM /" + tempRegionName1 + " r1, /" + normalRegionName1 + " r2 WHERE r1.ID = r2.ID";
+      String query2 = "SELECT * FROM /" + normalRegionName2 + " r1, /" + tempRegionName2 + " r2 WHERE r1.ID = r2.ID";
+      String query3 = "SELECT * FROM /" + normalRegionName2;
+
+      distributedSystemMXBean.queryDataForCompressedResult(query1, null, 2);
+      distributedSystemMXBean.queryDataForCompressedResult(query2, null, 2);
+      distributedSystemMXBean.queryDataForCompressedResult(query3, null, 2);
+
+      // TODO: assert results of queryDataForCompressedResult?
     });
   }
- 
+
   @Test
   public void testRegionsLocalDataSet() throws Exception {
+    String partitionedRegionName = this.testName.getMethodName() + "_PARTITIONED_REGION";
+
+    String[] values1 = new String[] { "val1", "val2", "val3" };
+    String[] values2 = new String[] { "val4", "val5", "val6" };
+
+    this.memberVMs[0].invoke(this.testName.getMethodName() + " Create Region", () -> {
+      PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
+      partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
+
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(1);
+      for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+        partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
+      }
+      partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
 
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
-
-    final String PartitionedRegionName6 = "LocalDataSetTest";
-
-    final String[] valArray1 = new String[] { "val1", "val2", "val3" };
-    final String[] valArray2 = new String[] { "val4", "val5", "val6" };
-    this.managedNode1.invoke(new SerializableRunnable("testRegionsLocalDataSet:Create Region") {
-      public void run() {
-        try {
-    
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
-
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
-          
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(1);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
-          
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(paf.create());
-              
-          Region r = rf.create(PartitionedRegionName6);
-
-          for (int i = 0; i < valArray1.length; i++) {
-            r.put(new Date(2013,1,i+5), valArray1[i]);
-          }
-        } catch (Exception e) {
-          e.printStackTrace();
-          fail(e.getMessage());
-        }
+      RegionFactory regionFactory = this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(partitionAttributesFactory.create());
+      Region region = regionFactory.create(partitionedRegionName);
 
+      for (int i = 0; i < values1.length; i++) {
+        region.put(getDate(2013, 1, i + 5), values1[i]);
       }
     });
 
-    this.managedNode2.invoke(new SerializableRunnable("testRegionsLocalDataSet: Create Region") {
-      public void run() {
-        try {
-
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
-
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
-          
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(2);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
-          
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(paf.create());
-              
-          Region r = rf.create(PartitionedRegionName6);
-          
-          for (int i = 0; i < valArray2.length; i++) {
-            r.put(new Date(2013,5,i+5), valArray2[i]);
-          }
-          
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+    this.memberVMs[1].invoke(this.testName.getMethodName() + " Create Region", () -> {
+      PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
+      partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
 
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(2);
+      for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+        partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
+      }
+      partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+
+      RegionFactory regionFactory = this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(partitionAttributesFactory.create());
+      Region region = regionFactory.create(partitionedRegionName);
+
+      for (int i = 0; i < values2.length; i++) {
+        region.put(getDate(2013, 5, i + 5), values2[i]);
       }
     });
 
-    this.managedNode3.invoke(new SerializableRunnable("testRegionsLocalDataSet: Create Region") {
-      public void run() {
-        try {
-
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
-
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
-          
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(3);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
-          
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(paf.create());
-              
-          Region r = rf.create(PartitionedRegionName6);
-          
-
-          
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+    this.memberVMs[2].invoke(this.testName.getMethodName() + " Create Region", () -> {
+      PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
+      partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
 
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(3);
+      for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+        partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
       }
+      partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+
+      RegionFactory regionFactory = this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(partitionAttributesFactory.create());
+      regionFactory.create(partitionedRegionName);
     });
 
-    final List<String> member1RealData = (List<String>)managedNode1.invoke(() -> QueryDataDUnitTest.getLocalDataSet( PartitionedRegionName6 ));
-   
-    final List<String> member2RealData = (List<String>) managedNode2.invoke(() -> QueryDataDUnitTest.getLocalDataSet( PartitionedRegionName6 ));
-    
-    final List<String> member3RealData = (List<String>) managedNode3.invoke(() -> QueryDataDUnitTest.getLocalDataSet( PartitionedRegionName6 ));
-    
-
-    
-    this.managingNode.invoke(new SerializableRunnable("testRegionsLocalDataSet") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-
-        try {
-          String query = "Select * from /" + PartitionedRegionName6;
-
-          try {
-            final DistributedRegionMXBean regionMBean = MBeanUtil.getDistributedRegionMbean("/"
-                + PartitionedRegionName6, 3);
-
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              public String description() {
-                return "Waiting for all entries to get reflected at managing node";
-              }
-
-              public boolean done() {
-
-                boolean done = (regionMBean.getSystemRegionEntryCount() == (valArray1.length + valArray2.length));
-                return done;
-              }
-
-            }, MAX_WAIT, 1000, true);
-
-            LogWriterUtils.getLogWriter().info("member1RealData  is = " + member1RealData);
-            LogWriterUtils.getLogWriter().info("member2RealData  is = " + member2RealData);
-            LogWriterUtils.getLogWriter().info("member3RealData  is = " + member3RealData);
-            
-            String member1Result = bean.queryData(query, member1.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member1Result " + query + " is = " + member1Result);
-
-
-            String member2Result = bean.queryData(query, member2.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member2Result " + query + " is = " + member2Result);
-            
-            String member3Result = bean.queryData(query, member3.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member3Result " + query + " is = " + member3Result);
-            
-            for (String val : member1RealData) {
-              assertTrue(member1Result.contains(val));
-             }
-            
-            for (String val : member2RealData) {
-              assertTrue(member2Result.contains(val));
-            }
-
-            assertTrue(member3Result.contains("No Data Found"));
-          } catch (Exception e) {
-            fail(e.getMessage());
-          }
-
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+    final List<String> member1RealData = this.memberVMs[0].invoke(() -> getLocalDataSet(partitionedRegionName));
+    final List<String> member2RealData = this.memberVMs[1].invoke(() -> getLocalDataSet(partitionedRegionName));
+    final List<String> member3RealData = this.memberVMs[2].invoke(() -> getLocalDataSet(partitionedRegionName));
+
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean = this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
+      DistributedRegionMXBean distributedRegionMXBean = awaitDistributedRegionMXBean("/" + partitionedRegionName, 3);
+
+      String alias = "Waiting for all entries to get reflected at managing node";
+      int expectedEntryCount = values1.length + values2.length;
+      await(alias).until(() -> assertThat(distributedRegionMXBean.getSystemRegionEntryCount()).isEqualTo(expectedEntryCount));
 
+      String query = "Select * from /" + partitionedRegionName;
+
+      String member1Result = distributedSystemMXBean.queryData(query, member1.getId(), 0);
+      verifyJsonIsValid(member1Result);
+
+      String member2Result = distributedSystemMXBean.queryData(query, member2.getId(), 0);
+      verifyJsonIsValid(member2Result);
+
+      String member3Result = distributedSystemMXBean.queryData(query, member3.getId(), 0);
+      verifyJsonIsValid(member3Result);
+
+      for (String val : member1RealData) {
+        assertThat(member1Result).contains(val);
       }
+
+      for (String val : member2RealData) {
+        assertThat(member2Result).contains(val);
+      }
+
+      assertThat(member3Result).contains("No Data Found");
     });
   }
-  
-  
-  private static List<String> getLocalDataSet(String region){
-    PartitionedRegion parRegion = PartitionedRegionHelper.getPartitionedRegion(region, GemFireCacheImpl.getExisting());
-    Set<BucketRegion> localPrimaryBucketRegions = parRegion.getDataStore().getAllLocalPrimaryBucketRegions();
-    List<String> allPrimaryVals = new ArrayList<String>();
-    for(BucketRegion brRegion : localPrimaryBucketRegions){
-      for(Object obj : brRegion.values()){
-        allPrimaryVals.add((String)obj);
+
+  private Date getDate(final int year, final int month, final int date) {
+    Calendar calendar = Calendar.getInstance();
+    calendar.set(year, month, date);
+    return calendar.getTime();
+  }
+
+  private void verifyJsonIsValid(final String jsonString) throws JSONException {
+    assertThat(jsonString, isJson());
+    assertThat(jsonString, hasJsonPath("$.result"));
+    assertThat(new JSONObject(jsonString)).isNotNull();
+  }
+
+  private void putDataInRegion(final String regionName, final Object[] portfolio, final int from, final int to) {
+    Region region = this.managementTestRule.getCache().getRegion(regionName);
+    for (int i = from; i < to; i++) {
+      region.put(new Integer(i), portfolio[i]);
+    }
+  }
+
+  private void generateValuesInRegions() {
+    int COUNT_DESTINATION = 30;
+    int COUNT_FROM = 0;
+
+    // Create common Portfolios and NewPortfolios
+    final Portfolio[] portfolio = createPortfoliosAndPositions(COUNT_DESTINATION);
+
+    // Fill local region
+    this.memberVMs[0].invoke(() -> putDataInRegion(LOCAL_REGION_NAME, portfolio, COUNT_FROM, COUNT_DESTINATION));
+
+    // Fill replicated region
+    this.memberVMs[0].invoke(() -> putDataInRegion(REPLICATE_REGION_NAME1, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[1].invoke(() -> putDataInRegion(REPLICATE_REGION_NAME2, portfolio, COUNT_FROM, COUNT_DESTINATION));
+
+    // Fill Partition Region
+    this.memberVMs[0].invoke(() -> putDataInRegion(PARTITIONED_REGION_NAME1, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[0].invoke(() -> putDataInRegion(PARTITIONED_REGION_NAME2, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[0].invoke(() -> putDataInRegion(PARTITIONED_REGION_NAME3, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[0].invoke(() -> putDataInRegion(PARTITIONED_REGION_NAME4, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[0].invoke(() -> putDataInRegion(PARTITIONED_REGION_NAME5, portfolio, COUNT_FROM, COUNT_DESTINATION));
+
+    this.memberVMs[0].invoke(() -> putPdxInstances(REPLICATE_REGION_NAME3));
+  }
+
+  private void putPdxInstances(final String regionName) throws CacheException {
+    Region region = this.managementTestRule.getCache().getRegion(regionName);
+
+    PdxInstanceFactory pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
+    pdxInstanceFactory.writeInt("ID", 111);
+    pdxInstanceFactory.writeString("status", "active");
+    pdxInstanceFactory.writeString("secId", "IBM");
+    PdxInstance pdxInstance = pdxInstanceFactory.create();
+    region.put("IBM", pdxInstance);
+
+    pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
+    pdxInstanceFactory.writeInt("ID", 222);
+    pdxInstanceFactory.writeString("status", "inactive");
+    pdxInstanceFactory.writeString("secId", "YHOO");
+    pdxInstance = pdxInstanceFactory.create();
+    region.put("YHOO", pdxInstance);
+
+    pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
+    pdxInstanceFactory.writeInt("ID", 333);
+    pdxInstanceFactory.writeString("status", "active");
+    pdxInstanceFactory.writeString("secId", "GOOGL");
+    pdxInstance = pdxInstanceFactory.create();
+    region.put("GOOGL", pdxInstance);
+
+    pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
+    pdxInstanceFactory.writeInt("ID", 111);
+    pdxInstanceFactory.writeString("status", "inactive");
+    pdxInstanceFactory.writeString("secId", "VMW");
+    pdxInstance = pdxInstanceFactory.create();
+    region.put("VMW", pdxInstance);
+  }
+
+  private void putBigInstances(final String regionName) {
+    Region region = this.managementTestRule.getCache().getRegion(regionName);
+
+    for (int i = 0; i < 1200; i++) {
+      List<String> bigCollection = new ArrayList<>();
+      for (int j = 0; j < 200; j++) {
+        bigCollection.add(BIG_COLLECTION_ELEMENT_ + j);
       }
-      
+      region.put(BIG_COLLECTION_ + i, bigCollection);
     }
-    
-   return allPrimaryVals;
   }
 
-  /**
-   * creates a Fixed Partition List to be used for Fixed Partition Region
-   * 
-   * @param primaryIndex
-   *          index for each fixed partition
-   */
-  private static List<FixedPartitionAttributes> createFixedPartitionList(int primaryIndex) {
-    List<FixedPartitionAttributes> fpaList = new ArrayList<FixedPartitionAttributes>();
+  private void createLocalRegion() {
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.LOCAL).create(LOCAL_REGION_NAME);
+  }
+
+  private void createReplicatedRegion() {
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE).create(REPLICATE_REGION_NAME1);
+  }
+
+  private void createColocatedPR() {
+    PartitionResolver testKeyBasedResolver = new TestPartitionResolver();
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS).setPartitionResolver(testKeyBasedResolver).create()).create(PARTITIONED_REGION_NAME1);
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS).setPartitionResolver(testKeyBasedResolver).setColocatedWith(PARTITIONED_REGION_NAME1).create()).create(PARTITIONED_REGION_NAME2);
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS).setPartitionResolver(testKeyBasedResolver).setColocatedWith(PARTITIONED_REGION_NAME2).create()).create(PARTITIONED_REGION_NAME3);
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS).setPartitionResolver(testKeyBasedResolver).create()).create(PARTITIONED_REGION_NAME4); // not collocated
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION).setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS).setPartitionResolver(testKeyBasedResolver).setColocatedWith(PARTITIONED_REGION_NAME4).create()).create(PARTITIONED_REGION_NAME5); // collocated with 4
+  }
+
+  private void createDistributedRegion(final String regionName) {
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
+  }
+
+  private void createRegionsInNodes() throws InterruptedException, TimeoutException, ExecutionException {
+    // Create local Region on servers
+    this.memberVMs[0].invoke(() -> createLocalRegion());
+
+    // Create ReplicatedRegion on servers
+    this.memberVMs[0].invoke(() -> createReplicatedRegion());
+    this.memberVMs[1].invoke(() -> createReplicatedRegion());
+    this.memberVMs[2].invoke(() -> createReplicatedRegion());
+
+    this.memberVMs[1].invoke(() -> createDistributedRegion(REPLICATE_REGION_NAME2));
+    this.memberVMs[0].invoke(() -> createDistributedRegion(REPLICATE_REGION_NAME3));
+    this.memberVMs[0].invoke(() -> createDistributedRegion(REPLICATE_REGION_NAME4));
+
+    // Create two co-located PartitionedRegions On Servers.
+    this.memberVMs[0].invoke(() -> createColocatedPR());
+    this.memberVMs[1].invoke(() -> createColocatedPR());
+    this.memberVMs[2].invoke(() -> createColocatedPR());
+
+    this.managerVM.invoke("Wait for all Region Proxies to get replicated", () -> {
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME1, 3);
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME2, 3);
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME3, 3);
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME4, 3);
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME5, 3);
+      awaitDistributedRegionMXBean("/" + REPLICATE_REGION_NAME1, 3);
+      awaitDistributedRegionMXBean("/" + REPLICATE_REGION_NAME2, 1);
+      awaitDistributedRegionMXBean("/" + REPLICATE_REGION_NAME3, 1);
+      awaitDistributedRegionMXBean("/" + REPLICATE_REGION_NAME4, 1);
+    });
+  }
+
+  private List<String> getLocalDataSet(final String region) {
+    PartitionedRegion partitionedRegion = PartitionedRegionHelper.getPartitionedRegion(region, this.managementTestRule.getCache());
+    Set<BucketRegion> localPrimaryBucketRegions = partitionedRegion.getDataStore().getAllLocalPrimaryBucketRegions();
+
+    List<String> allPrimaryValues = new ArrayList<>();
+
+    for (BucketRegion bucketRegion : localPrimaryBucketRegions) {
+      for (Object value : bucketRegion.values()) {
+        allPrimaryValues.add((String) value);
+      }
+    }
+
+    return allPrimaryValues;
+  }
+
+  private List<FixedPartitionAttributes> createFixedPartitionList(final int primaryIndex) {
+    List<FixedPartitionAttributes> fixedPartitionAttributesList = new ArrayList<>();
     if (primaryIndex == 1) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", true, 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", 3));
     }
     if (primaryIndex == 2) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", true, 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", 3));
     }
     if (primaryIndex == 3) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", true, 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", true, 3));
+    }
+    return fixedPartitionAttributesList;
+  }
+
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getMemberMBeanName(member);
+    String alias = "awaiting MemberMXBean proxy for " + member;
+
+    await(alias).until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
+  }
+
+  private DistributedSystemMXBean awaitDistributedSystemMXBean() {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+
+    await().until(() -> assertThat(service.getDistributedSystemMXBean()).isNotNull());
+
+    return service.getDistributedSystemMXBean();
+  }
+
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
+
+    return service.getDistributedRegionMXBean(name);
+  }
+
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name, final int memberCount) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name).getMemberCount()).isEqualTo(memberCount));
+
+    return service.getDistributedRegionMXBean(name);
+  }
+
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
+  }
+
+  private ConditionFactory await(final String alias) {
+    return Awaitility.await(alias).atMost(2, MINUTES);
+  }
+
+  private static class TestPartitionResolver implements PartitionResolver {
+
+    @Override
+    public void close() {
+    }
+
+    @Override
+    public Serializable getRoutingObject(EntryOperation opDetails) {
+      return (((Integer)opDetails.getKey()).intValue() % NUM_OF_BUCKETS);
+    }
+
+    @Override
+    public String getName() {
+      return getClass().getName();
     }
-   return fpaList;
   }
 }


[4/8] incubator-geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java
index 9fb9ab0..c02a220 100644
--- a/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java
@@ -16,6 +16,7 @@
  */
 package org.apache.geode.management;
 
+import static com.jayway.awaitility.Awaitility.*;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static org.junit.Assert.*;
 
@@ -23,8 +24,11 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
 import javax.management.Attribute;
 import javax.management.AttributeList;
+import javax.management.JMException;
 import javax.management.MBeanServer;
 import javax.management.Notification;
 import javax.management.NotificationListener;
@@ -38,102 +42,99 @@ import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.Region;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.offheap.OffHeapMemoryStats;
 import org.apache.geode.internal.offheap.OffHeapStorage;
 import org.apache.geode.internal.offheap.OffHeapStoredObject;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.beans.MemberMBean;
 import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
 import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
  * Tests the off-heap additions to the RegionMXBean and MemberMXBean JMX interfaces.
  */
-@SuppressWarnings("serial")
 @Category(DistributedTest.class)
+@SuppressWarnings("serial")
 public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
+
   /**
    * Specified assertion operations.
    */
-  private static enum ASSERT_OP {
+  private enum ASSERT_OP {
     EQUAL,
     GREATER_THAN,
     GREATER_THAN_OR_EQUAL,
     LESS_THAN
   }
-  
+
   /**
    * Name of off-heap test region.
    */
   private static final String OFF_HEAP_REGION_NAME = "offHeapRegion";
-  
+
   /**
    * Path of off-heap test region.
    */
   private static final String OFF_HEAP_REGION_PATH = "/" + OFF_HEAP_REGION_NAME;
-  
+
   /**
    * Expected total off-heap reserved memory (1 megabyte).
    */
   private static final long TOTAL_MEMORY = 1048576;
-  
+
   /**
    * Half of expected memory total.
    */
   private static final int HALF_TOTAL_MEMORY = (int) (TOTAL_MEMORY / 2);
-  
+
   /**
    * An arbitrary array size.
    */
   private static final int ALLOCATION_SIZE = 100000;
-  
+
   /**
    * A non-arbitrary array size.
    */
   private static final int NEW_ALLOCATION_SIZE = 400000;
-  
+
   /**
    * Java object serialization overhead.
    */
   private static final int OBJECT_OVERHEAD = 8;
-  
+
   /**
    * A region entry key.
    */
   private static final String KEY = "key";
-  
+
   /**
    * Another region entry key.
    */
   private static final String KEY2 = "key2";
-  
+
   /**
    * Yet another region entry key.
    */
   private static final String KEY3 = "key3";
-  
+
   /**
    * A region entry value.
    */
-  private static final byte[] VALUE = "Proin lobortis enim vel sem congue ut condimentum leo rhoncus. In turpis lorem, rhoncus nec rutrum vel, sodales vitae lacus. Etiam nunc ligula, scelerisque id egestas vitae, gravida non enim. Donec ac ligula purus. Mauris gravida ligula sit amet mi ornare blandit. Aliquam at velit ac enim varius malesuada ut eu tortor. Quisque diam nisi, fermentum vel accumsan at, commodo et velit.".getBytes();
-  
+  private static final byte[] VALUE = "Proin lobortis enim vel sem congue ut condimentum leo rhoncus. In turpis lorem, rhoncus nec rutrum vel, sodales vitae lacus. Etiam nunc ligula, scelerisque id egestas vitae, gravida non enim. Donec ac ligula purus. Mauris gravida ligula sit amet mi ornare blandit. Aliquam at velit ac enim varius malesuada ut eu tortor. Quisque diam nisi, fermentum vel accumsan at, commodo et velit."
+    .getBytes();
+
   /**
    * The expected size of the region entry value in off-heap memory.
    */
   private static final int OBJECT_SIZE = VALUE.length + OBJECT_OVERHEAD;
-  
+
   /**
    * Listens for off-heap JMX notifications.
    */
   private static final OffHeapNotificationListener notificationListener = new OffHeapNotificationListener();
-  
+
   /**
    * Local MBeanServer.
    */
@@ -141,42 +142,35 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   @Override
   public final void postSetUp() throws Exception {
-    Host.getHost(0).getVM(0).invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        System.setProperty(OffHeapStorage.STAY_CONNECTED_ON_OUTOFOFFHEAPMEMORY_PROPERTY, "true");
-      }
+    Host.getHost(0).getVM(0).invoke(() -> {
+      System.setProperty(OffHeapStorage.STAY_CONNECTED_ON_OUTOFOFFHEAPMEMORY_PROPERTY, "true");
     });
   }
 
   @Override
   public final void preTearDownCacheTestCase() throws Exception {
-    Host.getHost(0).getVM(0).invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        System.clearProperty(OffHeapStorage.STAY_CONNECTED_ON_OUTOFOFFHEAPMEMORY_PROPERTY);
-      }
+    Host.getHost(0).getVM(0).invoke(() -> {
+      System.clearProperty(OffHeapStorage.STAY_CONNECTED_ON_OUTOFOFFHEAPMEMORY_PROPERTY);
     });
   }
-  
+
   /**
    * Tests off-heap additions to the RegionMXBean and MemberMXBean interfaces.
-   * @throws Exception
    */
   @Test
   public void testOffHeapMBeanAttributesAndStats() throws Exception {
-    final VM vm = Host.getHost(0).getVM(0);    
+    final VM vm = Host.getHost(0).getVM(0);
 
     try {
       // Setup off-heap memory for cache
       setSystemPropertiesOnVm(vm, true, getSystemProperties());
-      
+
       // Create our off-heap region
-      assertNotNull(createOffHeapRegionOnVm(vm,OFF_HEAP_REGION_NAME,DataPolicy.REPLICATE));
-      
+      assertNotNull(createOffHeapRegionOnVm(vm, OFF_HEAP_REGION_NAME, DataPolicy.REPLICATE));
+
       // Make sure our off-heap region has off-heap enabled.
       assertOffHeapRegionAttributesOnVm(vm);
-      
+
       // Make sure our starting off heap stats are correct
       assertOffHeapMetricsOnVm(vm, TOTAL_MEMORY, 0, 0, 0);
   
@@ -187,19 +181,19 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
       {
         doPutOnVm(vm, KEY, VALUE, OFF_HEAP_REGION_NAME, false);
         assertOffHeapMetricsOnVm(vm, (TOTAL_MEMORY - OBJECT_SIZE), OBJECT_SIZE, 1, 0);
-    
+
         doPutOnVm(vm, KEY2, VALUE, OFF_HEAP_REGION_NAME, false);
         assertOffHeapMetricsOnVm(vm, (TOTAL_MEMORY - (2 * OBJECT_SIZE)), (2 * OBJECT_SIZE), 2, 0);
-    
+
         doPutOnVm(vm, KEY3, VALUE, OFF_HEAP_REGION_NAME, false);
         assertOffHeapMetricsOnVm(vm, (TOTAL_MEMORY - (3 * OBJECT_SIZE)), (3 * OBJECT_SIZE), 3, 0);
-    
+
         doDestroyOnVm(vm, KEY3, OFF_HEAP_REGION_NAME);
         assertOffHeapMetricsOnVm(vm, (TOTAL_MEMORY - (2 * OBJECT_SIZE)), (2 * OBJECT_SIZE), 2, 0);
-    
+
         doDestroyOnVm(vm, KEY2, OFF_HEAP_REGION_NAME);
         assertOffHeapMetricsOnVm(vm, (TOTAL_MEMORY - OBJECT_SIZE), OBJECT_SIZE, 1, 0);
-    
+
         doDestroyOnVm(vm, KEY, OFF_HEAP_REGION_NAME);
         assertOffHeapMetricsOnVm(vm, TOTAL_MEMORY, 0, 0, 0);
       }
@@ -207,62 +201,61 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
       doCleanupOnVm(vm);
     }
   }
-  
+
   /**
    * Tests the fragmentation statistic for off-heap memory.
-   * @throws Exception
    */
   @Test
   public void testFragmentationStat() throws Exception {
-    final VM vm = Host.getHost(0).getVM(0);    
+    final VM vm = Host.getHost(0).getVM(0);
 
     try {
       // Setup off-heap memory for cache
       setSystemPropertiesOnVm(vm, true, getSystemProperties());
-      
+
       // Create our off-heap region
-      assertNotNull(createOffHeapRegionOnVm(vm,OFF_HEAP_REGION_NAME,DataPolicy.REPLICATE));
-      vm.invoke(new SerializableRunnable() {      
+      assertNotNull(createOffHeapRegionOnVm(vm, OFF_HEAP_REGION_NAME, DataPolicy.REPLICATE));
+      vm.invoke(new SerializableRunnable() {
         @Override
         public void run() {
           Region region = getCache().getRegion(OFF_HEAP_REGION_NAME);
-          assertNotNull(region);    
+          assertNotNull(region);
         }
       });
-      
+
       // Make sure our off-heap region has off-heap enabled.
       assertOffHeapRegionAttributesOnVm(vm);
-      
+
       // Make sure our starting off heap stats are correct
       assertOffHeapMetricsOnVm(vm, TOTAL_MEMORY, 0, 0, 0);
-      
+
       // After allocating large chunk (equal to total memory) 
       // we should still have no fragmentation
       int largeChunk = (int) TOTAL_MEMORY - OffHeapStoredObject.HEADER_SIZE;
       doPutOnVm(vm, KEY, new byte[largeChunk], OFF_HEAP_REGION_NAME, false);
       // No compaction has run, so fragmentation should be zero
-      assertFragmentationStatOnVm(vm,0,ASSERT_OP.EQUAL);
-      
+      assertFragmentationStatOnVm(vm, 0, ASSERT_OP.EQUAL);
+
       // Allocate more memory to trigger compaction
       doPutOnVm(vm, KEY, new byte[ALLOCATION_SIZE], OFF_HEAP_REGION_NAME, true);
       // When total memory is used no fragmentation
-      assertFragmentationStatOnVm(vm,0,ASSERT_OP.EQUAL);
-      
+      assertFragmentationStatOnVm(vm, 0, ASSERT_OP.EQUAL);
+
       // After freeing all memory we should have no fragmentation
       doDestroyOnVm(vm, KEY, OFF_HEAP_REGION_NAME);
-      assertFragmentationStatOnVm(vm,0,ASSERT_OP.EQUAL);
-      
+      assertFragmentationStatOnVm(vm, 0, ASSERT_OP.EQUAL);
+
       // Allocate HALF_TOTAL_MEMORY twice and release one to create one fragment
       int halfChunk = HALF_TOTAL_MEMORY - OffHeapStoredObject.HEADER_SIZE;
       doPutOnVm(vm, KEY + "0", new byte[halfChunk], OFF_HEAP_REGION_NAME, false);
       doPutOnVm(vm, KEY + "1", new byte[halfChunk], OFF_HEAP_REGION_NAME, false);
       doDestroyOnVm(vm, KEY + "0", OFF_HEAP_REGION_NAME);
-      
+
       // Allocate largeChunk to trigger compaction and fragmentation should be zero 
       // as all free memory is available as one fragment
       doPutOnVm(vm, KEY + "1", new byte[largeChunk], OFF_HEAP_REGION_NAME, true);
-      assertFragmentationStatOnVm(vm,0,ASSERT_OP.EQUAL);
-      
+      assertFragmentationStatOnVm(vm, 0, ASSERT_OP.EQUAL);
+
       // Consume the available fragment as below
       // [16][262120][16][262120][16] = [524288] (HALF_TOTAL_MEMORY)
       int smallChunk = OffHeapStoredObject.MIN_CHUNK_SIZE - OffHeapStoredObject.HEADER_SIZE;
@@ -272,7 +265,7 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
       doPutOnVm(vm, KEY + "S2", new byte[smallChunk], OFF_HEAP_REGION_NAME, false);
       doPutOnVm(vm, KEY + "M2", new byte[mediumChunk], OFF_HEAP_REGION_NAME, false);
       doPutOnVm(vm, KEY + "S3", new byte[smallChunk], OFF_HEAP_REGION_NAME, false);
-      
+
       // free small chunks to create gaps
       doDestroyOnVm(vm, KEY + "S1", OFF_HEAP_REGION_NAME);
       doDestroyOnVm(vm, KEY + "S2", OFF_HEAP_REGION_NAME);
@@ -285,53 +278,52 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
        * Setup a fragmentation attribute monitor
        */
       {
-        setupOffHeapMonitorOnVm(vm,"OffHeapFragmentation",0,0);      
+        setupOffHeapMonitorOnVm(vm, "OffHeapFragmentation", 0, 0);
         clearNotificationListenerOnVm(vm);
       }
 
       // Make sure we have some fragmentation
       assertFragmentationStatOnVm(vm, 100, ASSERT_OP.EQUAL);
-      
+
       // Make sure our fragmentation monitor was triggered
       waitForNotificationListenerOnVm(vm, 5000, 500, true);
     } finally {
       doCleanupOnVm(vm);
-    }      
+    }
   }
 
   /**
-   * Tests the compation time statistic for off-heap memory.
-   * @throws Exception
+   * Tests the compaction time statistic for off-heap memory.
    */
   @Test
   public void testCompactionTimeStat() throws Exception {
-    final VM vm = Host.getHost(0).getVM(0);    
+    final VM vm = Host.getHost(0).getVM(0);
 
     try {
       // Setup off-heap memory for cache
       setSystemPropertiesOnVm(vm, true, getSystemProperties());
-      
+
       // Create our off-heap region
-      assertNotNull(createOffHeapRegionOnVm(vm,OFF_HEAP_REGION_NAME,DataPolicy.REPLICATE));
-      
+      assertNotNull(createOffHeapRegionOnVm(vm, OFF_HEAP_REGION_NAME, DataPolicy.REPLICATE));
+
       // Make sure our off-heap region has off-heap enabled.
       assertOffHeapRegionAttributesOnVm(vm);
-      
+
       // Make sure our starting off heap stats are correct
       assertOffHeapMetricsOnVm(vm, TOTAL_MEMORY, 0, 0, 0);
-      
+
       // After allocating large chunck we should still have no compaction time
       doPutOnVm(vm, KEY, new byte[HALF_TOTAL_MEMORY], OFF_HEAP_REGION_NAME, false);
-      assertCompactionTimeStatOnVm(vm,0,ASSERT_OP.EQUAL);
-      
+      assertCompactionTimeStatOnVm(vm, 0, ASSERT_OP.EQUAL);
+
       // After freeing all memory we should have no compaction time
       doDestroyOnVm(vm, KEY, OFF_HEAP_REGION_NAME);
-      assertCompactionTimeStatOnVm(vm,0,ASSERT_OP.EQUAL);
-      
+      assertCompactionTimeStatOnVm(vm, 0, ASSERT_OP.EQUAL);
+
       // Consume all off-heap memory using an allocation size
-      int numAllocations = doConsumeOffHeapMemoryOnVm(vm,ALLOCATION_SIZE);
+      int numAllocations = doConsumeOffHeapMemoryOnVm(vm, ALLOCATION_SIZE);
       assertTrue(numAllocations > 0);
-      
+
       // Randomly free 3 allocations to produce off-heap gaps
       doFreeOffHeapMemoryOnVm(vm, numAllocations, 3);
 
@@ -339,13 +331,13 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
        * Setup a compaction time attribute monitor
        */
       {
-        setupOffHeapMonitorOnVm(vm,"OffHeapCompactionTime",0,0);      
+        setupOffHeapMonitorOnVm(vm, "OffHeapCompactionTime", 0, 0);
         clearNotificationListenerOnVm(vm);
       }
-      
+
       // Allocate enough memory to force compaction which will update compaction time stat
-      doPutOnVm(vm,KEY, new byte[NEW_ALLOCATION_SIZE], OFF_HEAP_REGION_NAME, true);
-      
+      doPutOnVm(vm, KEY, new byte[NEW_ALLOCATION_SIZE], OFF_HEAP_REGION_NAME, true);
+
       // Make sure our compaction time monitor was triggered
       waitForNotificationListenerOnVm(vm, 5000, 500, true);
 
@@ -353,29 +345,29 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
        * Make sure we have some compaction time.  In some environments the 
        * compaction time is reported as 0 due to time sample granularity and compaction speed. 
        */
-      assertCompactionTimeStatOnVm(vm, 0, ASSERT_OP.GREATER_THAN_OR_EQUAL);      
+      assertCompactionTimeStatOnVm(vm, 0, ASSERT_OP.GREATER_THAN_OR_EQUAL);
     } finally {
       doCleanupOnVm(vm);
-    }      
+    }
   }
 
   /**
-   *  Asserts that a monitor assigned to the OffHeapObjects attribute is triggered.
+   * Asserts that a monitor assigned to the OffHeapObjects attribute is triggered.
    */
   @Test
-  public void testOffHeapObjectsMonitoring()  throws Exception {
-    final VM vm = Host.getHost(0).getVM(0);    
+  public void testOffHeapObjectsMonitoring() throws Exception {
+    final VM vm = Host.getHost(0).getVM(0);
 
     try {
       // Setup off-heap memory for cache
       setSystemPropertiesOnVm(vm, true, getSystemProperties());
-      
+
       // Create our off-heap region
-      assertNotNull(createOffHeapRegionOnVm(vm,OFF_HEAP_REGION_NAME,DataPolicy.REPLICATE));
-      
+      assertNotNull(createOffHeapRegionOnVm(vm, OFF_HEAP_REGION_NAME, DataPolicy.REPLICATE));
+
       // Make sure our off-heap region has off-heap enabled.
       assertOffHeapRegionAttributesOnVm(vm);
-      
+
       // Make sure our starting off heap stats are correct
       assertOffHeapMetricsOnVm(vm, TOTAL_MEMORY, 0, 0, 0);                
 
@@ -383,37 +375,37 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
        * Tests off-heap objects notification
        */
       {
-        setupOffHeapMonitorOnVm(vm,"OffHeapObjects",0,-1);
-        
+        setupOffHeapMonitorOnVm(vm, "OffHeapObjects", 0, -1);
+
         clearNotificationListenerOnVm(vm);
-        
+
         doPutOnVm(vm, KEY, VALUE, OFF_HEAP_REGION_NAME, false);
-        
+
         waitForNotificationListenerOnVm(vm, 5000, 500, true);
       }
-      
+
     } finally {
       doCleanupOnVm(vm);
-    }      
+    }
   }
-  
+
   /**
    * Asserts that a monitor assigned to the OffHeapFreeSize attribute is triggered.
    */
   @Test
-  public void testOffHeapFreeSizeMonitoring()  throws Exception {
-    final VM vm = Host.getHost(0).getVM(0);    
+  public void testOffHeapFreeSizeMonitoring() throws Exception {
+    final VM vm = Host.getHost(0).getVM(0);
 
     try {
       // Setup off-heap memory for cache
       setSystemPropertiesOnVm(vm, true, getSystemProperties());
-      
+
       // Create our off-heap region
-      assertNotNull(createOffHeapRegionOnVm(vm,OFF_HEAP_REGION_NAME,DataPolicy.REPLICATE));
-      
+      assertNotNull(createOffHeapRegionOnVm(vm, OFF_HEAP_REGION_NAME, DataPolicy.REPLICATE));
+
       // Make sure our off-heap region has off-heap enabled.
       assertOffHeapRegionAttributesOnVm(vm);
-      
+
       // Make sure our starting off heap stats are correct
       assertOffHeapMetricsOnVm(vm, TOTAL_MEMORY, 0, 0, 0);                
 
@@ -421,37 +413,37 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
        * Tests off-heap objects notification
        */
       {
-        setupOffHeapMonitorOnVm(vm,"OffHeapFreeSize",TOTAL_MEMORY,TOTAL_MEMORY);
-        
+        setupOffHeapMonitorOnVm(vm, "OffHeapFreeSize", TOTAL_MEMORY, TOTAL_MEMORY);
+
         clearNotificationListenerOnVm(vm);
-        
+
         doPutOnVm(vm, KEY, VALUE, OFF_HEAP_REGION_NAME, false);
-        
+
         waitForNotificationListenerOnVm(vm, 5000, 500, true);
       }
-      
+
     } finally {
       doCleanupOnVm(vm);
-    }      
+    }
   }
 
   /**
    * Asserts that a monitor assigned to the OffHeapAllocatedSize attribute is triggered.
    */
   @Test
-  public void testOffHeapAllocatedSizeMonitoring()  throws Exception {
-    final VM vm = Host.getHost(0).getVM(0);    
+  public void testOffHeapAllocatedSizeMonitoring() throws Exception {
+    final VM vm = Host.getHost(0).getVM(0);
 
     try {
       // Setup off-heap memory for cache
       setSystemPropertiesOnVm(vm, true, getSystemProperties());
-      
+
       // Create our off-heap region
-      assertNotNull(createOffHeapRegionOnVm(vm,OFF_HEAP_REGION_NAME,DataPolicy.REPLICATE));
-      
+      assertNotNull(createOffHeapRegionOnVm(vm, OFF_HEAP_REGION_NAME, DataPolicy.REPLICATE));
+
       // Make sure our off-heap region has off-heap enabled.
       assertOffHeapRegionAttributesOnVm(vm);
-      
+
       // Make sure our starting off heap stats are correct
       assertOffHeapMetricsOnVm(vm, TOTAL_MEMORY, 0, 0, 0);                
 
@@ -459,188 +451,182 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
        * Tests off-heap objects notification
        */
       {
-        setupOffHeapMonitorOnVm(vm,"OffHeapAllocatedSize",0,OBJECT_SIZE);
-        
+        setupOffHeapMonitorOnVm(vm, "OffHeapAllocatedSize", 0, OBJECT_SIZE);
+
         clearNotificationListenerOnVm(vm);
-        
+
         doPutOnVm(vm, KEY, VALUE, OFF_HEAP_REGION_NAME, false);
-        
+
         waitForNotificationListenerOnVm(vm, 5000, 500, true);
       }
-      
+
     } finally {
       doCleanupOnVm(vm);
-    }      
+    }
   }
 
   /**
    * Destroys a number of entries previously allocated.
+   *
    * @param vm a virtual machine
    * @param numAllocations the number of previous off-heap allocations
    * @param numDestroys the number of destroys to perform
    */
-  protected void doFreeOffHeapMemoryOnVm(VM vm,final int numAllocations,final int numDestroys) {
-    vm.invoke(new SerializableRunnable() {      
+  private void doFreeOffHeapMemoryOnVm(final VM vm, final int numAllocations, final int numDestroys) {
+    vm.invoke(new SerializableRunnable() {
       @Override
       public void run() {
-        doFreeOffHeapMemory(numAllocations,numDestroys);
+        doFreeOffHeapMemory(numAllocations, numDestroys);
       }
     });
   }
-  
+
   /**
    * Performs some destroys to free off-heap allocations.
+   *
    * @param numAllocations the number of previous off-heap allocations
    * @param numDestroys the number of destroys to perform
    */
-  protected void doFreeOffHeapMemory(int numAllocations,int numDestroys) {
+  private void doFreeOffHeapMemory(final int numAllocations, final int numDestroys) {
     assertTrue(numDestroys <= numAllocations);
-    
+
     Region region = getCache().getRegion(OFF_HEAP_REGION_NAME);
-    assertNotNull(region);    
-    assertTrue(numDestroys <= region.size());    
-    
+    assertNotNull(region);
+    assertTrue(numDestroys <= region.size());
+
     String key = "KEY0";
     Object value = key;
     int destroyed = 0;
 
-    while(destroyed < numDestroys) {
+    while (destroyed < numDestroys) {
       key = "KEY" + ((int) (Math.random() * numAllocations));
       value = region.get(key);
-      
-      if(null != value) {
+
+      if (null != value) {
         region.destroy(key);
         ++destroyed;
       }
     }
   }
-  
+
   /**
    * Consumes off off-heap memory until the allocation size cannot be satisfied.
+   *
    * @param vm a virtual machine
    * @param allocationSize the number of bytes for each allocation
+   *
    * @return the number of successful puts
    */
-  protected int doConsumeOffHeapMemoryOnVm(VM vm,final int allocationSize) {
-    return (Integer) vm.invoke(new SerializableCallable() {
-      @Override
-      public Object call() {
-        return doConsumeOffHeapMemory(allocationSize);
-      }      
-    });
+  private int doConsumeOffHeapMemoryOnVm(final VM vm, final int allocationSize) {
+    return vm.invoke(() -> doConsumeOffHeapMemory(allocationSize));
   }
-  
+
   /**
    * Consumes off off-heap memory until the allocation size cannot be satisfied.
+   *
    * @param allocationSize the number of bytes for each allocation
+   *
    * @return the number of successful puts
    */
-  protected int doConsumeOffHeapMemory(int allocationSize) { // TODO:KIRK: change this to handle new OutOfOffHeapMemoryException
-    OffHeapMemoryStats stats = ((GemFireCacheImpl) getCache()).getOffHeapStore().getStats();
+  private int doConsumeOffHeapMemory(final int allocationSize) {
     int i = 0;
 
     // Loop until we fail
     try {
-      while(true) {
-        doPut("KEY" + (i++),new byte[allocationSize],OFF_HEAP_REGION_NAME, false);      
+      while (true) { // TODO: put a time limit on this just in case
+        doPut("KEY" + (i++), new byte[allocationSize], OFF_HEAP_REGION_NAME, false);
       }
     } catch (OutOfOffHeapMemoryException e) {
     }
-    
+
     return i;
   }
-    
+
   /**
    * Asserts that the compactionTime stat is available and satisfies an assert operation.
+   *
    * @param vm a virtual machine.
    * @param compactionTime total off heap compaction time.
    * @param op an assert operation.
    */
-  protected void assertCompactionTimeStatOnVm(VM vm,final long compactionTime,final ASSERT_OP op) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertCompactionTimeStat(compactionTime, op);
-      }      
-    });
-  }  
-  
+  private void assertCompactionTimeStatOnVm(final VM vm, final long compactionTime, final ASSERT_OP op) {
+    vm.invoke(() -> assertCompactionTimeStat(compactionTime, op));
+  }
+
   /**
    * Asserts that the compactionTime stat is available and satisfies an assert operation.
+   *
    * @param compactionTime total off heap compaction time.
    * @param op an assert operation.
    */
-  protected void assertCompactionTimeStat(long compactionTime,ASSERT_OP op) {
-    ManagementService service = ManagementService.getExistingManagementService(getCache());    
+  private void assertCompactionTimeStat(final long compactionTime, final ASSERT_OP op) {
+    ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
-    
+
     assertTrue(service.isManager());
 
-    MemberMXBean memberBean = service.getMemberMXBean();   
+    MemberMXBean memberBean = service.getMemberMXBean();
     assertNotNull(memberBean);
-    
-    switch(op) {
-    case EQUAL:
-      assertEquals(compactionTime,memberBean.getOffHeapCompactionTime());
-      break;
-    case GREATER_THAN:
-      assertTrue(compactionTime < memberBean.getOffHeapCompactionTime());
-      break;
-    case GREATER_THAN_OR_EQUAL:
-      assertTrue(compactionTime <= memberBean.getOffHeapCompactionTime());
-      break;
-    case LESS_THAN:
-      assertTrue(compactionTime > memberBean.getOffHeapCompactionTime());
-      break;
+
+    switch (op) {
+      case EQUAL:
+        assertEquals(compactionTime, memberBean.getOffHeapCompactionTime());
+        break;
+      case GREATER_THAN:
+        assertTrue(compactionTime < memberBean.getOffHeapCompactionTime());
+        break;
+      case GREATER_THAN_OR_EQUAL:
+        assertTrue(compactionTime <= memberBean.getOffHeapCompactionTime());
+        break;
+      case LESS_THAN:
+        assertTrue(compactionTime > memberBean.getOffHeapCompactionTime());
+        break;
     }
   }
-  
+
   /**
    * Asserts that the fragmentation stat is available and satisfies an assert operation.
+   *
    * @param vm a virtual machine
    * @param fragmentation a fragmentation percentage
    * @param op an assertion operation
    */
-  protected void assertFragmentationStatOnVm(VM vm,final int fragmentation, final ASSERT_OP op) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertFragmentationStat(fragmentation,op);
-      }      
-    });
+  private void assertFragmentationStatOnVm(final VM vm, final int fragmentation, final ASSERT_OP op) {
+    vm.invoke(() -> assertFragmentationStat(fragmentation, op));
   }
-  
+
   /**
    * Asserts that the fragmentation stat is available and satisfies an assert operation.
+   *
    * @param fragmentation a fragmentation percentage
    * @param op an assertion operation
    */
-  protected void assertFragmentationStat(int fragmentation,ASSERT_OP op) {
-    ManagementService service = ManagementService.getExistingManagementService(getCache());    
+  private void assertFragmentationStat(final int fragmentation, final ASSERT_OP op) {
+    ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
-    
+
     assertTrue(service.isManager());
 
-    MemberMXBean memberBean = service.getMemberMXBean();   
+    MemberMXBean memberBean = service.getMemberMXBean();
     assertNotNull(memberBean);
-    
-    switch(op) {
-    case EQUAL:
-      assertEquals(fragmentation,memberBean.getOffHeapFragmentation());
-      break;
-    case GREATER_THAN:
-      assertTrue(fragmentation < memberBean.getOffHeapFragmentation());
-      break;
-    case LESS_THAN:
-      assertTrue(fragmentation > memberBean.getOffHeapFragmentation());
-      break;
+
+    switch (op) {
+      case EQUAL:
+        assertEquals(fragmentation, memberBean.getOffHeapFragmentation());
+        break;
+      case GREATER_THAN:
+        assertTrue(fragmentation < memberBean.getOffHeapFragmentation());
+        break;
+      case LESS_THAN:
+        assertTrue(fragmentation > memberBean.getOffHeapFragmentation());
+        break;
     }
   }
-  
+
   /**
    * Returns off-heap system properties for enabling off-heap and the JMX system.
    */
-  protected Properties getSystemProperties() {
+  private Properties getSystemProperties() {
     Properties props = getDistributedSystemProperties();
 
     props.setProperty(OFF_HEAP_MEMORY_SIZE, "1m");
@@ -653,15 +639,11 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Removes off heap region on vm and disconnects.
-   * @param vm a virutal machine.
+   *
+   * @param vm a virtual machine.
    */
-  protected void doCleanupOnVm(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        cleanup();
-      }      
-    });
+  private void doCleanupOnVm(final VM vm) {
+    vm.invoke(() -> cleanup());
   }
 
   /**
@@ -670,339 +652,310 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
   protected void cleanup() {
     Cache existingCache = basicGetCache();
 
-    if(null != existingCache && !existingCache.isClosed()) {
+    if (null != existingCache && !existingCache.isClosed()) {
       Region region = getCache().getRegion(OFF_HEAP_REGION_NAME);
 
       if (null != region) {
         region.destroyRegion();
       }
     }
-    
+
     disconnectFromDS();
   }
-  
+
   /**
    * Asserts that the off heap region data is available and enabled for a VM.
    */
-  @SuppressWarnings("serial")
-  protected void assertOffHeapRegionAttributesOnVm(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertOffHeapRegionAttributes();
-      }      
-    });
+  private void assertOffHeapRegionAttributesOnVm(final VM vm) {
+    vm.invoke(() -> assertOffHeapRegionAttributes());
   }
-  
+
   /**
    * Asserts that the off heap region data is available and enabled.
    */
-  protected void assertOffHeapRegionAttributes() {
-    ManagementService service = ManagementService.getExistingManagementService(getCache());    
+  private void assertOffHeapRegionAttributes() {
+    ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
-    
+
     assertTrue(service.isManager());
-    
+
     RegionMXBean regionBean = service.getLocalRegionMBean(OFF_HEAP_REGION_PATH);
     assertNotNull(regionBean);
-    
+
     RegionAttributesData regionData = regionBean.listRegionAttributes();
     assertNotNull(regionData);
-    
+
     assertTrue(regionData.getOffHeap());
   }
-  
+
   /**
    * Asserts that OffHeapMetrics match input parameters for a VM.
+   *
    * @param vm a virtual machine.
    * @param freeMemory total off-heap free memory in bytes.
    * @param allocatedMemory allocated (or used) off-heap memory in bytes.
    * @param objects number of objects stored in off-heap memory.
    * @param fragmentation the fragmentation percentage.
    */
-  protected void assertOffHeapMetricsOnVm(VM vm,final long freeMemory,final long allocatedMemory,final long objects,final int fragmentation) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertOffHeapMetrics(freeMemory, allocatedMemory, objects, fragmentation);
-      }      
-    });
+  private void assertOffHeapMetricsOnVm(final VM vm,
+                                        final long freeMemory,
+                                        final long allocatedMemory,
+                                        final long objects,
+                                        final int fragmentation) {
+    vm.invoke(() -> assertOffHeapMetrics(freeMemory, allocatedMemory, objects, fragmentation));
   }
-  
+
   /**
    * Asserts that OffHeapMetrics match input parameters.
+   *
    * @param freeMemory total off-heap free memory in bytes.
    * @param allocatedMemory allocated (or used) off-heap memory in bytes.
    * @param objects number of objects stored in off-heap memory.
    * @param fragmentation the fragmentation percentage.
    */
-  protected void assertOffHeapMetrics(long freeMemory,long allocatedMemory,long objects, int fragmentation) {
-    ManagementService service = ManagementService.getExistingManagementService(getCache());    
+  private void assertOffHeapMetrics(final long freeMemory, final long allocatedMemory, final long objects, final int fragmentation) {
+    ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
-    
+
     assertTrue(service.isManager());
 
-    MemberMXBean memberBean = service.getMemberMXBean();   
+    MemberMXBean memberBean = service.getMemberMXBean();
     assertNotNull(memberBean);
-    
-    assertEquals(freeMemory,memberBean.getOffHeapFreeMemory());
-    assertEquals(allocatedMemory,memberBean.getOffHeapUsedMemory());
-    assertEquals(objects,memberBean.getOffHeapObjects());
-    assertEquals(fragmentation,memberBean.getOffHeapFragmentation());
+
+    assertEquals(freeMemory, memberBean.getOffHeapFreeMemory());
+    assertEquals(allocatedMemory, memberBean.getOffHeapUsedMemory());
+    assertEquals(objects, memberBean.getOffHeapObjects());
+    assertEquals(fragmentation, memberBean.getOffHeapFragmentation());
   }
-  
+
   /**
    * Creates an off-heap region on a vm.
+   *
    * @param vm a virtual machine.
    * @param name a region name.
    * @param dataPolicy a data policy.
+   *
    * @return true if successful.
    */
-  protected boolean createOffHeapRegionOnVm(final VM vm,final String name,final DataPolicy dataPolicy) {
-    return (Boolean) vm.invoke(new SerializableCallable() {
-      @Override
-      public Object call() throws Exception {
-        return (null != createOffHeapRegion(name, dataPolicy));
-      }      
-    });
+  private boolean createOffHeapRegionOnVm(final VM vm, final String name, final DataPolicy dataPolicy) {
+    return vm.invoke(() -> null != createOffHeapRegion(name, dataPolicy));
   }
-  
+
   /**
    * Creates an off-heap region.
+   *
    * @param name a region name.
    * @param dataPolicy a data policy.
+   *
    * @return the newly created region.
    */
-  protected Region createOffHeapRegion(String name,DataPolicy dataPolicy) {
+  private Region createOffHeapRegion(final String name, final DataPolicy dataPolicy) {
     return getCache().createRegionFactory().setOffHeap(true).setDataPolicy(dataPolicy).create(name);
   }
 
   /**
    * Sets the distributed system properties for a vm.
+   *
    * @param vm a virtual machine.
    * @param management starts the ManagementService when true.
    * @param props distributed system properties.
    */
-  @SuppressWarnings("serial")
-  protected void setSystemPropertiesOnVm(VM vm,final boolean management,final Properties props) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        setSystemProperties(management,props);
-      }      
-    });
+  private void setSystemPropertiesOnVm(final VM vm, final boolean management, final Properties props) {
+    vm.invoke(() -> setSystemProperties(management, props));
   }
 
   /**
    * Sets the distributed system properties.
+   *
    * @param management starts the ManagementService when true.
    * @param props distributed system properties.
    */
-  protected void setSystemProperties(boolean management,Properties props) {
+  private void setSystemProperties(final boolean management, final Properties props) {
     getSystem(props);
-    
-    if(management) {
+
+    if (management) {
       ManagementService service = ManagementService.getManagementService(getCache());
-      if(!service.isManager()) {
+      if (!service.isManager()) {
         service.startManager();
       }
     }
   }
-  
+
   /**
    * Performs a destroy operation on a vm.
+   *
    * @param vm a virtual machine.
    * @param key the region entry to destroy.
    * @param regionName a region name.
    */
-  protected void doDestroyOnVm(final VM vm,final Object key,final String regionName) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        doDestroy(key,regionName);
-      }      
-    });
+  private void doDestroyOnVm(final VM vm, final Object key, final String regionName) {
+    vm.invoke(() -> doDestroy(key, regionName));
   }
-  
+
   /**
    * Performs a destroy operation.
+   *
    * @param key the region entry to destroy.
    * @param regionName a region name.
    */
-  protected void doDestroy(Object key, String regionName) {
-    Region region =  getCache().getRegion(regionName);
+  private void doDestroy(final Object key, final String regionName) {
+    Region region = getCache().getRegion(regionName);
     assertNotNull(region);
-    
+
     region.destroy(key);
   }
-  
+
   /**
    * Performs a put operation on a vm.
+   *
    * @param vm a virtual machine.
    * @param key region entry key.
    * @param value region entry value.
    * @param regionName a region name.
    */
-  protected void doPutOnVm(final VM vm,final Object key,final Object value,final String regionName, final boolean expectException) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        doPut(key,value,regionName,expectException);
-      }      
-    });
+  private void doPutOnVm(final VM vm,
+                         final Object key,
+                         final Object value,
+                         final String regionName,
+                         final boolean expectException) {
+    vm.invoke(() -> doPut(key, value, regionName, expectException));
   }
-  
+
   /**
    * Performs a put operation.
+   *
    * @param key region entry key.
    * @param value region entry value.
    * @param regionName a region name.
    */
-  protected void doPut(Object key, Object value, String regionName,boolean expectException) {
-    Region region =  getCache().getRegion(regionName);
+  private void doPut(final Object key, final Object value, final String regionName, final boolean expectException) {
+    Region region = getCache().getRegion(regionName);
     assertNotNull(region);
-    
+
     try {
       region.put(key, value);
+      if (expectException) {
+        fail("Expected OutOfOffHeapMemoryException");
+      }
     } catch (OutOfOffHeapMemoryException e) {
-      if(!expectException)
+      if (!expectException) {
         throw e;
+      }
     }
   }
 
   /**
    * Adds an off-heap notification listener to the MemberMXBean for a vm.
+   *
    * @param vm a virtual machine.
    */
-  protected void addOffHeapNotificationListenerOnVm(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        addOffHeapNotificationListener();
-      }      
-    });
+  private void addOffHeapNotificationListenerOnVm(final VM vm) {
+    vm.invoke(() -> addOffHeapNotificationListener());
   }
-  
+
   /**
    * Adds an off-heap notification listener to the MemberMXBean.
    */
-  protected void addOffHeapNotificationListener() {
-    ManagementService service = ManagementService.getExistingManagementService(getCache());    
+  private void addOffHeapNotificationListener() {
+    ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
-    
+
     assertTrue(service.isManager());
 
-    MemberMXBean memberBean = service.getMemberMXBean();   
+    MemberMXBean memberBean = service.getMemberMXBean();
     assertNotNull(memberBean);
-    
+
     assertTrue(memberBean instanceof MemberMBean);
-    
-    ((MemberMBean) memberBean).addNotificationListener(notificationListener, null, null);    
+
+    ((MemberMBean) memberBean).addNotificationListener(notificationListener, null, null);
   }
-    
+
   /**
    * Creates and adds a generic GaugeMonitor for an attribute of the MemberMXBean on a VM.
+   *
    * @param vm a virtual machine.
    * @param attribute the attribute to monitor.
    * @param highThreshold the high threshold trigger.
    * @param lowThreshold the low threshold trigger.
    */
-  protected void setupOffHeapMonitorOnVm(VM vm,final String attribute,final long highThreshold,final long lowThreshold) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        setupOffHeapMonitor(attribute,highThreshold,lowThreshold);
-      }      
-    });
+  private void setupOffHeapMonitorOnVm(final VM vm,
+                                       final String attribute,
+                                       final long highThreshold,
+                                       final long lowThreshold) {
+    vm.invoke(() -> setupOffHeapMonitor(attribute, highThreshold, lowThreshold));
   }
-  
+
   /**
    * Creates and adds a generic GaugeMonitor for an attribute of the MemberMXBean.
+   *
    * @param attribute the attribute to monitor.
    * @param highThreshold the high threshold trigger.
    * @param lowThreshold the low threshold trigger.
    */
-  protected void setupOffHeapMonitor(String attribute,long highThreshold,long lowThreshold) {
+  private void setupOffHeapMonitor(final String attribute, final long highThreshold, final long lowThreshold) throws JMException {
     ObjectName memberMBeanObjectName = MBeanJMXAdapter.getMemberMBeanName(InternalDistributedSystem.getConnectedInstance().getDistributedMember());
     assertNotNull(memberMBeanObjectName);
-    
-    try {
-      ObjectName offHeapMonitorName = new ObjectName("monitors:type=Gauge,attr=" + attribute);      
-      mbeanServer.createMBean("javax.management.monitor.GaugeMonitor", offHeapMonitorName);
-      
-      AttributeList al = new AttributeList();
-      al.add(new Attribute("ObservedObject", memberMBeanObjectName));
-      al.add(new Attribute("GranularityPeriod", 500));
-      al.add(new Attribute("ObservedAttribute", attribute));
-      al.add(new Attribute("Notify", true));
-      al.add(new Attribute("NotifyHigh", true));
-      al.add(new Attribute("NotifyLow", true));
-      al.add(new Attribute("HighTheshold",highThreshold));
-      al.add(new Attribute("LowThreshold",lowThreshold));
-      
-      mbeanServer.setAttributes(offHeapMonitorName, al);      
-      mbeanServer.addNotificationListener(offHeapMonitorName, notificationListener, null, null);
-      mbeanServer.invoke(offHeapMonitorName, "start", new Object[]{}, new String[]{});
-    } catch (Exception e) {
-      fail(e.getMessage());
-    }        
+
+    ObjectName offHeapMonitorName = new ObjectName("monitors:type=Gauge,attr=" + attribute);
+    mbeanServer.createMBean("javax.management.monitor.GaugeMonitor", offHeapMonitorName);
+
+    AttributeList al = new AttributeList();
+    al.add(new Attribute("ObservedObject", memberMBeanObjectName));
+    al.add(new Attribute("GranularityPeriod", 500));
+    al.add(new Attribute("ObservedAttribute", attribute));
+    al.add(new Attribute("Notify", true));
+    al.add(new Attribute("NotifyHigh", true));
+    al.add(new Attribute("NotifyLow", true));
+    al.add(new Attribute("HighTheshold", highThreshold));
+    al.add(new Attribute("LowThreshold", lowThreshold));
+
+    mbeanServer.setAttributes(offHeapMonitorName, al);
+    mbeanServer.addNotificationListener(offHeapMonitorName, notificationListener, null, null);
+    mbeanServer.invoke(offHeapMonitorName, "start", new Object[] {}, new String[] {});
   }
 
   /**
    * Waits to receive MBean notifications.
+   *
    * @param vm a virtual machine.
    * @param wait how long to wait for in millis.
    * @param interval the polling interval to check for notifications.
    * @param throwOnTimeout throws an exception on timeout if true.
    */
-  protected void waitForNotificationListenerOnVm(VM vm, final long wait,final long interval,final boolean throwOnTimeout) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        Wait.waitForCriterion(new WaitCriterion() {          
-          @Override
-          public boolean done() {
-            return (notificationListener.getNotificationSize() > 0);
-          }
-          
-          @Override
-          public String description() {
-            return "Awaiting Notification Listener";
-          }
-        }, wait, interval, throwOnTimeout);
-      }      
-    });
+  private void waitForNotificationListenerOnVm(final VM vm,
+                                               final long wait,
+                                               final long interval,
+                                               final boolean throwOnTimeout) {
+    vm.invoke(() -> await("Awaiting Notification Listener").atMost(wait, TimeUnit.MILLISECONDS).until(() -> assertTrue(notificationListener.getNotificationSize() > 0)));
   }
-  
+
   /**
    * Clears received notifications.
+   *
    * @param vm a virtual machine.
    */
-  protected void clearNotificationListenerOnVm(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        notificationListener.clear();
-      }      
-    });
-  }
-}
-/**
- * Collects MBean Notifications.
- */
-class OffHeapNotificationListener implements NotificationListener {
-  List<Notification> notificationList = Collections.synchronizedList(new ArrayList<Notification>());
-  
-  @Override
-  public void handleNotification(Notification notification, Object handback) {
-    this.notificationList.add(notification);
-  }    
-  
-  public void clear() {
-    this.notificationList.clear();
+  private void clearNotificationListenerOnVm(final VM vm) {
+    vm.invoke(() -> notificationListener.clear());
   }
-  
-  public int getNotificationSize() {
-    return this.notificationList.size();
+
+  /**
+   * Collects MBean Notifications.
+   */
+  private static class OffHeapNotificationListener implements NotificationListener {
+
+    List<Notification> notificationList = Collections.synchronizedList(new ArrayList<Notification>());
+
+    @Override
+    public void handleNotification(final Notification notification, final Object handback) {
+      this.notificationList.add(notification);
+    }
+
+    public void clear() {
+      this.notificationList.clear();
+    }
+
+    public int getNotificationSize() {
+      return this.notificationList.size();
+    }
   }
 }



[6/8] incubator-geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java
index 8d7d6d3..7480bf6 100644
--- a/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java
@@ -16,24 +16,25 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
+import static java.util.concurrent.TimeUnit.*;
+import static org.assertj.core.api.Assertions.*;
 
 import java.io.File;
-import java.util.Arrays;
-import java.util.List;
+import java.io.Serializable;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeoutException;
 
 import javax.management.ObjectName;
 
-import org.apache.geode.LogWriter;
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.DiskStore;
@@ -42,700 +43,366 @@ import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
 import org.apache.geode.cache.Scope;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.DiskRegion;
 import org.apache.geode.internal.cache.DiskRegionStats;
 import org.apache.geode.internal.cache.DistributedRegion;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.LocalRegion;
 import org.apache.geode.internal.cache.persistence.PersistentMemberID;
 import org.apache.geode.internal.cache.persistence.PersistentMemberManager;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
+import org.apache.geode.internal.process.ProcessUtils;
+import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.test.dunit.AsyncInvocation;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 
 /**
  * Test cases to cover all test cases which pertains to disk from Management
  * layer
- * 
- * 
  */
 @Category(DistributedTest.class)
-public class DiskManagementDUnitTest extends ManagementTestBase {
-
-  /**
-   * 
-   */
-  private static final long serialVersionUID = 1L;
+@SuppressWarnings({ "serial", "unused" })
+public class DiskManagementDUnitTest implements Serializable {
 
-  // This must be bigger than the dunit ack-wait-threshold for the revoke
-  // tests. The command line is setting the ack-wait-threshold to be
-  // 60 seconds.
-  private static final int MAX_WAIT = 70 * 1000;
-
-  boolean testFailed = false;
-
-  String failureCause = "";
-  static final String REGION_NAME = "region";
+  private static final String REGION_NAME = DiskManagementDUnitTest.class.getSimpleName() + "_region";
 
   private File diskDir;
 
-  protected static LogWriter logWriter;
+  @Manager
+  private VM managerVM;
 
-  public DiskManagementDUnitTest() throws Exception {
-    super();
-  
-    diskDir = new File("diskDir-" + getName()).getAbsoluteFile();
-    org.apache.geode.internal.FileUtil.delete(diskDir);
-    diskDir.mkdir();
-    diskDir.deleteOnExit();
-  }
+  @Member
+  private VM[] memberVMs;
 
-  @Override
-  protected final void postSetUpManagementTestBase() throws Exception {
-    failureCause = "";
-    testFailed = false;
-  }
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().start(true).build();
+
+  @Rule
+  public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
 
-  @Override
-  protected final void postTearDownManagementTestBase() throws Exception {
-    org.apache.geode.internal.FileUtil.delete(diskDir);
+  @Before
+  public void before() throws Exception {
+    this.diskDir = this.temporaryFolder.newFolder("diskDir");
   }
 
   /**
-   * Tests Disk Compaction from a MemberMbean which is at cache level. All the
+   * Tests Disk Compaction from a MemberMXBean which is at cache level. All the
    * disks which belong to the cache should be compacted.
-   * 
-   * @throws Exception
    */
-
   @Test
-  public void testDiskCompact() throws Throwable {
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
-    }
-    
-    for (VM vm : getManagedNodeList()) {
-      compactAllDiskStores(vm);
+  public void testDiskCompact() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
     }
 
+    for (VM memberVM : this.memberVMs) {
+      compactAllDiskStores(memberVM);
+    }
   }
 
   /**
-   * Tests Disk Compaction from a MemberMbean which is at cache level. All the
+   * Tests Disk Compaction from a MemberMXBean which is at cache level. All the
    * disks which belong to the cache should be compacted.
-   * 
-   * @throws Exception
    */
-
   @Test
-  public void testDiskCompactRemote() throws Throwable {
-
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
+  public void testDiskCompactRemote() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
     }
-    compactDiskStoresRemote(managingNode);
 
+    compactDiskStoresRemote(this.managerVM, this.memberVMs.length);
   }
 
   /**
    * Tests various operations defined on DiskStore Mbean
-   * 
-   * @throws Exception
    */
-
   @Test
-  public void testDiskOps() throws Throwable {
-
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
-      invokeFlush(vm);
-      invokeForceRoll(vm);
-      invokeForceCompaction(vm);
+  public void testDiskOps() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
+      invokeFlush(memberVM);
+      invokeForceRoll(memberVM);
+      invokeForceCompaction(memberVM);
     }
-
   }
 
   @Test
-  public void testDiskBackupAllMembers() throws Throwable {
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
-
+  public void testDiskBackupAllMembers() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
     }
-    backupAllMembers(managingNode);
+
+    backupAllMembers(this.managerVM, this.memberVMs.length);
   }
 
   /**
-   * Checks the test case of missing disks and revoking them through MemberMbean
+   * Checks the test case of missing disks and revoking them through MemberMXBean
    * interfaces
-   * 
-   * @throws Throwable
    */
-  @SuppressWarnings("serial")
   @Test
-  public void testMissingMembers() throws Throwable {
-
-    initManagement(false);
-    VM vm0 = getManagedNodeList().get(0);
-    VM vm1 = getManagedNodeList().get(1);
-    VM vm2 = getManagedNodeList().get(2);
-    
-    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating region in VM0");
-    createPersistentRegion(vm0);
-    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating region in VM1");
-    createPersistentRegion(vm1);
-
-    putAnEntry(vm0);
-
- 
-    managingNode.invoke(new SerializableRunnable("Check for waiting regions") {
-
-      public void run() {
-        Cache cache = getCache();
-        ManagementService service = getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        PersistentMemberDetails[] missingDiskStores = bean
-            .listMissingDiskStores();
-
-        assertNull(missingDiskStores);
-      }
-    });
+  public void testMissingMembers() throws Exception {
+    VM memberVM1 = this.memberVMs[0];
+    VM memberVM2 = this.memberVMs[1];
 
-    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("closing region in vm0");
-    closeRegion(vm0);
-
-    updateTheEntry(vm1);
-
-    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("closing region in vm1");
-    closeRegion(vm1);
-    AsyncInvocation future = createPersistentRegionAsync(vm0);
-    waitForBlockedInitialization(vm0);
-    assertTrue(future.isAlive());
-
-    managingNode.invoke(new SerializableRunnable("Revoke the member") {
-
-      public void run() {
-        Cache cache = getCache();
-        GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache;
-        ManagementService service = getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        PersistentMemberDetails[] missingDiskStores = bean
-        .listMissingDiskStores();
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("waiting members=" + missingDiskStores);
-        assertNotNull(missingDiskStores);
-        assertEquals(1, missingDiskStores.length);
-
-        for (PersistentMemberDetails id : missingDiskStores) {
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Missing DiskStoreID is =" + id.getDiskStoreId());
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Missing Host is =" + id.getHost());
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Missing Directory is =" + id.getDirectory());
-
-          try {
-            bean.revokeMissingDiskStores(id.getDiskStoreId());
-          } catch (Exception e) {
-            fail("revokeMissingDiskStores failed with exception " + e);
-          }
-        }
-      }
+    createPersistentRegion(memberVM1);
+    createPersistentRegion(memberVM2);
+
+    putAnEntry(memberVM1);
+
+    this.managerVM.invoke("checkForMissingDiskStores", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      PersistentMemberDetails[] missingDiskStores = distributedSystemMXBean.listMissingDiskStores();
+
+      assertThat(missingDiskStores).isNull();
     });
 
-    future.join(MAX_WAIT);
-    if (future.isAlive()) {
-      fail("Region not created within" + MAX_WAIT);
-    }
-    if (future.exceptionOccurred()) {
-      throw new Exception(future.getException());
-    }
-    checkForRecoveryStat(vm0, true);
-    // Check to make sure we recovered the old
-    // value of the entry.
-    SerializableRunnable checkForEntry = new SerializableRunnable(
-        "check for the entry") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        assertEquals("B", region.get("A"));
-      }
-    };
-    vm0.invoke(checkForEntry);
+    closeRegion(memberVM1);
 
-  }
+    updateTheEntry(memberVM2, "C");
 
-  protected void checkNavigation(final VM vm,
-      final DistributedMember diskMember, final String diskStoreName) {
-    SerializableRunnable checkNavigation = new SerializableRunnable(
-        "Check Navigation") {
-      public void run() {
+    closeRegion(memberVM2);
 
-        final ManagementService service = getManagementService();
+    AsyncInvocation creatingPersistentRegionAsync = createPersistentRegionAsync(memberVM1);
 
-        DistributedSystemMXBean disMBean = service.getDistributedSystemMXBean();
-        try {
-          ObjectName expected = MBeanJMXAdapter.getDiskStoreMBeanName(diskMember.getId(), diskStoreName);
-          ObjectName actual = disMBean.fetchDiskStoreObjectName(diskMember.getId(), diskStoreName);
-          assertEquals(expected, actual);
-        } catch (Exception e) {
-          fail("Disk Store Navigation Failed " + e);
-        }
+    memberVM1.invoke(() ->
+      await().until(() -> {
+        GemFireCacheImpl cache = (GemFireCacheImpl) this.managementTestRule.getCache();
+        PersistentMemberManager persistentMemberManager = cache.getPersistentMemberManager();
+        Map<String, Set<PersistentMemberID>> regions = persistentMemberManager.getWaitingRegions();
+        return !regions.isEmpty();
+      })
+    );
 
+    assertThat(creatingPersistentRegionAsync.isAlive()).isTrue();
 
-      }
-    };
-    vm.invoke(checkNavigation);
-  }
+    this.managerVM.invoke("revokeMissingDiskStore", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
+      PersistentMemberDetails[] missingDiskStores = bean.listMissingDiskStores();
 
-  /**
-   * get Distributed member for a given vm
-   */
-  @SuppressWarnings("serial")
-  protected static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
+      assertThat(missingDiskStores).isNotNull().hasSize(1);
+
+      assertThat(bean.revokeMissingDiskStores(missingDiskStores[0].getDiskStoreId())).isTrue();
+    });
+
+    await(creatingPersistentRegionAsync);
+
+    verifyRecoveryStats(memberVM1, true);
+
+    // Check to make sure we recovered the old value of the entry.
+    memberVM1.invoke("check for the entry", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      assertThat(region.get("A")).isEqualTo("B");
+    });
   }
 
   /**
    * Invokes flush on the given disk store by MBean interface
-   * 
-   * @param vm
-   *          reference to VM
    */
-  @SuppressWarnings("serial")
-  public void invokeFlush(final VM vm) {
-    SerializableRunnable invokeFlush = new SerializableRunnable(
-        "Invoke Flush On Disk") {
-      public void run() {
-        Cache cache = getCache();
-        DiskStoreFactory dsf = cache.createDiskStoreFactory();
-        String name = "testFlush_" + vm.getPid();
-        DiskStore ds = dsf.create(name);
-
-        ManagementService service = getManagementService();
-        DiskStoreMXBean bean = service.getLocalDiskStoreMBean(name);
-        assertNotNull(bean);
-        bean.flush();
-      }
-    };
-    vm.invoke(invokeFlush);
+  private void invokeFlush(final VM memberVM) {
+    memberVM.invoke("invokeFlush", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
+      String name = "testFlush_" + ProcessUtils.identifyPid();
+      DiskStore diskStore = diskStoreFactory.create(name);
+
+      ManagementService service = this.managementTestRule.getManagementService();
+      DiskStoreMXBean diskStoreMXBean = service.getLocalDiskStoreMBean(name);
+      assertThat(diskStoreMXBean).isNotNull();
+      assertThat(diskStoreMXBean.getName()).isEqualTo(diskStore.getName());
+
+      diskStoreMXBean.flush();
+    });
   }
 
   /**
    * Invokes force roll on disk store by MBean interface
-   * 
-   * @param vm
-   *          reference to VM
    */
-  @SuppressWarnings("serial")
-  public void invokeForceRoll(final VM vm) {
-    SerializableRunnable invokeForceRoll = new SerializableRunnable(
-        "Invoke Force Roll") {
-      public void run() {
-        Cache cache = getCache();
-        DiskStoreFactory dsf = cache.createDiskStoreFactory();
-        String name = "testForceRoll_" + vm.getPid();
-        DiskStore ds = dsf.create(name);
-        ManagementService service = getManagementService();
-        DiskStoreMXBean bean = service.getLocalDiskStoreMBean(name);
-        assertNotNull(bean);
-        bean.forceRoll();
-      }
-    };
-    vm.invoke(invokeForceRoll);
+  private void invokeForceRoll(final VM memberVM) {
+    memberVM.invoke("invokeForceRoll", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
+      String name = "testForceRoll_" + ProcessUtils.identifyPid();
+      DiskStore diskStore = diskStoreFactory.create(name);
+
+      ManagementService service = this.managementTestRule.getManagementService();
+      DiskStoreMXBean diskStoreMXBean = service.getLocalDiskStoreMBean(name);
+      assertThat(diskStoreMXBean).isNotNull();
+      assertThat(diskStoreMXBean.getName()).isEqualTo(diskStore.getName());
+
+      diskStoreMXBean.forceRoll();
+    });
   }
 
   /**
    * Invokes force compaction on disk store by MBean interface
-   * 
-   * @param vm
-   *          reference to VM
    */
-  @SuppressWarnings("serial")
-  public void invokeForceCompaction(final VM vm) {
-    SerializableRunnable invokeForceCompaction = new SerializableRunnable(
-        "Invoke Force Compaction") {
-      public void run() {
-        Cache cache = getCache();
-        DiskStoreFactory dsf = cache.createDiskStoreFactory();
-        dsf.setAllowForceCompaction(true);
-        String name = "testForceCompaction_" + vm.getPid();
-        DiskStore ds = dsf.create(name);
-        ManagementService service = getManagementService();
-        DiskStoreMXBean bean = service.getLocalDiskStoreMBean(name);
-        assertNotNull(bean);
-        assertEquals(false, bean.forceCompaction());
-      }
-    };
-    vm.invoke(invokeForceCompaction);
+  private void invokeForceCompaction(final VM memberVM) {
+    memberVM.invoke("invokeForceCompaction", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      DiskStoreFactory dsf = cache.createDiskStoreFactory();
+      dsf.setAllowForceCompaction(true);
+      String name = "testForceCompaction_" + ProcessUtils.identifyPid();
+      DiskStore diskStore = dsf.create(name);
+
+      ManagementService service = this.managementTestRule.getManagementService();
+      DiskStoreMXBean diskStoreMXBean = service.getLocalDiskStoreMBean(name);
+      assertThat(diskStoreMXBean).isNotNull();
+      assertThat(diskStoreMXBean.getName()).isEqualTo(diskStore.getName());
+
+      assertThat(diskStoreMXBean.forceCompaction()).isFalse();
+    });
   }
 
   /**
    * Makes the disk compactable by adding and deleting some entries
-   * 
-   * @throws Exception
    */
-  @SuppressWarnings("serial")
-  public void makeDiskCompactable(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Make The Disk Compactable") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        DiskRegion dr = ((LocalRegion) region).getDiskRegion();
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("putting key1");
-        region.put("key1", "value1");
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("putting key2");
-        region.put("key2", "value2");
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("removing key2");
-        region.remove("key2");
-        // now that it is compactable the following forceCompaction should
-        // go ahead and do a roll and compact it.
-      }
+  private void makeDiskCompactable(final VM memberVM) throws Exception {
+    memberVM.invoke("makeDiskCompactable", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      region.put("key1", "value1");
+      region.put("key2", "value2");
+      region.remove("key2");
+      // now that it is compactable the following forceCompaction should
+      // go ahead and do a roll and compact it.
     });
-
   }
 
-
-
- 
-
   /**
    * Compacts all DiskStores belonging to a member
-   * 
-   * @param vm1
-   *          reference to VM
-   * @throws Exception
    */
-  @SuppressWarnings("serial")
-  public void compactAllDiskStores(VM vm1) throws Exception {
-
-    vm1.invoke(new SerializableCallable("Compact All Disk Stores") {
-
-      public Object call() throws Exception {
-        ManagementService service = getManagementService();
-        MemberMXBean memberBean = service.getMemberMXBean();
-        String[] compactedDiskStores = memberBean.compactAllDiskStores();
-
-        assertTrue(compactedDiskStores.length > 0);
-        for (int i = 0; i < compactedDiskStores.length; i++) {
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info(
-              "<ExpectedString> Compacted Store " + i + " "
-                  + compactedDiskStores[i] + "</ExpectedString> ");
-        }
-
-        return null;
-      }
+  private void compactAllDiskStores(final VM memberVM) throws Exception {
+    memberVM.invoke("compactAllDiskStores", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      MemberMXBean memberMXBean = service.getMemberMXBean();
+      String[] compactedDiskStores = memberMXBean.compactAllDiskStores();
+      assertThat(compactedDiskStores).hasSize(1);
     });
-
   }
 
   /**
    * Takes a back up of all the disk store in a given directory
    */
-  @SuppressWarnings("serial")
-  public void backupAllMembers(final VM managingVM) throws Exception {
-
-    managingVM.invoke(new SerializableCallable("Backup All Disk Stores") {
+  private void backupAllMembers(final VM managerVM, final int memberCount) {
+    managerVM.invoke("backupAllMembers", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
+      File backupDir = this.temporaryFolder.newFolder("backupDir");
 
-      public Object call() throws Exception {
-        ManagementService service = getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        DiskBackupStatus status = bean.backupAllMembers(getBackupDir("test_backupAllMembers")
-            .getAbsolutePath(), null);
+      DiskBackupStatus status = bean.backupAllMembers(backupDir.getAbsolutePath(), null);
 
-        return null;
-      }
+      assertThat(status.getBackedUpDiskStores().keySet().size()).isEqualTo(memberCount);
+      assertThat(status.getOfflineDiskStores()).isEqualTo(null); // TODO: fix GEODE-1946
     });
-
   }
 
   /**
-   * Compact a disk store from Managing node
+   * Compact a disk store from managerVM VM
    */
-  @SuppressWarnings("serial")
-  public void compactDiskStoresRemote(VM managingVM) throws Exception {
-    {
-
-      managingVM.invoke(new SerializableCallable("Compact All Disk Stores Remote") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          Set<DistributedMember> otherMemberSet = cache
-              .getDistributionManager().getOtherNormalDistributionManagerIds();
-
-          for (DistributedMember member : otherMemberSet) {
-            MemberMXBean bean = MBeanUtil.getMemberMbeanProxy(member);
-            String[] allDisks = bean.listDiskStores(true);
-            assertNotNull(allDisks);
-            List<String> listString = Arrays.asList(allDisks);
-            org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info(
-                "<ExpectedString> Remote All Disk Stores Are  "
-                    + listString.toString() + "</ExpectedString> ");
-            String[] compactedDiskStores = bean.compactAllDiskStores();
-            assertTrue(compactedDiskStores.length > 0);
-            for (int i = 0; i < compactedDiskStores.length; i++) {
-              org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info(
-                  "<ExpectedString> Remote Compacted Store " + i + " "
-                      + compactedDiskStores[i] + "</ExpectedString> ");
-            }
-
-          }
-          return null;
-        }
-      });
+  private void compactDiskStoresRemote(final VM managerVM, final int memberCount) {
+    managerVM.invoke("compactDiskStoresRemote", () -> {
+      Set<DistributedMember> otherMemberSet = this.managementTestRule.getOtherNormalMembers();// ((GemFireCacheImpl)cache).getDistributionManager().getOtherNormalDistributionManagerIds();
+      assertThat(otherMemberSet.size()).isEqualTo(memberCount);
 
-    }
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-  }
+      for (DistributedMember member : otherMemberSet) {
+        MemberMXBean memberMXBean = awaitMemberMXBeanProxy(member);
 
-  /**
-   * Checks if a file with the given extension is present
-   * 
-   * @param fileExtension
-   *          file extension
-   * @throws Exception
-   */
-  protected void checkIfContainsFileWithExt(String fileExtension)
-      throws Exception {
-    File[] files = diskDir.listFiles();
-    for (int j = 0; j < files.length; j++) {
-      if (files[j].getAbsolutePath().endsWith(fileExtension)) {
-        fail("file \"" + files[j].getAbsolutePath() + "\" still exists");
-      }
-    }
+        String[] allDisks = memberMXBean.listDiskStores(true);
+        assertThat(allDisks).isNotNull().hasSize(1);
 
-  }
-
-  /**
-   * Update Entry
-   * 
-   * @param vm1
-   *          reference to VM
-   */
-  protected void updateTheEntry(VM vm1) {
-    updateTheEntry(vm1, "C");
-  }
-
-  /**
-   * Update an Entry
-   * @param vm1
-   *          reference to VM
-   * @param value
-   *          Value which is updated
-   */
-  @SuppressWarnings("serial")
-  protected void updateTheEntry(VM vm1, final String value) {
-    vm1.invoke(new SerializableRunnable("change the entry") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        region.put("A", value);
+        String[] compactedDiskStores = memberMXBean.compactAllDiskStores();
+        assertThat(compactedDiskStores).hasSize(1);
       }
     });
   }
 
-  /**
-   * Put an entry to region
-   * 
-   * @param vm0
-   *          reference to VM
-   */
-  @SuppressWarnings("serial")
-  protected void putAnEntry(VM vm0) {
-    vm0.invoke(new SerializableRunnable("Put an entry") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        region.put("A", "B");
-      }
+  private void updateTheEntry(final VM memberVM, final String value) {
+    memberVM.invoke("updateTheEntry", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      region.put("A", value);
     });
   }
 
-  /**
-   * Close the given region REGION_NAME
-   * 
-   * @param vm
-   *          reference to VM
-   */
-  @SuppressWarnings("serial")
-  protected void closeRegion(final VM vm) {
-    SerializableRunnable closeRegion = new SerializableRunnable(
-        "Close persistent region") {
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        region.close();
-      }
-    };
-    vm.invoke(closeRegion);
+  private void putAnEntry(final VM memberVM) {
+    memberVM.invoke("putAnEntry", () -> {
+      Cache cache = managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      region.put("A", "B");
+    });
   }
 
-  /**
-   * Waiting to blocked waiting for another persistent member to come online
-   * 
-   * @param vm
-   *          reference to VM
-   */
-  @SuppressWarnings("serial")
-  private void waitForBlockedInitialization(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-
-      public void run() {
-        Wait.waitForCriterion(new WaitCriterion() {
-
-          public String description() {
-            return "Waiting to blocked waiting for another persistent member to come online";
-          }
-
-          public boolean done() {
-            Cache cache = getCache();
-            GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache;
-            PersistentMemberManager mm = cacheImpl.getPersistentMemberManager();
-            Map<String, Set<PersistentMemberID>> regions = mm
-                .getWaitingRegions();
-            boolean done = !regions.isEmpty();
-            return done;
-          }
-
-        }, MAX_WAIT, 100, true);
-
-      }
-
+  private void closeRegion(final VM memberVM) {
+    memberVM.invoke("closeRegion", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      region.close();
     });
   }
 
-  /**
-   * Creates a persistent region
-   * 
-   * @param vm
-   *          reference to VM
-   * @throws Throwable
-   */
-  protected void createPersistentRegion(VM vm) throws Throwable {
-    AsyncInvocation future = createPersistentRegionAsync(vm);
-    future.join(MAX_WAIT);
-    if (future.isAlive()) {
-      fail("Region not created within" + MAX_WAIT);
-    }
-    if (future.exceptionOccurred()) {
-      throw new RuntimeException(future.getException());
-    }
+  private void createPersistentRegion(final VM memberVM) throws InterruptedException, ExecutionException, TimeoutException {
+    await(createPersistentRegionAsync(memberVM));
   }
 
-  /**
-   * Creates a persistent region in async manner
-   * 
-   * @param vm
-   *          reference to VM
-   * @return reference to AsyncInvocation
-   */
-  @SuppressWarnings("serial")
-  protected AsyncInvocation createPersistentRegionAsync(final VM vm) {
-    SerializableRunnable createRegion = new SerializableRunnable(
-        "Create persistent region") {
-      public void run() {
-        Cache cache = getCache();
-        DiskStoreFactory dsf = cache.createDiskStoreFactory();
-        File dir = getDiskDirForVM(vm);
-        dir.mkdirs();
-        dsf.setDiskDirs(new File[] { dir });
-        dsf.setMaxOplogSize(1);
-        dsf.setAllowForceCompaction(true);
-        dsf.setAutoCompact(false);
-        DiskStore ds = dsf.create(REGION_NAME);
-        RegionFactory rf = cache.createRegionFactory();
-        rf.setDiskStoreName(ds.getName());
-        rf.setDiskSynchronous(true);
-        rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
-        rf.setScope(Scope.DISTRIBUTED_ACK);
-        rf.create(REGION_NAME);
-      }
-    };
-    return vm.invokeAsync(createRegion);
+  private AsyncInvocation createPersistentRegionAsync(final VM memberVM) {
+    return memberVM.invokeAsync("createPersistentRegionAsync", () -> {
+      File dir = new File(diskDir, String.valueOf(ProcessUtils.identifyPid()));
+
+      Cache cache = this.managementTestRule.getCache();
+
+      DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
+      diskStoreFactory.setDiskDirs(new File[] { dir });
+      diskStoreFactory.setMaxOplogSize(1);
+      diskStoreFactory.setAllowForceCompaction(true);
+      diskStoreFactory.setAutoCompact(false);
+      DiskStore diskStore = diskStoreFactory.create(REGION_NAME);
+
+      RegionFactory regionFactory = cache.createRegionFactory();
+      regionFactory.setDiskStoreName(diskStore.getName());
+      regionFactory.setDiskSynchronous(true);
+      regionFactory.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
+      regionFactory.setScope(Scope.DISTRIBUTED_ACK);
+      regionFactory.create(REGION_NAME);
+    });
   }
 
-  /**
-   * Validates a persistent region
-   * 
-   * @param vm
-   *          reference to VM
-   */
-  @SuppressWarnings("serial")
-  protected void validatePersistentRegion(final VM vm) {
-    SerializableRunnable validateDisk = new SerializableRunnable(
-        "Validate persistent region") {
-      public void run() {
-        Cache cache = getCache();
-        ManagementService service = getManagementService();
-        DiskStoreMXBean bean = service.getLocalDiskStoreMBean(REGION_NAME);
-        assertNotNull(bean);
+  private void verifyRecoveryStats(final VM memberVM, final boolean localRecovery) {
+    memberVM.invoke("verifyRecoveryStats", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      DistributedRegion distributedRegion = (DistributedRegion) region;
+      DiskRegionStats stats = distributedRegion.getDiskRegion().getStats();
+
+      if (localRecovery) {
+        assertThat(stats.getLocalInitializations()).isEqualTo(1);
+        assertThat(stats.getRemoteInitializations()).isEqualTo(0);
+      } else {
+        assertThat(stats.getLocalInitializations()).isEqualTo(0);
+        assertThat(stats.getRemoteInitializations()).isEqualTo(1);
       }
-    };
-    vm.invoke(validateDisk);
+    });
   }
 
-  /**
-   * Appends vm id to disk dir
-   * 
-   * @param vm
-   *          reference to VM
-   * @return
-   */
-  protected File getDiskDirForVM(final VM vm) {
-    File dir = new File(diskDir, String.valueOf(vm.getPid()));
-    return dir;
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getMemberMBeanName(member);
+    await().until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
   }
 
-  /**
-   * Checks recovery status
-   * 
-   * @param vm
-   *          reference to VM
-   * @param localRecovery
-   *          local recovery on or not
-   */
-  @SuppressWarnings("serial")
-  private void checkForRecoveryStat(VM vm, final boolean localRecovery) {
-    vm.invoke(new SerializableRunnable("check disk region stat") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        DistributedRegion distributedRegion = (DistributedRegion) region;
-        DiskRegionStats stats = distributedRegion.getDiskRegion().getStats();
-        if (localRecovery) {
-          assertEquals(1, stats.getLocalInitializations());
-          assertEquals(0, stats.getRemoteInitializations());
-        } else {
-          assertEquals(0, stats.getLocalInitializations());
-          assertEquals(1, stats.getRemoteInitializations());
-        }
-
-      }
-    });
+  private void await(final AsyncInvocation createPersistentRegionAsync) throws InterruptedException, ExecutionException, TimeoutException {
+    createPersistentRegionAsync.await(2, MINUTES);
   }
 
-  /**
-   * 
-   * @return back up directory
-   */
-  protected static File getBackupDir(String name) throws Exception {
-    File backUpDir = new File("BackupDir-" + name).getAbsoluteFile();
-    org.apache.geode.internal.FileUtil.delete(backUpDir);
-    backUpDir.mkdir();
-    backUpDir.deleteOnExit();
-    return backUpDir;
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
   }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java
index b343dad..743fcaa 100644
--- a/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java
@@ -16,23 +16,19 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
+import static java.util.concurrent.TimeUnit.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.Invoke.*;
+import static org.assertj.core.api.Assertions.*;
 
+import java.io.Serializable;
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import javax.management.InstanceNotFoundException;
 import javax.management.ListenerNotFoundException;
 import javax.management.MBeanServer;
 import javax.management.Notification;
@@ -41,11 +37,16 @@ import javax.management.NotificationFilter;
 import javax.management.NotificationListener;
 import javax.management.ObjectName;
 
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
 import org.apache.logging.log4j.Logger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
 
-import org.apache.geode.cache.Cache;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.internal.admin.Alert;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.logging.LogService;
@@ -59,843 +60,482 @@ import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.management.internal.beans.MemberMBean;
 import org.apache.geode.management.internal.beans.SequenceNumber;
 import org.apache.geode.test.dunit.IgnoredException;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
- * Distributed System tests
- * 
- * a) For all the notifications 
- * 
- *  i) gemfire.distributedsystem.member.joined
- * 
- *  ii) gemfire.distributedsystem.member.left
- * 
- *  iii) gemfire.distributedsystem.member.suspect
- * 
- *  iv ) All notifications emitted by member mbeans
- * 
- *  vi) Alerts
- * 
+ * Distributed System management tests
+ * <p>
+ * a) For all the notifications
+ * i) gemfire.distributedsystem.member.joined
+ * ii) gemfire.distributedsystem.member.left
+ * iii) gemfire.distributedsystem.member.suspect
+ * iv ) All notifications emitted by member mbeans
+ * vi) Alerts
+ * <p>
  * b) Concurrently modify proxy list by removing member and accessing the
  * distributed system MBean
- * 
+ * <p>
  * c) Aggregate Operations like shutDownAll
- * 
+ * <p>
  * d) Member level operations like fetchJVMMetrics()
- * 
+ * <p>
  * e ) Statistics
- * 
- * 
- * 
  */
 @Category(DistributedTest.class)
-public class DistributedSystemDUnitTest extends ManagementTestBase {
+@SuppressWarnings({ "serial", "unused" })
+public class DistributedSystemDUnitTest implements Serializable {
 
   private static final Logger logger = LogService.getLogger();
-  
-  private static final long serialVersionUID = 1L;
-
- 
-  private static final int MAX_WAIT = 10 * 1000;
-  
-  private static MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-  
-  static List<Notification> notifList = new ArrayList<>();
-  
-  static Map<ObjectName , NotificationListener> notificationListenerMap = new HashMap<ObjectName , NotificationListener>();
-  
-  static final String WARNING_LEVEL_MESSAGE = "Warninglevel Alert Message";
-  
-  static final String SEVERE_LEVEL_MESSAGE =  "Severelevel Alert Message";
-
-  
-  public DistributedSystemDUnitTest() {
-    super();
+
+  private static final String WARNING_LEVEL_MESSAGE = "Warning Level Alert Message";
+  private static final String SEVERE_LEVEL_MESSAGE = "Severe Level Alert Message";
+
+  private static List<Notification> notifications;
+  private static Map<ObjectName, NotificationListener> notificationListenerMap;
+
+  @Manager
+  private VM managerVM;
+
+  @Member
+  private VM[] memberVMs;
+
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
+
+  @Before
+  public void before() throws Exception {
+    notifications = new ArrayList<>();
+    notificationListenerMap = new HashMap<>();
+
+    invokeInEveryVM(() -> notifications = new ArrayList<>());
+    invokeInEveryVM(() -> notificationListenerMap = new HashMap<>());
+  }
+
+  @After
+  public void after() throws Exception {
+    resetAlertCounts(this.managerVM);
   }
 
   /**
    * Tests each and every operations that is defined on the MemberMXBean
-   * 
-   * @throws Exception
    */
   @Test
   public void testDistributedSystemAggregate() throws Exception {
-    VM managingNode = getManagingNode();
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    addNotificationListener(managingNode);
+    this.managementTestRule.createManager(this.managerVM);
+    addNotificationListener(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
-      createCache(vm);
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
     }
-    
-    checkAggregate(managingNode);
-    for (VM vm : getManagedNodeList()) {
-      closeCache(vm);
-    }
-
-    closeCache(managingNode);
 
+    verifyDistributedSystemMXBean(this.managerVM);
   }
-   
+
   /**
    * Tests each and every operations that is defined on the MemberMXBean
-   * 
-   * @throws Exception
    */
   @Test
   public void testAlertManagedNodeFirst() throws Exception {
-
-    for (VM vm : getManagedNodeList()) {
-      createCache(vm);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    VM managingNode = getManagingNode();
+    this.managementTestRule.createManager(this.managerVM);
+    addAlertListener(this.managerVM);
+    verifyAlertCount(this.managerVM, 0, 0);
 
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    addAlertListener(managingNode);
-    checkAlertCount(managingNode, 0, 0);
-
-    final DistributedMember managingMember = getMember(managingNode);
+    DistributedMember managerDistributedMember = this.managementTestRule.getDistributedMember(this.managerVM);
 
     // Before we start we need to ensure that the initial (implicit) SEVERE alert has propagated everywhere.
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.SEVERE);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.SEVERE);
     }
 
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.WARNING));
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.WARNING));
 
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.WARNING);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.WARNING);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    checkAlertCount(managingNode, 3, 3);
-    resetAlertCounts(managingNode);
-
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.SEVERE));
+    verifyAlertCount(this.managerVM, 3, 3);
+    resetAlertCounts(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.SEVERE);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
-    }
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.SEVERE));
 
-    checkAlertCount(managingNode, 3, 0);
-    resetAlertCounts(managingNode);
-    
-    for (VM vm : getManagedNodeList()) {
-      closeCache(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.SEVERE);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    closeCache(managingNode);
+    verifyAlertCount(this.managerVM, 3, 0);
   }
-  
-  @SuppressWarnings("serial")
-  public void ensureLoggerState(VM vm1, final DistributedMember member,
-      final int alertLevel) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Ensure Logger State") {
-
-        public Object call() throws Exception {
-          
-          Wait.waitForCriterion(new WaitCriterion() {
-            public String description() {
-              return "Waiting for all alert Listener to register with managed node";
-            }
-
-            public boolean done() {
-
-              if (AlertAppender.getInstance().hasAlertListener(member, alertLevel)) {
-                return true;
-              }
-              return false;
-            }
-
-          }, MAX_WAIT, 500, true);
-
-          return null;
-        }
-      });
 
-    }
-  }
-  
   /**
    * Tests each and every operations that is defined on the MemberMXBean
-   * 
-   * @throws Exception
    */
   @Test
   public void testShutdownAll() throws Exception {
-    final Host host = Host.getHost(0);
-    VM managedNode1 = host.getVM(0);
-    VM managedNode2 = host.getVM(1);
-    VM managedNode3 = host.getVM(2);
-
-    VM managingNode = host.getVM(3);
-
-    // Managing Node is created first
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    
-    createCache(managedNode1);
-    createCache(managedNode2);
-    createCache(managedNode3);
-    shutDownAll(managingNode);
-    closeCache(managingNode);
+    VM memberVM1 = getHost(0).getVM(0);
+    VM memberVM2 = getHost(0).getVM(1);
+    VM memberVM3 = getHost(0).getVM(2);
+
+    VM managerVM = getHost(0).getVM(3);
+
+    // managerVM Node is created first
+    this.managementTestRule.createManager(managerVM);
+
+    this.managementTestRule.createMember(memberVM1);
+    this.managementTestRule.createMember(memberVM2);
+    this.managementTestRule.createMember(memberVM3);
+
+    shutDownAll(managerVM);
   }
-  
+
   @Test
-  public void testNavigationAPIS() throws Exception{
-    
-    final Host host = Host.getHost(0); 
-    
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    
-    for(VM vm : managedNodeList){
-      createCache(vm);
+  public void testNavigationAPIS() throws Exception {
+    this.managementTestRule.createManager(this.managerVM);
+
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
     }
-    
-    checkNavigationAPIs(managingNode);    
+
+    verifyFetchMemberObjectName(this.managerVM, this.memberVMs.length + 1);
   }
-  
+
   @Test
   public void testNotificationHub() throws Exception {
-    this.initManagement(false);
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
 
     class NotificationHubTestListener implements NotificationListener {
+
       @Override
       public synchronized void handleNotification(Notification notification, Object handback) {
         logger.info("Notification received {}", notification);
-        notifList.add(notification);
+        notifications.add(notification);
       }
     }
 
-    managingNode
-        .invoke(new SerializableRunnable("Add Listener to MemberMXBean") {
-
-          public void run() {
-            Cache cache = getCache();
-            ManagementService service = getManagementService();
-            final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-            
-            Wait.waitForCriterion(new WaitCriterion() {
-              public String description() {
-                return "Waiting for all members to send their initial Data";
-              }
-
-              public boolean done() {
-                if (bean.listMemberObjectNames().length == 5) {// including locator 
-                  return true;
-                } else {
-                  return false;
-                }
-              }
-            }, MAX_WAIT, 500, true);
-            for (ObjectName objectName : bean.listMemberObjectNames()) {
-              NotificationHubTestListener listener = new NotificationHubTestListener();
-              try {
-                mbeanServer.addNotificationListener(objectName, listener, null,
-                    null);
-                notificationListenerMap.put(objectName, listener);
-              } catch (InstanceNotFoundException e) {
-                LogWriterUtils.getLogWriter().error(e);
-              }
-            }
-          }
-        });
+    this.managerVM.invoke("addListenerToMemberMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      final DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
 
-    // Check in all VMS
+      await().until(() -> assertThat(distributedSystemMXBean.listMemberObjectNames()).hasSize(5));
 
-    for (VM vm : managedNodeList) {
-      vm.invoke(new SerializableRunnable("Check Hub Listener num count") {
-
-        public void run() {
-          Cache cache = getCache();
-          SystemManagementService service = (SystemManagementService) getManagementService();
-          NotificationHub hub = service.getNotificationHub();
-          Map<ObjectName, NotificationHubListener> listenerObjectMap = hub
-              .getListenerObjectMap();
-          assertEquals(1, listenerObjectMap.keySet().size());
-          ObjectName memberMBeanName = MBeanJMXAdapter.getMemberMBeanName(cache
-              .getDistributedSystem().getDistributedMember());
+      for (ObjectName objectName : distributedSystemMXBean.listMemberObjectNames()) {
+        NotificationHubTestListener listener = new NotificationHubTestListener();
+        ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener, null, null);
+        notificationListenerMap.put(objectName, listener);
+      }
+    });
 
-          NotificationHubListener listener = listenerObjectMap
-              .get(memberMBeanName);
+    // Check in all VMS
 
-          /*
-           * Counter of listener should be 2 . One for default Listener which is
-           * added for each member mbean by distributed system mbean One for the
-           * added listener in test
-           */
-          assertEquals(2, listener.getNumCounter());
+    for (VM memberVM : this.memberVMs) {
+      memberVM.invoke("checkNotificationHubListenerCount", () -> {
+        SystemManagementService service = this.managementTestRule.getSystemManagementService();
+        NotificationHub notificationHub = service.getNotificationHub();
+        Map<ObjectName, NotificationHubListener> listenerMap = notificationHub.getListenerObjectMap();
+        assertThat(listenerMap.keySet()).hasSize(1);
 
-          // Raise some notifications
+        ObjectName memberMBeanName = MBeanJMXAdapter.getMemberMBeanName(this.managementTestRule.getDistributedMember());
+        NotificationHubListener listener = listenerMap.get(memberMBeanName);
 
-          NotificationBroadcasterSupport memberLevelNotifEmitter = (MemberMBean) service
-              .getMemberMXBean();
+        /*
+         * Counter of listener should be 2 . One for default Listener which is
+         * added for each member mbean by distributed system mbean One for the
+         * added listener in test
+         */
+        assertThat(listener.getNumCounter()).isEqualTo(2);
 
-          String memberSource = MBeanJMXAdapter.getMemberNameOrId(cache
-              .getDistributedSystem().getDistributedMember());
+        // Raise some notifications
 
-          // Only a dummy notification , no actual region is creates
-          Notification notification = new Notification(
-              JMXNotificationType.REGION_CREATED, memberSource, SequenceNumber
-                  .next(), System.currentTimeMillis(),
-                  ManagementConstants.REGION_CREATED_PREFIX + "/test");
-          memberLevelNotifEmitter.sendNotification(notification);
+        NotificationBroadcasterSupport notifier = (MemberMBean) service.getMemberMXBean();
+        String memberSource = MBeanJMXAdapter.getMemberNameOrId(this.managementTestRule.getDistributedMember());
 
-        }
+        // Only a dummy notification , no actual region is created
+        Notification notification = new Notification(JMXNotificationType.REGION_CREATED, memberSource, SequenceNumber.next(), System.currentTimeMillis(), ManagementConstants.REGION_CREATED_PREFIX + "/test");
+        notifier.sendNotification(notification);
       });
     }
 
-    managingNode.invoke(new SerializableRunnable(
-        "Check notifications && Remove Listeners") {
-
-      public void run() {
-
-        Wait.waitForCriterion(new WaitCriterion() {
-          public String description() {
-            return "Waiting for all Notifications to reach the Managing Node";
-          }
-
-          public boolean done() {
-            if (notifList.size() == 3) {
-              return true;
-            } else {
-              return false;
-            }
-          }
-        }, MAX_WAIT, 500, true);
-
-        notifList.clear();
-
-        Iterator<ObjectName> it = notificationListenerMap.keySet().iterator();
-        while (it.hasNext()) {
-          ObjectName objectName = it.next();
-          NotificationListener listener = notificationListenerMap
-              .get(objectName);
-          try {
-            mbeanServer.removeNotificationListener(objectName, listener);
-          } catch (ListenerNotFoundException e) {
-            LogWriterUtils.getLogWriter().error(e);
-          } catch (InstanceNotFoundException e) {
-            LogWriterUtils.getLogWriter().error(e);
-          }
-        }
+    this.managerVM.invoke("checkNotificationsAndRemoveListeners", () -> {
+      await().until(() -> assertThat(notifications).hasSize(3));
 
+      notifications.clear();
+
+      for (ObjectName objectName : notificationListenerMap.keySet()) {
+        NotificationListener listener = notificationListenerMap.get(objectName);
+        ManagementFactory.getPlatformMBeanServer().removeNotificationListener(objectName, listener);
       }
     });
 
     // Check in all VMS again
 
-    for (VM vm : managedNodeList) {
-      vm.invoke(new SerializableRunnable("Check Hub Listener num count Again") {
-
-        public void run() {
-          Cache cache = getCache();
-          SystemManagementService service = (SystemManagementService) getManagementService();
-          NotificationHub hub = service.getNotificationHub();
-          Map<ObjectName, NotificationHubListener> listenerObjectMap = hub
-              .getListenerObjectMap();
-
-          assertEquals(1, listenerObjectMap.keySet().size());
-
-          ObjectName memberMBeanName = MBeanJMXAdapter.getMemberMBeanName(cache
-              .getDistributedSystem().getDistributedMember());
-
-          NotificationHubListener listener = listenerObjectMap
-              .get(memberMBeanName);
-
-          /*
-           * Counter of listener should be 1 for the default Listener which is
-           * added for each member mbean by distributed system mbean.
-           */
-          assertEquals(1, listener.getNumCounter());
-
-        }
+    for (VM memberVM : this.memberVMs) {
+      memberVM.invoke("checkNotificationHubListenerCountAgain", () -> {
+        SystemManagementService service = this.managementTestRule.getSystemManagementService();
+        NotificationHub hub = service.getNotificationHub();
+        Map<ObjectName, NotificationHubListener> listenerObjectMap = hub.getListenerObjectMap();
+        assertThat(listenerObjectMap.keySet().size()).isEqualTo(1);
+
+        ObjectName memberMBeanName = MBeanJMXAdapter.getMemberMBeanName(this.managementTestRule.getDistributedMember());
+        NotificationHubListener listener = listenerObjectMap.get(memberMBeanName);
+
+        /*
+         * Counter of listener should be 1 for the default Listener which is
+         * added for each member mbean by distributed system mbean.
+         */
+        assertThat(listener.getNumCounter()).isEqualTo(1);
       });
     }
 
-    managingNode
-    .invoke(new SerializableRunnable("Remove Listener from MemberMXBean") {
-
-      public void run() {
-        Cache cache = getCache();
-        ManagementService service = getManagementService();
-        final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        
-        Wait.waitForCriterion(new WaitCriterion() {
-          public String description() {
-            return "Waiting for all members to send their initial Data";
-          }
-
-          public boolean done() {
-            if (bean.listMemberObjectNames().length == 5) {// including locator 
-              return true;
-            } else {
-              return false;
-            }
-
-          }
-
-        }, MAX_WAIT, 500, true);
-        for (ObjectName objectName : bean.listMemberObjectNames()) {
-          NotificationHubTestListener listener = new NotificationHubTestListener();
-          try {
-            mbeanServer.removeNotificationListener(objectName, listener);
-          } catch (InstanceNotFoundException e) {
-            LogWriterUtils.getLogWriter().error(e);
-          } catch (ListenerNotFoundException e) {
-            // TODO: apparently there is never a notification listener on any these mbeans at this point 
-            // fix this test so it doesn't hit these unexpected exceptions -- getLogWriter().error(e);
-          }
+    this.managerVM.invoke("removeListenerFromMemberMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+
+      await().until(() -> assertThat(distributedSystemMXBean.listMemberObjectNames()).hasSize(5));
+
+      for (ObjectName objectName : distributedSystemMXBean.listMemberObjectNames()) {
+        NotificationHubTestListener listener = new NotificationHubTestListener();
+        try {
+          ManagementFactory.getPlatformMBeanServer().removeNotificationListener(objectName, listener); // because new instance!!
+        } catch (ListenerNotFoundException e) {
+          // TODO: [old] apparently there is never a notification listener on any these mbeans at this point [fix this]
+          // fix this test so it doesn't hit these unexpected exceptions -- getLogWriter().error(e);
         }
       }
     });
-    
-    for (VM vm : managedNodeList) {
-      vm.invoke(new SerializableRunnable("Check Hub Listeners clean up") {
-
-        public void run() {
-          Cache cache = getCache();
-          SystemManagementService service = (SystemManagementService) getManagementService();
-          NotificationHub hub = service.getNotificationHub();
-          hub.cleanUpListeners();
-          assertEquals(0, hub.getListenerObjectMap().size());
-
-          Iterator<ObjectName> it = notificationListenerMap.keySet().iterator();
-          while (it.hasNext()) {
-            ObjectName objectName = it.next();
-            NotificationListener listener = notificationListenerMap
-                .get(objectName);
-            try {
-              mbeanServer.removeNotificationListener(objectName, listener);
-              fail("Found Listeners inspite of clearing them");
-            } catch (ListenerNotFoundException e) {
-              // Expected Exception Do nothing
-            } catch (InstanceNotFoundException e) {
-              LogWriterUtils.getLogWriter().error(e);
-            }
-          }
+
+    for (VM memberVM : this.memberVMs) {
+      memberVM.invoke("verifyNotificationHubListenersWereRemoved", () -> {
+        SystemManagementService service = this.managementTestRule.getSystemManagementService();
+        NotificationHub notificationHub = service.getNotificationHub();
+        notificationHub.cleanUpListeners();
+        assertThat(notificationHub.getListenerObjectMap()).isEmpty();
+
+        for (ObjectName objectName : notificationListenerMap.keySet()) {
+          NotificationListener listener = notificationListenerMap.get(objectName);
+          assertThatThrownBy(() -> ManagementFactory.getPlatformMBeanServer().removeNotificationListener(objectName, listener)).isExactlyInstanceOf(ListenerNotFoundException.class);
         }
       });
     }
   }
-  
+
   /**
    * Tests each and every operations that is defined on the MemberMXBean
-   * 
-   * @throws Exception
    */
   @Test
   public void testAlert() throws Exception {
-    VM managingNode = getManagingNode();
-   
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    addAlertListener(managingNode);
-    resetAlertCounts(managingNode);
-    
-    final DistributedMember managingMember = getMember(managingNode);
-    
-    
-    
-    warnLevelAlert(managingNode);
-    severeLevelAlert(managingNode);
-    checkAlertCount(managingNode, 1, 0);
-    resetAlertCounts(managingNode);
-    
-    for (VM vm : getManagedNodeList()) {
-      
-      createCache(vm);
-      // Default is severe ,So only Severe level alert is expected
-      
-      ensureLoggerState(vm, managingMember, Alert.SEVERE);
-      
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
-      
-    }
-    checkAlertCount(managingNode, 3, 0);
-    resetAlertCounts(managingNode);
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.WARNING));
-
-    
-    for (VM vm : getManagedNodeList()) {
-      // warning and severe alerts both are to be checked
-      ensureLoggerState(vm, managingMember, Alert.WARNING);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
-    }
+    this.managementTestRule.createManager(this.managerVM);
+    addAlertListener(this.managerVM);
+    resetAlertCounts(this.managerVM);
+
+    DistributedMember managerDistributedMember = this.managementTestRule.getDistributedMember(this.managerVM);
+
+    generateWarningAlert(this.managerVM);
+    generateSevereAlert(this.managerVM);
+    verifyAlertCount(this.managerVM, 1, 0);
+    resetAlertCounts(this.managerVM);
+
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
 
-    checkAlertCount(managingNode, 3, 3);
-    
-    resetAlertCounts(managingNode);
-    
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.OFF));
-    
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.OFF);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.SEVERE);
+
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
-    checkAlertCount(managingNode, 0, 0);
-    resetAlertCounts(managingNode);
-    
-    for (VM vm : getManagedNodeList()) {
-      closeCache(vm);
+
+    verifyAlertCount(this.managerVM, 3, 0);
+    resetAlertCounts(this.managerVM);
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.WARNING));
+
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.WARNING);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    closeCache(managingNode);
+    verifyAlertCount(this.managerVM, 3, 3);
 
-  }
-  
-  @SuppressWarnings("serial")
-  public void checkAlertCount(VM vm1, final int expectedSevereAlertCount,
-      final int expectedWarningAlertCount) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Check Alert Count") {
-
-        public Object call() throws Exception {
-          final AlertNotifListener nt = AlertNotifListener.getInstance();
-          Wait.waitForCriterion(new WaitCriterion() {
-            public String description() {
-              return "Waiting for all alerts to reach the Managing Node";
-            }
-            public boolean done() {
-              if (expectedSevereAlertCount == nt.getseverAlertCount()
-                  && expectedWarningAlertCount == nt.getWarnigAlertCount()) {
-                return true;
-              } else {
-                return false;
-              }
-
-            }
-
-          }, MAX_WAIT, 500, true);
-
-          return null;
-        }
-      });
+    resetAlertCounts(this.managerVM);
+
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.OFF));
 
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.OFF);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
+
+    verifyAlertCount(this.managerVM, 0, 0);
   }
-  
 
+  private void verifyAlertAppender(final VM memberVM, final DistributedMember member, final int alertLevel) {
+    memberVM.invoke("verifyAlertAppender", () -> await().until(() -> assertThat(AlertAppender.getInstance().hasAlertListener(member, alertLevel)).isTrue()));
+  }
 
-  
-  @SuppressWarnings("serial")
-  public void setAlertLevel(VM vm1, final String alertLevel) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Set Alert level") {
+  private void verifyAlertCount(final VM managerVM, final int expectedSevereAlertCount, final int expectedWarningAlertCount) {
+    managerVM.invoke("verifyAlertCount", () -> {
+      AlertNotificationListener listener = AlertNotificationListener.getInstance();
 
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(bean);
-          bean.changeAlertLevel(alertLevel);
+      await().until(() -> assertThat(listener.getSevereAlertCount()).isEqualTo(expectedSevereAlertCount));
+      await().until(() -> assertThat(listener.getWarningAlertCount()).isEqualTo(expectedWarningAlertCount));
+    });
+  }
 
-          return null;
-        }
-      });
+  private void setAlertLevel(final VM managerVM, final String alertLevel) {
+    managerVM.invoke("setAlertLevel", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      distributedSystemMXBean.changeAlertLevel(alertLevel);
+    });
+  }
 
-    }
+  private void generateWarningAlert(final VM anyVM) {
+    anyVM.invoke("generateWarningAlert", () -> {
+      IgnoredException ignoredException = IgnoredException.addIgnoredException(WARNING_LEVEL_MESSAGE);
+      logger.warn(WARNING_LEVEL_MESSAGE);
+      ignoredException.remove();
+    });
   }
-  
-  @SuppressWarnings("serial")
-  public void warnLevelAlert(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Warning level Alerts") {
-
-        public Object call() throws Exception {
-          final IgnoredException warnEx = IgnoredException.addIgnoredException(WARNING_LEVEL_MESSAGE);
-          logger.warn(WARNING_LEVEL_MESSAGE);
-          warnEx.remove();
-          return null;
-        }
-      });
 
-    }
+  private void resetAlertCounts(final VM managerVM) {
+    managerVM.invoke("resetAlertCounts", () -> {
+      AlertNotificationListener listener = AlertNotificationListener.getInstance();
+      listener.resetCount();
+    });
   }
-  
-  
-  @SuppressWarnings("serial")
-  public void resetAlertCounts(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Reset Alert Count") {
-
-        public Object call() throws Exception {
-          AlertNotifListener nt =  AlertNotifListener.getInstance();
-          nt.resetCount();
-          return null;
-        }
-      });
 
-    }
+  private void generateSevereAlert(final VM anyVM) {
+    anyVM.invoke("generateSevereAlert", () -> {
+      IgnoredException ignoredException = IgnoredException.addIgnoredException(SEVERE_LEVEL_MESSAGE);
+      logger.fatal(SEVERE_LEVEL_MESSAGE);
+      ignoredException.remove();
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void severeLevelAlert(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Severe Level Alert") {
-
-        public Object call() throws Exception {
-          // add expected exception strings         
-          
-          final IgnoredException severeEx = IgnoredException.addIgnoredException(SEVERE_LEVEL_MESSAGE);
-          logger.fatal(SEVERE_LEVEL_MESSAGE);
-          severeEx.remove();
-          return null;
-        }
-      });
+  private void addAlertListener(final VM managerVM) {
+    managerVM.invoke("addAlertListener", () -> {
+      AlertNotificationListener listener = AlertNotificationListener.getInstance();
+      listener.resetCount();
 
-    }
-  }
-  
-  @SuppressWarnings("serial")
-  public void addAlertListener(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Add Alert Listener") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          AlertNotifListener nt =  AlertNotifListener.getInstance();
-          nt.resetCount();
-          
-          NotificationFilter notificationFilter = new NotificationFilter() {
-            @Override
-            public boolean isNotificationEnabled(Notification notification) {
-              return notification.getType().equals(JMXNotificationType.SYSTEM_ALERT);
-            }
-
-          };
-          
-          mbeanServer.addNotificationListener(MBeanJMXAdapter
-              .getDistributedSystemName(), nt, notificationFilter, null);
-
-          return null;
-        }
-      });
+      NotificationFilter notificationFilter = (Notification notification) -> notification.getType().equals(JMXNotificationType.SYSTEM_ALERT);
 
-    }
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(MBeanJMXAdapter.getDistributedSystemName(), listener, notificationFilter, null);
+    });
   }
-  
+
   /**
    * Check aggregate related functions and attributes
-   * @param vm1
-   * @throws Exception
    */
-  @SuppressWarnings("serial")
-  public void checkAggregate(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Chech Aggregate Attributes") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-          ManagementService service = getManagementService();
-
-          final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(service.getDistributedSystemMXBean());
-          
-          Wait.waitForCriterion(new WaitCriterion() {
-            public String description() {
-              return "Waiting All members to intitialize DistributedSystemMBean expect 5 but found " + bean.getMemberCount();
-            }
-            public boolean done() {
-              // including locator
-              if (bean.getMemberCount() == 5) {
-                return true;
-              } else {
-                return false;
-              }
-
-            }
-
-          }, MAX_WAIT, 500, true);
-
-
-
-          final Set<DistributedMember> otherMemberSet = cache
-              .getDistributionManager().getOtherNormalDistributionManagerIds();
-          Iterator<DistributedMember> memberIt = otherMemberSet.iterator();
-          while (memberIt.hasNext()) {
-            DistributedMember member = memberIt.next();
-            LogWriterUtils.getLogWriter().info(
-                "JVM Metrics For Member " + member.getId() + ":"
-                    + bean.showJVMMetrics(member.getId()));
-            LogWriterUtils.getLogWriter().info(
-                "OS Metrics For Member " + member.getId() + ":"
-                    + bean.showOSMetrics(member.getId()));
-          }
-
-          return null;
-        }
-      });
+  private void verifyDistributedSystemMXBean(final VM managerVM) {
+    managerVM.invoke("verifyDistributedSystemMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
 
-    }
+      await().until(() -> assertThat(distributedSystemMXBean.getMemberCount()).isEqualTo(5));
+
+      Set<DistributedMember> otherMemberSet = this.managementTestRule.getOtherNormalMembers();
+      for (DistributedMember member : otherMemberSet) {
+        // TODO: need assertions? JVMMetrics and OSMetrics
+      }
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void addNotificationListener(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Add Notification Listener") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(bean);
-          TestDistributedSystemNotif nt = new TestDistributedSystemNotif();
-          mbeanServer.addNotificationListener(MBeanJMXAdapter
-              .getDistributedSystemName(), nt, null, null);
-
-          return null;
-        }
-      });
+  private void addNotificationListener(final VM managerVM) {
+    managerVM.invoke("addNotificationListener", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      assertThat(distributedSystemMXBean).isNotNull();
 
-    }
+      DistributedSystemNotificationListener listener = new DistributedSystemNotificationListener();
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(MBeanJMXAdapter.getDistributedSystemName(), listener, null, null);
+    });
   }
 
- 
-
-  @SuppressWarnings("serial")
-  public void shutDownAll(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Shut Down All") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(service.getDistributedSystemMXBean());
-          bean.shutDownAllMembers();
-          Wait.pause(2000);
-          assertEquals(
-              cache.getDistributedSystem().getAllOtherMembers().size(), 1);
-          return null;
-        }
-      });
+  private void shutDownAll(final VM managerVM) {
+    managerVM.invoke("shutDownAll", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      distributedSystemMXBean.shutDownAllMembers();
 
-    }
+      await().until(() -> assertThat(this.managementTestRule.getOtherNormalMembers()).hasSize(0));
+    });
   }
-  
-
-  
-  @SuppressWarnings("serial")
-  public void checkNavigationAPIs(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Check Navigation APIS") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          
-          assertNotNull(service.getDistributedSystemMXBean());
-          
-          waitForAllMembers(4);
-          
-          for(int i =0; i< bean.listMemberObjectNames().length ; i++){
-            LogWriterUtils.getLogWriter().info(
-                "ObjectNames Of the Mmeber" + bean.listMemberObjectNames()[i] );
-          }
-
-          
-          ObjectName thisMemberName = MBeanJMXAdapter
-              .getMemberMBeanName(InternalDistributedSystem
-                  .getConnectedInstance().getDistributedMember().getId());
-
-          ObjectName memberName = bean
-              .fetchMemberObjectName(InternalDistributedSystem
-                  .getConnectedInstance().getDistributedMember().getId());
-          assertEquals(thisMemberName, memberName);
-          
-          return null;
-        }
-      });
 
-    }
+  private void verifyFetchMemberObjectName(final VM managerVM, final int memberCount) {
+    managerVM.invoke("verifyFetchMemberObjectName", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+
+      await().until(() -> assertThat(distributedSystemMXBean.listMemberObjectNames()).hasSize(memberCount));
+
+      String memberId = this.managementTestRule.getDistributedMember().getId();
+      ObjectName thisMemberName = MBeanJMXAdapter.getMemberMBeanName(memberId);
+      ObjectName memberName = distributedSystemMXBean.fetchMemberObjectName(memberId);
+      assertThat(memberName).isEqualTo(thisMemberName);
+    });
   }
 
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
+  }
 
-  /**
-   * Notification handler
-   * 
-   * 
-   */
-  private static class TestDistributedSystemNotif implements
-      NotificationListener {
+  private static class DistributedSystemNotificationListener implements NotificationListener {
 
     @Override
-    public void handleNotification(Notification notification, Object handback) {
-      assertNotNull(notification);      
+    public void handleNotification(final Notification notification, final Object handback) {
+      assertThat(notification).isNotNull();
     }
-
   }
-  
-  /**
-   * Notification handler
-   * 
-   * 
-   */
-  private static class AlertNotifListener implements NotificationListener {
-    
-    private static AlertNotifListener listener = new AlertNotifListener();
-    
-    public static AlertNotifListener getInstance(){
+
+  private static class AlertNotificationListener implements NotificationListener {
+
+    private static AlertNotificationListener listener = new AlertNotificationListener();
+
+    private int warningAlertCount = 0;
+
+    private int severeAlertCount = 0;
+
+    static AlertNotificationListener getInstance() { // TODO: get rid of singleton
       return listener;
     }
 
-    private int warnigAlertCount = 0;
+    @Override
+    public synchronized void handleNotification(final Notification notification, final Object handback) {
+      assertThat(notification).isNotNull();
 
-    private int severAlertCount = 0;
+      Map<String, String> notificationUserData = (Map<String, String>) notification.getUserData();
 
-    @Override
-    public synchronized void handleNotification(Notification notification, Object handback) {
-      assertNotNull(notification);
-      logger.info("Notification received {}", notification);
-      Map<String,String> notifUserData = (Map<String,String>)notification.getUserData();
-      if (notifUserData.get(JMXNotificationUserData.ALERT_LEVEL).equalsIgnoreCase("warning")) {
-        assertEquals(WARNING_LEVEL_MESSAGE,notification.getMessage());
-        ++warnigAlertCount;
+      if (notificationUserData.get(JMXNotificationUserData.ALERT_LEVEL).equalsIgnoreCase("warning")) {
+        assertThat(notification.getMessage()).isEqualTo(WARNING_LEVEL_MESSAGE);
+        warningAlertCount++;
       }
-      if (notifUserData.get(JMXNotificationUserData.ALERT_LEVEL).equalsIgnoreCase("severe")) {
-        assertEquals(SEVERE_LEVEL_MESSAGE,notification.getMessage());
-        ++severAlertCount;
+      if (notificationUserData.get(JMXNotificationUserData.ALERT_LEVEL).equalsIgnoreCase("severe")) {
+        assertThat(notification.getMessage()).isEqualTo(SEVERE_LEVEL_MESSAGE);
+        severeAlertCount++;
       }
     }
 
-    public void resetCount() {
-      warnigAlertCount = 0;
-
-      severAlertCount = 0;
+    void resetCount() {
+      warningAlertCount = 0;
+      severeAlertCount = 0;
     }
 
-    public int getWarnigAlertCount() {
-      return warnigAlertCount;
+    int getWarningAlertCount() {
+      return warningAlertCount;
     }
 
-    public int getseverAlertCount() {
-      return severAlertCount;
+    int getSevereAlertCount() {
+      return severeAlertCount;
     }
-
   }
-
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java
index ffa024f..dd22f7d 100644
--- a/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java
@@ -51,7 +51,7 @@ import org.apache.geode.test.junit.categories.FlakyTest;
 import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 import org.apache.geode.util.test.TestUtil;
 
-public class JMXMBeanDUnitTest extends DistributedTestCase {
+public class JMXMBeanDUnitTest extends DistributedTestCase { // TODO: rename and fix on Mac
 
   private Host host;
   private VM locator;


[5/8] incubator-geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java
index a426096..a91a2e1 100644
--- a/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java
@@ -16,54 +16,82 @@
  */
 package org.apache.geode.management;
 
+import static java.util.concurrent.TimeUnit.*;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.junit.Assert.*;
+import static org.apache.geode.internal.AvailablePortHelper.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.NetworkUtils.*;
+import static org.assertj.core.api.Assertions.*;
 
 import java.io.File;
-import java.io.IOException;
+import java.io.Serializable;
 import java.net.InetAddress;
-import java.net.UnknownHostException;
 import java.util.Properties;
 
+import javax.management.ObjectName;
+
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.Locator;
 import org.apache.geode.distributed.internal.DistributionConfig;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.distributed.internal.InternalLocator;
-import org.apache.geode.internal.AvailablePortHelper;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.management.internal.ManagementConstants;
-import org.apache.geode.test.dunit.Assert;
+import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableCallable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
 
 /**
- * Test cases
- * 
- * DistributedSystem Cache Locator no no yes yes no yes yes yes yes
+ * Distributed tests for managing {@code Locator} with {@link LocatorMXBean}.
  */
 @Category(DistributedTest.class)
-public class LocatorManagementDUnitTest extends ManagementTestBase {
+@SuppressWarnings({ "serial", "unused" })
+public class LocatorManagementDUnitTest implements Serializable {
+
+  private static final int MAX_WAIT_MILLIS = 120 * 1000;
+
+  private static final int ZERO = 0;
+
+  @Manager
+  private VM managerVM;
+  @Member
+  private VM[] membersVM;
+  private VM locatorVM;
 
-  private static final int MAX_WAIT = 8 * ManagementConstants.REFRESH_TIME;
+  private String hostName;
+  private int port;
 
-  private VM locator;
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-  @Override
-  protected final void postSetUpManagementTestBase() throws Exception {
-    locator = managedNode1;
+  @Rule
+  public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void before() throws Exception {
+//    this.managerVM = managingNode;
+//    this.membersVM = getManagedNodeList().toArray(new VM[getManagedNodeList().size()]);
+    this.locatorVM = this.membersVM[0];
+    this.hostName = getServerHostName(getHost(0));
+    this.port = getRandomAvailableTCPPort();
   }
 
-  @Override
-  protected final void preTearDownManagementTestBase() throws Exception {
-    stopLocator(locator);
+  @After
+  public void after() throws Exception {
+    stopLocator(this.locatorVM);
   }
 
   /**
@@ -72,48 +100,52 @@ public class LocatorManagementDUnitTest extends ManagementTestBase {
    */
   @Test
   public void testPeerLocation() throws Exception {
-    int locPort = AvailablePortHelper.getRandomAvailableTCPPort();
-    startLocator(locator, true, locPort);
-    locatorMBeanExist(locator, locPort, true);
+    startLocator(this.locatorVM, true, this.port);
+
+    verifyLocalLocatorMXBean(this.locatorVM, this.port, true);
 
-    Host host = Host.getHost(0);
-    String host0 = getServerHostName(host);
     Properties props = new Properties();
     props.setProperty(MCAST_PORT, "0");
-    props.setProperty(LOCATORS, host0 + "[" + locPort
-        + "]");
+    props.setProperty(LOCATORS, this.hostName + "[" + this.port + "]");
     props.setProperty(JMX_MANAGER, "true");
     props.setProperty(JMX_MANAGER_START, "false");
     props.setProperty(JMX_MANAGER_PORT, "0");
     props.setProperty(JMX_MANAGER_HTTP_PORT, "0");
-    createCache(managingNode, props);
-    startManagingNode(managingNode);
-    DistributedMember locatorMember = getMember(locator);
-    remoteLocatorMBeanExist(managingNode,locatorMember);
 
+    this.managementTestRule.createManager(this.managerVM, props, false);
+    this.managementTestRule.startManager(this.managerVM);
+
+    verifyRemoteLocatorMXBeanProxy(this.managerVM, this.managementTestRule.getDistributedMember(this.locatorVM));
   }
 
   @Test
   public void testPeerLocationWithPortZero() throws Exception {
-    // Start the locator with port=0
-    int locPort = startLocator(locator, true, 0);
-    locatorMBeanExist(locator, locPort, true);
+    this.port = startLocator(this.locatorVM, true, ZERO);
+    //this.locatorVM.invoke(() -> this.managementTestRule.getCache());
+
+    this.locatorVM.invoke(() -> assertHasCache());
+
+    verifyLocalLocatorMXBean(this.locatorVM, this.port, true);
 
-    Host host = Host.getHost(0);
-    String host0 = getServerHostName(host);
     Properties props = new Properties();
     props.setProperty(MCAST_PORT, "0");
-    props.setProperty(LOCATORS, host0 + "[" + locPort
-        + "]");
+    props.setProperty(LOCATORS, this.hostName + "[" + this.port + "]");
     props.setProperty(JMX_MANAGER, "true");
     props.setProperty(JMX_MANAGER_START, "false");
     props.setProperty(JMX_MANAGER_PORT, "0");
     props.setProperty(JMX_MANAGER_HTTP_PORT, "0");
-    createCache(managingNode, props);
-    startManagingNode(managingNode);
-    DistributedMember locatorMember = getMember(locator);
-    remoteLocatorMBeanExist(managingNode,locatorMember);
 
+    this.managementTestRule.createManager(this.managerVM, props, false);
+    this.managementTestRule.startManager(this.managerVM);
+
+    verifyRemoteLocatorMXBeanProxy(this.managerVM, this.managementTestRule.getDistributedMember(this.locatorVM));
+  }
+
+  private void assertHasCache() {
+    assertThat(GemFireCacheImpl.getInstance()).isNotNull();
+    assertThat(GemFireCacheImpl.getInstance().isClosed()).isFalse();
+    assertThat(InternalDistributedSystem.getAnyInstance()).isNotNull();
+    assertThat(InternalDistributedSystem.getAnyInstance().isConnected()).isTrue();
   }
 
   /**
@@ -121,276 +153,199 @@ public class LocatorManagementDUnitTest extends ManagementTestBase {
    */
   @Test
   public void testColocatedLocator() throws Exception {
-    initManagement(false);
-    int locPort = AvailablePortHelper.getRandomAvailableTCPPort();
-    startLocator(locator, false, locPort);
-    locatorMBeanExist(locator, locPort, false);
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
+
+    startLocator(this.locatorVM, false, this.port);
 
+    verifyLocalLocatorMXBean(this.locatorVM, this.port, false);
   }
 
   @Test
   public void testColocatedLocatorWithPortZero() throws Exception {
-    initManagement(false);
-    int locPort = startLocator(locator, false, 0);
-    locatorMBeanExist(locator, locPort, false);
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
+
+    this.port = startLocator(this.locatorVM, false, ZERO);
 
+    verifyLocalLocatorMXBean(this.locatorVM, this.port, false);
   }
 
   @Test
   public void testListManagers() throws Exception {
-    initManagement(false);
-    int locPort = AvailablePortHelper.getRandomAvailableTCPPort();
-    startLocator(locator, false, locPort);
-    listManagers(locator, locPort, false);
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
+
+    startLocator(this.locatorVM, false, this.port);
+
+    verifyListManagers(this.locatorVM);
   }
 
   @Test
   public void testListManagersWithPortZero() throws Exception {
-    initManagement(false);
-    int locPort = startLocator(locator, false, 0);
-    listManagers(locator, locPort, false);
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
+
+    this.port = startLocator(this.locatorVM, false, ZERO);
+
+    verifyListManagers(this.locatorVM);
   }
 
   @Test
   public void testWillingManagers() throws Exception {
-    int locPort = AvailablePortHelper.getRandomAvailableTCPPort();
-    startLocator(locator, true, locPort);
+    startLocator(this.locatorVM, true, this.port);
 
-    Host host = Host.getHost(0);
-    String host0 = getServerHostName(host);
-    
     Properties props = new Properties();
     props.setProperty(MCAST_PORT, "0");
-    props.setProperty(LOCATORS, host0 + "[" + locPort
-        + "]");
+    props.setProperty(LOCATORS, this.hostName + "[" + this.port + "]");
     props.setProperty(JMX_MANAGER, "true");
 
-    createCache(managedNode2, props);
-    createCache(managedNode3, props);
+    this.managementTestRule.createMember(this.membersVM[1], props);
+    this.managementTestRule.createMember(this.membersVM[2], props);
 
-    listWillingManagers(locator, locPort, false);
+    verifyListPotentialManagers(this.locatorVM);
   }
 
   @Test
   public void testWillingManagersWithPortZero() throws Exception {
-    int locPort = startLocator(locator, true, 0);
-
-    Host host = Host.getHost(0);
-    String host0 = getServerHostName(host);
+    this.port = startLocator(this.locatorVM, true, 0);
 
     Properties props = new Properties();
     props.setProperty(MCAST_PORT, "0");
-    props.setProperty(LOCATORS, host0 + "[" + locPort
-        + "]");
+    props.setProperty(LOCATORS, this.hostName + "[" + this.port + "]");
     props.setProperty(JMX_MANAGER, "true");
 
-    createCache(managedNode2, props);
-    createCache(managedNode3, props);
+    this.managementTestRule.createMember(this.membersVM[1], props);
+    this.managementTestRule.createMember(this.membersVM[2], props);
 
-    listWillingManagers(locator, locPort, false);
+    verifyListPotentialManagers(this.locatorVM);
   }
 
   /**
    * Starts a locator with given configuration.
    * If DS is already started it will use the same DS
-   * 
-   * @param vm
-   *          reference to VM
    */
-  protected Integer startLocator(final VM vm, final boolean isPeer, final int port) {
-
-    return (Integer) vm.invoke(new SerializableCallable("Start Locator In VM") {
-
-      public Object call() throws Exception {
+  private int startLocator(final VM locatorVM, final boolean isPeer, final int port) {
+    return locatorVM.invoke("startLocator", () -> {
+      assertThat(InternalLocator.hasLocator()).isFalse();
 
-        assertFalse(InternalLocator.hasLocator());
+      Properties properties = new Properties();
+      properties.setProperty(MCAST_PORT, "0");
+      properties.setProperty(LOCATORS, "");
 
-        Properties props = new Properties();
-        props.setProperty(MCAST_PORT, "0");
+      InetAddress bindAddress = InetAddress.getByName(this.hostName);
+      File logFile = this.temporaryFolder.newFile(testName.getMethodName() + "-locator-" + port + ".log");
+      Locator locator = Locator.startLocatorAndDS(port, logFile, bindAddress, properties, isPeer, true, null);
 
-        props.setProperty(LOCATORS, "");
-        props.setProperty(LOG_LEVEL, LogWriterUtils.getDUnitLogLevel());
+      assertThat(InternalLocator.hasLocator()).isTrue();
 
-        InetAddress bindAddr = null;
-        try {
-          bindAddr = InetAddress.getByName(getServerHostName(vm.getHost()));
-        } catch (UnknownHostException uhe) {
-          Assert.fail("While resolving bind address ", uhe);
-        }
-
-        Locator locator = null;
-        try {
-          File logFile = new File(getTestMethodName() + "-locator" + port + ".log");
-          locator = Locator.startLocatorAndDS(port, logFile, bindAddr, props, isPeer, true, null);
-        } catch (IOException ex) {
-          Assert.fail("While starting locator on port " + port, ex);
-        }
+      return locator.getPort();
+    });
+  }
 
-        assertTrue(InternalLocator.hasLocator());
-        return locator.getPort();
-      }
+  private void stopLocator(final VM locatorVM) {
+    locatorVM.invoke("stopLocator", () -> {
+      assertThat(InternalLocator.hasLocator()).isTrue();
+      InternalLocator.getLocator().stop();
     });
   }
 
-  /**
-   * Creates a persistent region
-   * 
-   * @param vm
-   *          reference to VM
-   */
-  protected String stopLocator(VM vm) {
+  private void verifyLocalLocatorMXBean(final VM locatorVM, final int port, final boolean isPeer) {
+    locatorVM.invoke("verifyLocalLocatorMXBean", () -> {
+      //ManagementService service = this.managementTestRule.getExistingManagementService();
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      ManagementService service = ManagementService.getExistingManagementService(cache);
+      assertThat(service).isNotNull();
 
-    return (String) vm.invoke(new SerializableCallable("Stop Locator In VM") {
+      LocatorMXBean locatorMXBean = service.getLocalLocatorMXBean();
+      assertThat(locatorMXBean).isNotNull();
+      assertThat(locatorMXBean.getPort()).isEqualTo(port);
 
-      public Object call() throws Exception {
+      //        LogWriterUtils.getLogWriter().info("Log of Locator" + bean.viewLog());
+      //        LogWriterUtils.getLogWriter().info("BindAddress" + bean.getBindAddress());
 
-        assertTrue(InternalLocator.hasLocator());
-        InternalLocator.getLocator().stop();
-        return null;
-      }
+      assertThat(locatorMXBean.isPeerLocator()).isEqualTo(isPeer);
     });
   }
 
-  /**
-   * Creates a persistent region
-   * 
-   * @param vm
-   *          reference to VM
-   */
-  protected void locatorMBeanExist(VM vm, final int locPort,
-      final boolean isPeer) {
-
-    vm.invoke(new SerializableCallable("Locator MBean created") {
-
-      public Object call() throws Exception {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-        ManagementService service = ManagementService
-            .getExistingManagementService(cache);
-        assertNotNull(service);
-        LocatorMXBean bean = service.getLocalLocatorMXBean();
-        assertNotNull(bean);
-        assertEquals(locPort, bean.getPort());
-        LogWriterUtils.getLogWriter().info("Log of Locator" + bean.viewLog());
-        LogWriterUtils.getLogWriter().info("BindAddress" + bean.getBindAddress());
-        assertEquals(isPeer, bean.isPeerLocator());
-        return null;
-      }
-    });
-  }
-
-  /**
-   * Creates a persistent region
-   * 
-   * @param vm
-   *          reference to VM
-   */
-  protected void remoteLocatorMBeanExist(VM vm, final DistributedMember member) {
-
-    vm.invoke(new SerializableCallable("Locator MBean created") {
-
-      public Object call() throws Exception {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        ManagementService service = ManagementService
-            .getExistingManagementService(cache);
-        assertNotNull(service);
-        LocatorMXBean bean = MBeanUtil.getLocatorMbeanProxy(member);
-        assertNotNull(bean);
+  private void verifyRemoteLocatorMXBeanProxy(final VM managerVM, final DistributedMember locatorMember) {
+    managerVM.invoke("verifyRemoteLocatorMXBeanProxy", () -> {
+      //ManagementService service = this.managementTestRule.getExistingManagementService();
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      ManagementService service = ManagementService.getExistingManagementService(cache);
+      assertThat(service).isNotNull();
 
-        LogWriterUtils.getLogWriter().info("Log of Locator" + bean.viewLog());
-        LogWriterUtils.getLogWriter().info("BindAddress" + bean.getBindAddress());
+      // LocatorMXBean locatorMXBean = MBeanUtil.getLocatorMbeanProxy(locatorMember); // TODO
+      LocatorMXBean locatorMXBean = awaitLockServiceMXBeanProxy(locatorMember);
+      assertThat(locatorMXBean).isNotNull();
 
-        return null;
-      }
+      //        LogWriterUtils.getLogWriter().info("Log of Locator" + bean.viewLog());
+      //        LogWriterUtils.getLogWriter().info("BindAddress" + bean.getBindAddress());
     });
   }
 
-  /**
-   * Creates a persistent region
-   * 
-   * @param vm
-   *          reference to VM
-   */
-  protected void listManagers(VM vm, final int locPort, final boolean isPeer) {
-
-    vm.invoke(new SerializableCallable("List Managers") {
-
-      public Object call() throws Exception {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+  private void verifyListManagers(final VM locatorVM) {
+    locatorVM.invoke("verifyListManagers", () -> {
+      //ManagementService service = this.managementTestRule.getExistingManagementService();
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      ManagementService service = ManagementService.getExistingManagementService(cache);
+      assertThat(service).isNotNull();
 
-        ManagementService service = ManagementService
-            .getExistingManagementService(cache);
-        assertNotNull(service);
-        final LocatorMXBean bean = service.getLocalLocatorMXBean();
-        assertNotNull(bean);
+      LocatorMXBean locatorMXBean = service.getLocalLocatorMXBean();
+      assertThat(locatorMXBean).isNotNull();
 
-        Wait.waitForCriterion(new WaitCriterion() {
+      await().until(() -> assertThat(locatorMXBean.listManagers()).hasSize(1));
+    });
+  }
 
-          public String description() {
-            return "Waiting for the managers List";
-          }
+  private void verifyListPotentialManagers(final VM locatorVM) {
+    locatorVM.invoke("verifyListPotentialManagers", () -> {
+      //ManagementService service = this.managementTestRule.getExistingManagementService();
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      ManagementService service = ManagementService.getExistingManagementService(cache);
+      assertThat(service).isNotNull();
 
-          public boolean done() {
+      //LocatorMXBean locatorMXBean = service.getLocalLocatorMXBean();
+      LocatorMXBean locatorMXBean = awaitLockServiceMXBean();
+      assertThat(locatorMXBean).isNotNull();
 
-            boolean done = bean.listManagers().length == 1;
-            return done;
-          }
+      await("listPotentialManagers has size 3").until(() -> assertThat(locatorMXBean.listPotentialManagers()).hasSize(3));
+    });
+  }
 
-        }, MAX_WAIT, 500, true);
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(MAX_WAIT_MILLIS, MILLISECONDS);
+  }
 
-        return null;
-      }
-    });
+  private ConditionFactory await(final String alias) {
+    return Awaitility.await(alias).atMost(MAX_WAIT_MILLIS, MILLISECONDS);
   }
 
   /**
-   * Creates a persistent region
-   * 
-   * @param vm
-   *          reference to VM
+   * Await and return a LocatorMXBean proxy for a specific member.
    */
-  protected void listWillingManagers(VM vm, final int locPort,
-      final boolean isPeer) {
-
-    vm.invoke(new SerializableCallable("List Willing Managers") {
-
-      public Object call() throws Exception {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-        ManagementService service = ManagementService
-            .getExistingManagementService(cache);
-        assertNotNull(service);
-        final LocatorMXBean bean = service.getLocalLocatorMXBean();
-        assertNotNull(bean);
-
-        Wait.waitForCriterion(new WaitCriterion() {
+  private LocatorMXBean awaitLockServiceMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName locatorMBeanName = service.getLocatorMBeanName(member);
 
-          public String description() {
-            return "Waiting for the Willing managers List";
-          }
+    await().until(() -> assertThat(service.getMBeanProxy(locatorMBeanName, LocatorMXBean.class)).isNotNull());
 
-          public boolean done() {
+    return service.getMBeanProxy(locatorMBeanName, LocatorMXBean.class);
+  }
 
-            boolean done = bean.listPotentialManagers().length == 3;
-            return done;
-          }
+  /**
+   * Await creation of local LocatorMXBean.
+   */
+  private LocatorMXBean awaitLockServiceMXBean() {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-        }, MAX_WAIT, 500, true);
+    await().until(() -> assertThat(service.getLocalLocatorMXBean()).isNotNull());
 
-        return null;
-      }
-    });
+    return service.getLocalLocatorMXBean();
   }
-  
-  /** get the host name to use for a server cache in client/server dunit
-   * testing
-   * @param host
-   * @return the host name
-   */
+
   public static String getServerHostName(Host host) {
     return System.getProperty(DistributionConfig.GEMFIRE_PREFIX + "server-bind-address") != null ?
-        System.getProperty(DistributionConfig.GEMFIRE_PREFIX + "server-bind-address")
-        : host.getHostName();
+      System.getProperty(DistributionConfig.GEMFIRE_PREFIX + "server-bind-address") : host.getHostName();
   }
-
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java b/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java
index 77514eb..b4ee5be 100644
--- a/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java
+++ b/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java
@@ -19,15 +19,17 @@ package org.apache.geode.management;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static org.junit.Assert.*;
 
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Properties;
 import java.util.Set;
-import javax.management.MBeanServer;
+
 import javax.management.ObjectName;
 
-import org.apache.geode.LogWriter;
+import org.junit.Rule;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.Region;
@@ -37,39 +39,32 @@ import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.DistributedSystem;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.statistics.SampleCollector;
 import org.apache.geode.management.internal.FederatingManager;
 import org.apache.geode.management.internal.LocalManager;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.ManagementStrings;
 import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.test.dunit.Assert;
 import org.apache.geode.test.dunit.AsyncInvocation;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.Invoke;
+import org.apache.geode.test.dunit.LogWriterUtils;
 import org.apache.geode.test.dunit.SerializableCallable;
 import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.Wait;
 import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
 import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
+import org.apache.geode.test.dunit.rules.DistributedRestoreSystemProperties;
 
 @SuppressWarnings("serial")
-public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
+public abstract class ManagementTestBase extends JUnit4CacheTestCase {
 
   private static final int MAX_WAIT = 70 * 1000;
 
-  /**
-   * log writer instance
-   */
-  private static LogWriter logWriter;
-
-  private static Properties props = new Properties();
-
-  /**
-   * Distributed System
-   */
-  protected static DistributedSystem ds;
+//  protected static DistributedSystem ds;
+  protected static ManagementService managementService;
+//  protected static Cache cache;
 
   /**
    * List containing all the Managed Node VM
@@ -81,23 +76,13 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
    */
   protected static VM managingNode;
 
-  /**
-   * Management Service
-   */
-  protected static ManagementService managementService;
-
   protected static VM managedNode1;
   protected static VM managedNode2;
   protected static VM managedNode3;
   protected static VM locatorVM;
 
-  private static SampleCollector sampleCollector;
-
-  protected static MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-
-  private static int mcastPort;
-
-  protected static Cache cache;
+  @Rule
+  public DistributedRestoreSystemProperties restoreSystemProperties = new DistributedRestoreSystemProperties();
 
   @Override
   public final void postSetUp() throws Exception {
@@ -122,16 +107,14 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
   }
 
   @Override
-  public final void preTearDown() throws Exception {
+  public final void preTearDownCacheTestCase() throws Exception {
     preTearDownManagementTestBase();
 
-    closeAllCache();
-    managementService = null;
-
-    mcastPort = 0;
-    disconnectAllFromDS();
-    props.clear();
+  }
 
+  @Override
+  public final void postTearDownCacheTestCase() throws Exception {
+    managementService = null;
     postTearDownManagementTestBase();
   }
 
@@ -141,99 +124,49 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
   protected void postTearDownManagementTestBase() throws Exception {
   }
 
-  public void closeAllCache() throws Exception {
-    closeCache(managingNode);
-    closeCache(managedNode1);
-    closeCache(managedNode2);
-    closeCache(managedNode3);
-    cache = null;
-  }
-
-  /**
-   * Enable system property gemfire.disableManagement false in each VM.
-   */
-  public void enableManagement() {
-    Invoke.invokeInEveryVM(new SerializableRunnable("Enable Management") {
-      public void run() {
-        System.setProperty(InternalDistributedSystem.DISABLE_MANAGEMENT_PROPERTY, "false");
-      }
-    });
-
-  }
-
-  /**
-   * Disable system property gemfire.disableManagement true in each VM.
-   */
-  public void disableManagement() {
-    Invoke.invokeInEveryVM(new SerializableRunnable("Disable Management") {
-      public void run() {
-        System.setProperty(InternalDistributedSystem.DISABLE_MANAGEMENT_PROPERTY, "true");
-      }
-    });
-
-  }
-
   /**
    * managingNodeFirst variable tests for two different test cases where
    * Managing & Managed Node creation time lines are reversed.
    */
-  public void initManagement(boolean managingNodeFirst) throws Exception {
-
+  protected void initManagement(final boolean managingNodeFirst) throws Exception {
     if (managingNodeFirst) {
       createManagementCache(managingNode);
       startManagingNode(managingNode);
-
       for (VM vm : managedNodeList) {
         createCache(vm);
-
       }
 
     } else {
       for (VM vm : managedNodeList) {
         createCache(vm);
-
       }
       createManagementCache(managingNode);
       startManagingNode(managingNode);
     }
   }
 
-  public void createCache(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Create Cache") {
-      public void run() {
-        createCache(false);
-      }
+  protected void createCache(final VM vm1) throws Exception {
+    vm1.invoke("Create Cache", () -> {
+      createCache(false);
     });
-
   }
 
-  public void createCache(VM vm1, final Properties props) throws Exception {
-    vm1.invoke(new SerializableRunnable("Create Cache") {
-      public void run() {
-        createCache(props);
-      }
+  protected void createCache(final VM vm1, final Properties props) throws Exception {
+    vm1.invoke("Create Cache", () -> {
+      createCache(props);
     });
-
   }
 
-  public Cache createCache(Properties props) {
-    System.setProperty("dunitLogPerTest", "true");
-    props.setProperty(LOG_FILE, getTestMethodName() + "-.log");
-    ds = getSystem(props);
-    cache = CacheFactory.create(ds);
+  private Cache createCache(final Properties props) {
+    Cache cache = getCache(props);
     managementService = ManagementService.getManagementService(cache);
-    logWriter = ds.getLogWriter();
-    assertNotNull(cache);
-    assertNotNull(managementService);
-    return cache;
-  }
 
-  public Cache getCache() {
     return cache;
   }
 
-  public Cache createCache(boolean management) {
-    System.setProperty("dunitLogPerTest", "true");
+  protected Cache createCache(final boolean management) {
+
+    Properties props = new Properties();
     if (management) {
       props.setProperty(JMX_MANAGER, "true");
       props.setProperty(JMX_MANAGER_START, "false");
@@ -243,71 +176,46 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
     props.setProperty(ENABLE_TIME_STATISTICS, "true");
     props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
     props.setProperty(LOG_FILE, getTestMethodName() + "-.log");
-    ds = getSystem(props);
-    cache = CacheFactory.create(ds);
+
+    Cache cache = getCache(props);
     managementService = ManagementService.getManagementService(cache);
-    logWriter = ds.getLogWriter();
-    assertNotNull(cache);
-    assertNotNull(managementService);
+
     return cache;
   }
 
-  public void createManagementCache(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Create Management Cache") {
-      public void run() {
-        createCache(true);
-      }
+  protected void createManagementCache(final VM vm1) throws Exception {
+    vm1.invoke("Create Management Cache", () -> {
+      createCache(true);
     });
   }
 
-  public void closeCache(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Close Cache") {
-      public void run() {
-        GemFireCacheImpl existingInstance = GemFireCacheImpl.getInstance();
-        if (existingInstance != null) {
-          existingInstance.close();
-        }
-        InternalDistributedSystem ds = InternalDistributedSystem
-            .getConnectedInstance();
-        if (ds != null) {
-          ds.disconnect();
-        }
+  protected void closeCache(final VM vm1) throws Exception {
+    vm1.invoke("Close Cache", () -> {
+      GemFireCacheImpl existingInstance = GemFireCacheImpl.getInstance();
+      if (existingInstance != null) {
+        existingInstance.close();
+      }
+      InternalDistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
+      if (ds != null) {
+        ds.disconnect();
       }
     });
-
-  }
-
-  public void closeCache() throws Exception {
-    GemFireCacheImpl existingInstance = GemFireCacheImpl.getInstance();
-    if (existingInstance != null) {
-      existingInstance.close();
-    }
-    InternalDistributedSystem ds = InternalDistributedSystem
-        .getConnectedInstance();
-    if (ds != null) {
-      ds.disconnect();
-    }
   }
 
-  public String getMemberId(final VM vm) {
-    SerializableCallable getMember = new SerializableCallable("getMemberId") {
-      public Object call() throws Exception {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        return cache.getDistributedSystem().getDistributedMember().getId();
-      }
-    };
-    return (String) vm.invoke(getMember);
+  protected String getMemberId(final VM vm) {
+    return vm.invoke("getMemberId", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      return cache.getDistributedSystem().getDistributedMember().getId();
+    });
   }
 
-  protected static void waitForProxy(final ObjectName objectName,
-      final Class interfaceClass) {
-
+  protected static void waitForProxy(final ObjectName objectName, final Class interfaceClass) {
     Wait.waitForCriterion(new WaitCriterion() {
+      @Override
       public String description() {
-        return "Waiting for the proxy of " + objectName.getCanonicalName()
-            + " to get propagated to Manager";
+        return "Waiting for the proxy of " + objectName.getCanonicalName() + " to get propagated to Manager";
       }
-
+      @Override
       public boolean done() {
         SystemManagementService service = (SystemManagementService) managementService;
         if (service.getMBeanProxy(objectName, interfaceClass) != null) {
@@ -316,218 +224,54 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
           return false;
         }
       }
-
     }, MAX_WAIT, 500, true);
   }
 
-  protected void runManagementTaskAdhoc() {
-    SystemManagementService service = (SystemManagementService) managementService;
-    service.getLocalManager().runManagementTaskAdhoc();
-  }
-
   /**
    * Marks a VM as Managing
-   *
-   * @throws Exception
    */
-  public void startManagingNode(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Start Being Managing Node") {
-      public void run() {
-        startBeingManagingNode();
-      }
-    });
-
-  }
-
-  public void startBeingManagingNode() {
-    Cache existingCache = GemFireCacheImpl.getInstance();
-    if (existingCache != null && !existingCache.isClosed()) {
+  protected void startManagingNode(final VM vm1) {
+    vm1.invoke("Start Being Managing Node", () -> {
+      Cache existingCache = GemFireCacheImpl.getInstance();
+      //    if (existingCache != null && !existingCache.isClosed()) {
       managementService = ManagementService.getManagementService(existingCache);
       SystemManagementService service = (SystemManagementService) managementService;
       service.createManager();
       service.startManager();
-    }
-  }
-
-  /**
-   * Marks a VM as Managing
-   *
-   * @throws Exception
-   */
-  public void startManagingNodeAsync(VM vm1) throws Exception {
-    vm1.invokeAsync(new SerializableRunnable("Start Being Managing Node") {
-
-      public void run() {
-        Cache existingCache = GemFireCacheImpl.getInstance();
-        if (existingCache != null && !existingCache.isClosed()) {
-          managementService = ManagementService
-              .getManagementService(existingCache);
-          managementService.startManager();
-        }
-
-      }
+      //    }
     });
-
   }
 
   /**
    * Stops a VM as a Managing node
-   *
-   * @throws Exception
-   */
-  public void stopManagingNode(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Stop Being Managing Node") {
-      public void run() {
-        Cache existingCache = GemFireCacheImpl.getInstance();
-        if (existingCache != null && !existingCache.isClosed()) {
-          if (managementService.isManager()) {
-            managementService.stopManager();
-          }
-
-        }
-
-      }
-    });
-
-  }
-
-  /**
-   * Check various resources clean up Once a VM stops being managable it should
-   * remove all the artifacts of management namely a) Notification region b)
-   * Monitoring Region c) Management task should stop
-   */
-  public void checkManagedNodeCleanup(VM vm) throws Exception {
-    vm.invoke(new SerializableRunnable("Managing Node Clean up") {
-
-      public void run() {
-        Cache existingCache = GemFireCacheImpl.getInstance();
-        if (existingCache != null) {
-          // Cache is closed
-          assertEquals(true, existingCache.isClosed());
-          // ManagementService should throw exception
-          LocalManager localManager = ((SystemManagementService) managementService)
-              .getLocalManager();
-          // Check Monitoring region destroyed
-          Region monitoringRegion = localManager.getManagementResourceRepo()
-              .getLocalMonitoringRegion();
-          assertEquals(null, monitoringRegion);
-          // check Notification region is destroyed
-          Region notifRegion = localManager.getManagementResourceRepo()
-              .getLocalNotificationRegion();
-          assertEquals(null, notifRegion);
-          // check ManagementTask is stopped
-          assertEquals(true, localManager.getFederationSheduler().isShutdown());
-
-        }
-
-      }
-    });
-
-  }
-
-  /**
-   * Check various resources clean up Once a VM stops being Managing.It should
-   * remove all the artifacts of management namely a) proxies b) Monitoring
-   * Region c) Management task should stop
    */
-
-  public void checkProxyCleanup(VM vm) throws Exception {
-
-    vm.invoke(new SerializableRunnable("Managing Node Clean up") {
-
-      public void run() {
-
-        try {
-          GemFireCacheImpl existingCache = GemFireCacheImpl.getInstance();
-          if (existingCache == null) {
-            return;
-          }
-
-          assertEquals(false, existingCache.isClosed());
-          // ManagementService should not be closed
-
-          Set<DistributedMember> otherMemberSet = existingCache
-              .getDistributionManager().getOtherDistributionManagerIds();
-
-          Iterator<DistributedMember> it = otherMemberSet.iterator();
-          FederatingManager federatingManager = ((SystemManagementService) managementService)
-              .getFederatingManager();
-
-          // check Proxy factory. There should not be any proxies left
-          DistributedMember member;
-          while (it.hasNext()) {
-            member = it.next();
-
-            assertNull(federatingManager.getProxyFactory().findAllProxies(
-                member));
-          }
-
-        } catch (ManagementException e) {
-          Assert.fail("failed with ManagementException", e);
+  protected void stopManagingNode(final VM vm1) {
+    vm1.invoke("Stop Being Managing Node", () -> {
+      Cache existingCache = GemFireCacheImpl.getInstance();
+      if (existingCache != null && !existingCache.isClosed()) {
+        if (managementService.isManager()) {
+          managementService.stopManager();
         }
       }
     });
-
-  }
-
-  /**
-   * All the expected exceptions are checked here
-   *
-   * @param e
-   * @return is failed
-   */
-  public boolean checkManagementExceptions(ManagementException e) {
-
-    if (e.getMessage()
-        .equals(ManagementStrings.Management_Service_CLOSED_CACHE)
-        || e.getMessage().equals(
-        ManagementStrings.Management_Service_MANAGEMENT_SERVICE_IS_CLOSED
-            .toLocalizedString())
-        || e
-        .getMessage()
-        .equals(
-            ManagementStrings.Management_Service_MANAGEMENT_SERVICE_NOT_STARTED_YET
-                .toLocalizedString())
-        || e.getMessage().equals(
-        ManagementStrings.Management_Service_NOT_A_GEMFIRE_DOMAIN_MBEAN
-            .toLocalizedString())
-        || e.getMessage().equals(
-        ManagementStrings.Management_Service_NOT_A_MANAGING_NODE_YET
-            .toLocalizedString())
-        || e
-        .getMessage()
-        .equals(
-            ManagementStrings.Management_Service_OPERATION_NOT_ALLOWED_FOR_CLIENT_CACHE
-                .toLocalizedString())
-        || e.getMessage().equals(
-        ManagementStrings.Management_Service_PROXY_NOT_AVAILABLE
-            .toLocalizedString())) {
-
-      return false;
-    }
-    return true;
   }
 
-  public static List<VM> getManagedNodeList() {
+  protected static List<VM> getManagedNodeList() {
     return managedNodeList;
   }
 
-  public static VM getManagingNode() {
+  protected static VM getManagingNode() {
     return managingNode;
   }
 
-  public static ManagementService getManagementService() {
+  protected static ManagementService getManagementService() {
     return managementService;
   }
 
   /**
    * Creates a Distributed region
-   *
-   * @param vm         reference to VM
-   * @param regionName name of the distributed region
    */
-  protected void createDistributedRegion(VM vm, final String regionName)
-      throws Exception {
+  protected void createDistributedRegion(final VM vm, final String regionName) throws InterruptedException {
     AsyncInvocation future = createDistributedRegionAsync(vm, regionName);
     future.join(MAX_WAIT);
     if (future.isAlive()) {
@@ -540,181 +284,99 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
 
   /**
    * Creates a Local region
-   *
-   * @param vm              reference to VM
-   * @param localRegionName name of the local region
    */
-  protected void createLocalRegion(VM vm, final String localRegionName)
-      throws Exception {
-    SerializableRunnable createLocalRegion = new SerializableRunnable(
-        "Create Local region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        RegionFactory rf = cache
-            .createRegionFactory(RegionShortcut.LOCAL);
-
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating Local Region");
-        rf.create(localRegionName);
-
-      }
-    };
-    vm.invoke(createLocalRegion);
+  protected void createLocalRegion(final VM vm, final String localRegionName) throws Exception {
+    vm.invoke("Create Local region", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      SystemManagementService service = (SystemManagementService) getManagementService();
+      RegionFactory rf = cache.createRegionFactory(RegionShortcut.LOCAL);
+
+      LogWriterUtils.getLogWriter().info("Creating Local Region");
+      rf.create(localRegionName);
+    });
   }
 
   /**
    * Creates a Sub region
-   *
-   * @param vm reference to VM
-   */
-  protected void createSubRegion(VM vm, final String parentRegionPath, final String subregionName)
-      throws Exception {
-    SerializableRunnable createSubRegion = new SerializableRunnable(
-        "Create Sub region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        Region region = cache.getRegion(parentRegionPath);
-
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating Sub Region");
-        region.createSubregion(subregionName, region.getAttributes());
-
-      }
-    };
-    vm.invoke(createSubRegion);
-  }
-
-  /**
-   * Puts in distributed region
-   *
-   * @param vm
    */
-  protected void putInDistributedRegion(final VM vm, final String key,
-      final String value, final String regionPath) {
-    SerializableRunnable put = new SerializableRunnable(
-        "Put In Distributed Region") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Region region = cache.getRegion(regionPath);
-        region.put(key, value);
-
-      }
-    };
-    vm.invoke(put);
+  protected void createSubRegion(final VM vm, final String parentRegionPath, final String subregionName) throws Exception {
+    vm.invoke("Create Sub region", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      SystemManagementService service = (SystemManagementService) getManagementService();
+      Region region = cache.getRegion(parentRegionPath);
+
+      LogWriterUtils.getLogWriter().info("Creating Sub Region");
+      region.createSubregion(subregionName, region.getAttributes());
+    });
   }
 
   /**
    * Creates a Distributed Region
-   *
-   * @param vm
    */
-  protected AsyncInvocation createDistributedRegionAsync(final VM vm,
-      final String regionName) {
-    SerializableRunnable createRegion = new SerializableRunnable(
-        "Create Distributed region") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-
-        RegionFactory rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating Dist Region");
-        rf.create(regionName);
-
-      }
-    };
-    return vm.invokeAsync(createRegion);
+  private AsyncInvocation createDistributedRegionAsync(final VM vm, final String regionName) {
+    return vm.invokeAsync("Create Distributed region", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      SystemManagementService service = (SystemManagementService) getManagementService();
+
+      RegionFactory rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
+      LogWriterUtils.getLogWriter().info("Creating Dist Region");
+      rf.create(regionName);
+    });
   }
 
   /**
    * Creates a partition Region
-   *
-   * @param vm
-   */
-  protected void createPartitionRegion(final VM vm,
-      final String partitionRegionName) {
-    SerializableRunnable createParRegion = new SerializableRunnable(
-        "Create Partitioned region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        RegionFactory rf = cache
-            .createRegionFactory(RegionShortcut.PARTITION_REDUNDANT);
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating Par Region");
-        rf.create(partitionRegionName);
-
-      }
-    };
-    vm.invoke(createParRegion);
-  }
-
-  /**
-   * closes a Distributed Region
-   *
-   * @param vm
    */
-  protected void closeRegion(final VM vm, final String regionPath) {
-    SerializableRunnable closeRegion = new SerializableRunnable(
-        "Close Distributed region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Closing Dist Region");
-        Region region = cache.getRegion(regionPath);
-        region.close();
-
-      }
-    };
-    vm.invoke(closeRegion);
+  protected void createPartitionRegion(final VM vm, final String partitionRegionName) {
+    vm.invoke("Create Partitioned region", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      SystemManagementService service = (SystemManagementService) getManagementService();
+      RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION_REDUNDANT);
+      LogWriterUtils.getLogWriter().info("Creating Par Region");
+      rf.create(partitionRegionName);
+    });
   }
 
-  public void waitForAllMembers(final int expectedCount) {
+  protected void waitForAllMembers(final int expectedCount) {
     ManagementService service = getManagementService();
     final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
 
     assertNotNull(service.getDistributedSystemMXBean());
 
     Wait.waitForCriterion(new WaitCriterion() {
+      @Override
       public String description() {
         return "Waiting All members to intimate DistributedSystemMBean";
       }
-
+      @Override
       public boolean done() {
         if (bean.listMemberObjectNames() != null) {
-
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info(
-              "Member Length " + bean.listMemberObjectNames().length);
-
+          LogWriterUtils.getLogWriter().info("Member Length " + bean.listMemberObjectNames().length);
         }
-
         if (bean.listMemberObjectNames().length >= expectedCount) {
           return true;
         } else {
           return false;
         }
-
       }
-
     }, MAX_WAIT, 500, true);
 
     assertNotNull(bean.getManagerObjectName());
   }
 
-  public static void waitForRefresh(final int expectedRefreshCount,
-      final ObjectName objectName) {
+  protected static void waitForRefresh(final int expectedRefreshCount, final ObjectName objectName) {
     final ManagementService service = getManagementService();
 
-    final long currentTime = System.currentTimeMillis();
-
     Wait.waitForCriterion(new WaitCriterion() {
-      int actualRefreshCount = 0;
-      long lastRefreshTime = service.getLastUpdateTime(objectName);
+      private int actualRefreshCount = 0;
+      private long lastRefreshTime = service.getLastUpdateTime(objectName);
 
+      @Override
       public String description() {
         return "Waiting For Proxy Refresh Count = " + expectedRefreshCount;
       }
 
+      @Override
       public boolean done() {
         long newRefreshTime = service.getLastUpdateTime(objectName);
         if (newRefreshTime > lastRefreshTime) {
@@ -727,12 +389,10 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
         }
         return false;
       }
-
     }, MAX_WAIT, 500, true);
-
   }
 
-  public DistributedMember getMember(final VM vm) {
+  protected DistributedMember getMember(final VM vm) {
     SerializableCallable getMember = new SerializableCallable("Get Member") {
       public Object call() {
         GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
@@ -742,4 +402,13 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
     };
     return (DistributedMember) vm.invoke(getMember);
   }
+
+  protected boolean mbeanExists(final ObjectName objectName) {
+    return ManagementFactory.getPlatformMBeanServer().isRegistered(objectName);
+  }
+
+  protected <T> T getMBeanProxy(final ObjectName objectName, Class<T> interfaceClass) {
+    SystemManagementService service = (SystemManagementService)ManagementService.getManagementService(getCache());
+    return service.getMBeanProxy(objectName, interfaceClass);
+  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java b/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java
new file mode 100644
index 0000000..630c95e
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java
@@ -0,0 +1,430 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.management;
+
+import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.assertj.core.api.Assertions.*;
+
+import java.io.Serializable;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import org.junit.rules.MethodRule;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.DistributedSystemDisconnectedException;
+import org.apache.geode.distributed.internal.DM;
+import org.apache.geode.distributed.internal.DistributionManager;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.management.internal.SystemManagementService;
+import org.apache.geode.test.dunit.Invoke;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
+import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
+import org.apache.geode.test.dunit.standalone.DUnitLauncher;
+
+/**
+ * Overriding MethodRule is only way to get {@code Object target}
+ */
+@SuppressWarnings("unused")
+public class ManagementTestRule implements MethodRule, Serializable {
+
+  public static Builder builder() {
+    return new Builder();
+  }
+
+  private final int managersCount;
+  private final int membersCount;
+  private final boolean start;
+  private final boolean managersFirst;
+  private final boolean createManagers;
+  private final boolean createMembers;
+
+  private JUnit4CacheTestCase helper;
+
+  private VM[] managers;
+  private VM[] members;
+
+  protected ManagementTestRule(final Builder builder) {
+    this.helper = new JUnit4CacheTestCase() {
+    };
+    this.managersCount = builder.managersCount;
+    this.membersCount = builder.membersCount;
+    this.start = builder.start;
+    this.managersFirst = builder.managersFirst;
+    this.createManagers = builder.createManagers;
+    this.createMembers = builder.createMembers;
+  }
+
+  public DistributedMember getDistributedMember() {
+    return getCache().getDistributedSystem().getDistributedMember();
+  }
+
+  public DistributedMember getDistributedMember(final VM vm) {
+    return vm.invoke("getDistributedMember", () -> getDistributedMember());
+  }
+
+  public void createManagers() {
+    for (VM manager : this.managers) {
+      manager.invoke(() -> createManager(true));
+    }
+  }
+
+  public void createMembers() {
+    for (VM member : this.members) {
+      member.invoke(() -> createMember());
+    }
+  }
+
+  public void createManager() {
+    createManager(true);
+  }
+
+  public void createManager(final Properties properties) {
+    createManager(properties, true);
+  }
+
+  public void createManager(final boolean start) {
+    createManager(new Properties(), start);
+  }
+
+  public void createManager(final Properties properties, final boolean start) {
+    setPropertyIfNotSet(properties, JMX_MANAGER, "true");
+    setPropertyIfNotSet(properties, JMX_MANAGER_START, "false");
+    setPropertyIfNotSet(properties, JMX_MANAGER_PORT, "0");
+    setPropertyIfNotSet(properties, HTTP_SERVICE_PORT, "0");
+    setPropertyIfNotSet(properties, ENABLE_TIME_STATISTICS, "true");
+    setPropertyIfNotSet(properties, STATISTIC_SAMPLING_ENABLED, "true");
+
+    this.helper.getCache(properties);
+
+    if (start) {
+      startManager();
+    }
+  }
+
+  public void createManager(final VM managerVM) {
+    managerVM.invoke("createManager", () -> createManager());
+  }
+
+  public void createManager(final VM managerVM, final boolean start) {
+    managerVM.invoke("createManager", () -> createManager(start));
+  }
+
+  public void createManager(final VM managerVM, final Properties properties) {
+    managerVM.invoke("createManager", () -> createManager(properties, true));
+  }
+
+  public void createManager(final VM managerVM, final Properties properties, final boolean start) {
+    managerVM.invoke("createManager", () -> createManager(properties, start));
+  }
+
+  public void createMember() {
+    createMember(new Properties());
+  }
+
+  public void createMember(final Properties properties) {
+    setPropertyIfNotSet(properties, JMX_MANAGER, "false");
+    setPropertyIfNotSet(properties, ENABLE_TIME_STATISTICS, "true");
+    setPropertyIfNotSet(properties, STATISTIC_SAMPLING_ENABLED, "true");
+
+    System.out.println("KIRK: creating " + properties.getProperty(NAME));
+    this.helper.getCache(properties);
+  }
+
+  public void createMember(final VM memberVM) {
+    Properties properties = new Properties();
+    properties.setProperty(NAME, "memberVM-" + memberVM.getPid());
+    memberVM.invoke("createMember", () -> createMember(properties));
+  }
+
+  public void createMember(final VM memberVM, final Properties properties) throws Exception {
+    memberVM.invoke("createMember", () -> createMember(properties));
+  }
+
+  public Cache getCache() {
+//    Cache cache = GemFireCacheImpl.getInstance();
+//    if (cache != null && !cache.isClosed()) {
+//      return cache;
+//    }
+    return this.helper.getCache();
+  }
+
+  public boolean hasCache() {
+//    Cache cache = GemFireCacheImpl.getInstance();
+//    if (cache != null && !cache.isClosed()) {
+//      return true;
+//    }
+    return this.helper.hasCache();
+  }
+
+  public Cache basicGetCache() {
+//    Cache cache = GemFireCacheImpl.getInstance();
+//    if (cache != null && !cache.isClosed()) {
+//      return cache;
+//    }
+    return this.helper.basicGetCache();
+  }
+
+  public ManagementService getManagementService() {
+    assertThat(hasCache()).isTrue();
+    return ManagementService.getManagementService(basicGetCache());
+  }
+
+  public SystemManagementService getSystemManagementService() {
+    assertThat(hasCache()).isTrue();
+    return (SystemManagementService) ManagementService.getManagementService(basicGetCache());
+  }
+
+  public ManagementService getExistingManagementService() {
+    assertThat(hasCache()).isTrue();
+    return ManagementService.getExistingManagementService(basicGetCache());
+  }
+
+  public void startManager() {
+    SystemManagementService service = getSystemManagementService();
+    service.createManager();
+    service.startManager();
+  }
+
+  public void startManager(final VM managerVM) {
+    managerVM.invoke("startManager", () -> startManager());
+  }
+
+  public void stopManager() {
+    if (getManagementService().isManager()) {
+      getManagementService().stopManager();
+    }
+  }
+
+  public void stopManager(final VM managerVM) {
+    managerVM.invoke("stopManager", () -> stopManager());
+  }
+
+  public Set<DistributedMember> getOtherNormalMembers() {
+    Set<DistributedMember> allMembers = new HashSet<>(getAllNormalMembers());
+    allMembers.remove(getDistributedMember());
+    return allMembers;
+  }
+
+  public Set<DistributedMember> getAllNormalMembers() {
+    return getDistributionManager().getNormalDistributionManagerIds(); // excludes LOCATOR_DM_TYPE
+  }
+
+  private DM getDistributionManager() {
+    return ((GemFireCacheImpl)getCache()).getDistributionManager();
+  }
+
+  public void disconnectAllFromDS() {
+    stopManagerQuietly();
+    Invoke.invokeInEveryVM("stopManager", () -> stopManagerQuietly());
+    JUnit4DistributedTestCase.disconnectFromDS();
+    Invoke.invokeInEveryVM("disconnectFromDS", () -> JUnit4DistributedTestCase.disconnectFromDS());
+  }
+
+  private void setPropertyIfNotSet(final Properties properties, final String key, final String value) {
+    if (!properties.containsKey(key)) {
+      properties.setProperty(key, value);
+    }
+  }
+
+  private void stopManagerQuietly() {
+    try {
+      if (hasCache() && !basicGetCache().isClosed()) {
+        stopManager();
+      }
+    } catch (DistributedSystemDisconnectedException | NullPointerException ignore) {
+    }
+  }
+
+  @Override
+  public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
+    return new Statement() {
+      @Override
+      public void evaluate() throws Throwable {
+        setUp(target);
+        try {
+          base.evaluate();
+        } finally {
+          tearDown();
+        }
+      }
+    };
+  }
+
+  private void setUp(final Object target) throws Exception {
+    DUnitLauncher.launchIfNeeded();
+    JUnit4DistributedTestCase.disconnectAllFromDS();
+
+    int whichVM = 0;
+
+    this.managers = new VM[this.managersCount];
+    for (int i = 0; i < this.managersCount; i++) {
+      this.managers[i] = getHost(0).getVM(whichVM);
+      whichVM++;
+    }
+
+    this.members = new VM[this.membersCount];
+    for (int i = 0; i < this.membersCount; i++) {
+      this.members[i] = getHost(0).getVM(whichVM);
+      whichVM++;
+    }
+
+    if (this.start) {
+      start();
+    }
+
+    processAnnotations(target);
+  }
+
+  private void start() {
+    if (this.createManagers && this.managersFirst) {
+      createManagers();
+    }
+    if (this.createMembers) {
+      createMembers();
+    }
+    if (this.createManagers && !this.managersFirst) {
+      createManagers();
+    }
+  }
+
+  private void tearDown() throws Exception {
+    JUnit4DistributedTestCase.disconnectAllFromDS();
+  }
+
+  private void processAnnotations(final Object target) {
+    try {
+      Class<?> clazz = target.getClass();
+
+      Field[] fields = clazz.getDeclaredFields();
+      for (Field field : fields) {
+        boolean alreadyAssigned = false;
+        for (Annotation annotation : field.getAnnotations()) {
+          if (annotation.annotationType().equals(Manager.class)) {
+            // annotated with @Manager
+            throwIfAlreadyAssigned(field, alreadyAssigned);
+            assignManagerField(target, field);
+            alreadyAssigned = true;
+          }
+          if (annotation.annotationType().equals(Member.class)) {
+            // annotated with @Manager
+            throwIfAlreadyAssigned(field, alreadyAssigned);
+            assignMemberField(target, field);
+            alreadyAssigned = true;
+          }
+        }
+      }
+    } catch (IllegalAccessException e) {
+      throw new Error(e);
+    }
+  }
+
+  private void throwIfAlreadyAssigned(final Field field, final boolean alreadyAssigned) {
+    if (alreadyAssigned) {
+      throw new IllegalStateException("Field " + field.getName() + " is already annotated with " + field.getAnnotations());
+    }
+  }
+
+  private void assignManagerField(final Object target, final Field field) throws IllegalAccessException {
+    throwIfNotSameType(field, VM.class);
+
+    field.setAccessible(true);
+    if (field.getType().isArray()) {
+      field.set(target, this.managers);
+    } else {
+      field.set(target, this.managers[0]);
+    }
+  }
+
+  private void assignMemberField(final Object target, final Field field) throws IllegalAccessException {
+    throwIfNotSameType(field, VM.class);
+
+    field.setAccessible(true);
+    if (field.getType().isArray()) {
+      field.set(target, this.members);
+    } else {
+      field.set(target, this.members[0]);
+    }
+  }
+
+  private void throwIfNotSameType(final Field field, final Class clazz) {
+    if (!field.getType().equals(clazz) && // non-array
+        !field.getType().getComponentType().equals(clazz)) { // array
+      throw new IllegalArgumentException("Field " + field.getName() + " is not same type as " + clazz.getName());
+    }
+  }
+
+  public static class Builder {
+
+    private boolean start = false;
+
+    private boolean createManagers = true;
+
+    private boolean createMembers = true;
+
+    private int managersCount = 1;
+
+    private int membersCount = 3;
+
+    private boolean managersFirst = true;
+
+    protected Builder() {
+    }
+
+    public Builder createManagers(final boolean value) {
+      this.createManagers = value;
+      return this;
+    }
+
+    public Builder createMembers(final boolean value) {
+      this.createMembers = value;
+      return this;
+    }
+
+    public Builder withManagers(final int count) {
+      this.managersCount = count;
+      return this;
+    }
+
+    public Builder withMembers(final int count) {
+      this.membersCount = count;
+      return this;
+    }
+
+    public Builder managersFirst(final boolean value) {
+      this.managersFirst = value;
+      return this;
+    }
+
+    public Builder start(final boolean value) {
+      this.start = value;
+      return this;
+    }
+
+    public ManagementTestRule build() {
+      return new ManagementTestRule(this);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/Manager.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/Manager.java b/geode-core/src/test/java/org/apache/geode/management/Manager.java
new file mode 100644
index 0000000..0de158e
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/Manager.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.management;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Target(FIELD)
+@Retention(RUNTIME)
+@Documented
+public @interface Manager {
+  String name() default "";
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/Member.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/Member.java b/geode-core/src/test/java/org/apache/geode/management/Member.java
new file mode 100644
index 0000000..e90d278
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/Member.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.geode.management;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Target(FIELD)
+@Retention(RUNTIME)
+@Documented
+public @interface Member {
+  String name() default "";
+}


[8/8] incubator-geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
Convert from ManagementTestCase to ManagementTestRule


Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/86a3fb5a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/86a3fb5a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/86a3fb5a

Branch: refs/heads/feature/GEODE-1930
Commit: 86a3fb5a6f5edd0fe758653413f5fa8b69aeebac
Parents: 1feea53
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Oct 31 13:45:28 2016 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Oct 31 13:45:28 2016 -0700

----------------------------------------------------------------------
 .../RestAPIsAndInterOpsDUnitTest.java           |   43 +-
 geode-core/build.gradle                         |    1 +
 .../org/apache/geode/management/JVMMetrics.java |    3 +-
 .../org/apache/geode/management/OSMetrics.java  |    3 +-
 .../internal/SystemManagementService.java       |    2 +-
 .../DistributedLockServiceDUnitTest.java        |    2 +-
 .../cache/ConnectDisconnectDUnitTest.java       |    2 +-
 ...gionBucketCreationDistributionDUnitTest.java |    2 +-
 .../cache/locks/TXLockServiceDUnitTest.java     |    4 +-
 .../internal/logging/log4j/Configuration.java   |   16 +
 .../management/CacheManagementDUnitTest.java    |  937 ++++-----
 .../management/ClientHealthStatsDUnitTest.java  |  596 +++---
 .../management/CompositeTypeTestDUnitTest.java  |  202 +-
 .../management/DLockManagementDUnitTest.java    |  549 ++----
 .../management/DiskManagementDUnitTest.java     |  821 +++-----
 .../management/DistributedSystemDUnitTest.java  | 1038 ++++------
 .../geode/management/JMXMBeanDUnitTest.java     |    2 +-
 .../management/LocatorManagementDUnitTest.java  |  429 ++--
 .../geode/management/ManagementTestBase.java    |  577 ++----
 .../geode/management/ManagementTestRule.java    |  430 ++++
 .../org/apache/geode/management/Manager.java    |   31 +
 .../org/apache/geode/management/Member.java     |   31 +
 .../management/OffHeapManagementDUnitTest.java  |  723 ++++---
 .../geode/management/QueryDataDUnitTest.java    | 1297 +++++-------
 .../management/RegionManagementDUnitTest.java   | 1856 ++++++++----------
 .../stats/DistributedSystemStatsDUnitTest.java  |  110 +-
 .../QueryDataFunctionApplyLimitClauseTest.java  |   10 +-
 .../internal/pulse/TestClientIdsDUnitTest.java  |   52 +-
 .../pulse/TestSubscriptionsDUnitTest.java       |  291 +--
 .../geode/test/dunit/AsyncInvocation.java       |   59 +-
 .../org/apache/geode/test/dunit/Invoke.java     |    4 +-
 .../java/org/apache/geode/test/dunit/VM.java    |    7 +-
 .../java/org/apache/geode/test/dunit/Wait.java  |    2 +
 .../cache/internal/JUnit4CacheTestCase.java     |    5 +
 .../internal/JUnit4DistributedTestCase.java     |    4 +-
 .../dunit/rules/DistributedDisconnectRule.java  |    4 +-
 .../DistributedRestoreSystemProperties.java     |    4 +-
 .../geode/test/dunit/rules/DistributedRule.java |   68 +
 .../test/dunit/rules/DistributedRunRules.java   |   76 +
 .../test/dunit/rules/DistributedStatement.java  |   76 +
 .../test/dunit/rules/DistributedTestRule.java   |  192 ++
 .../DistributedUseJacksonForJsonPathRule.java   |   51 +
 .../dunit/rules/DistributedWrapperRule.java     |   52 +
 .../geode/test/dunit/rules/RemoteInvoker.java   |   16 +-
 .../apache/geode/test/dunit/rules/WhichVMs.java |   58 +
 .../rules/tests/DistributedTestRuleTest.java    |   54 +
 .../test/dunit/standalone/DUnitLauncher.java    |    9 +-
 geode-junit/build.gradle                        |    1 +
 .../junit/rules/UseJacksonForJsonPathRule.java  |  128 ++
 .../SerializableExternalResource.java           |   22 +
 .../serializable/SerializableStatement.java     |   27 +
 .../management/LuceneManagementDUnitTest.java   |   20 +-
 gradle/dependency-versions.properties           |    3 +-
 53 files changed, 5070 insertions(+), 5932 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java b/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
index 0299615..baefcba 100644
--- a/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
@@ -67,7 +67,6 @@ import org.apache.geode.distributed.DistributedSystem;
 import org.apache.geode.internal.AvailablePort;
 import org.apache.geode.internal.AvailablePortHelper;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.management.ManagementTestBase;
 import org.apache.geode.pdx.PdxInstance;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.NetworkUtils;
@@ -80,28 +79,14 @@ import org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactor
  *
  * @since GemFire 8.0
  */
-
 @Category(DistributedTest.class)
 @RunWith(Parameterized.class)
 @Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class)
+@SuppressWarnings("serial")
 public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
 
-  private static final long serialVersionUID = -254776154266339226L;
-
-  @Parameterized.Parameter
-  public String urlContext;
-
-  @Parameterized.Parameters
-  public static Collection<String> data() {
-    return Arrays.asList("/geode", "/gemfire-api");
-  }
-
-  private ManagementTestBase helper;
-
   public static final String PEOPLE_REGION_NAME = "People";
 
-  //private static RestTemplate restTemplate;
-
   private static final String findAllPeopleQuery = "/queries?id=findAllPeople&q=SELECT%20*%20FROM%20/People";
   private static final String findPeopleByGenderQuery = "/queries?id=filterByGender&q=SELECT%20*%20from%20/People%20where%20gender=$1";
   private static final String findPeopleByLastNameQuery = "/queries?id=filterByLastName&q=SELECT%20*%20from%20/People%20where%20lastName=$1";
@@ -182,20 +167,12 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
       + " \"middleName\": \"kiran12\"," + " \"lastName\": \"Patel\","
       + " \"birthDate\": \"23/08/2012\"," + "\"gender\": \"MALE\"" + "}" + "]";
 
-  public RestAPIsAndInterOpsDUnitTest() {
-    super();
-    this.helper = new ManagementTestBase() {{}};
-
-  }
-
-  @Override
-  public final void preSetUp() throws Exception {
-    disconnectAllFromDS();
-  }
+  @Parameterized.Parameter
+  public String urlContext;
 
-  @Override
-  protected final void postTearDownLocatorTestBase() throws Exception {
-    disconnectAllFromDS();
+  @Parameterized.Parameters
+  public static Collection<String> data() {
+    return Arrays.asList("/geode", "/gemfire-api");
   }
 
   public String startBridgeServerWithRestService(final String hostName, final String[] groups, final String locators, final String[] regions,
@@ -842,14 +819,6 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
 
     //Querying
     doQueryOpsUsingRestApis(restEndpoint);
-
-    // stop the client and make sure the bridge server notifies
-    // stopBridgeMemberVM(client);
-    helper.closeCache(locator);
-    helper.closeCache(manager);
-    helper.closeCache(server);
-    helper.closeCache(client);
-
   }
 
   private void createClientCache(final String host, final int port) throws Exception {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/build.gradle
----------------------------------------------------------------------
diff --git a/geode-core/build.gradle b/geode-core/build.gradle
index b2e5a4e..dae24bc 100755
--- a/geode-core/build.gradle
+++ b/geode-core/build.gradle
@@ -111,6 +111,7 @@ dependencies {
 
   // Test Dependencies
   // External
+  testCompile 'com.jayway.jsonpath:json-path-assert:' + project.'json-path-assert.version'
   testCompile 'org.apache.bcel:bcel:' + project.'bcel.version'
   testRuntime 'org.apache.derby:derby:' + project.'derby.version'
   testCompile 'org.mockito:mockito-core:' + project.'mockito-core.version'

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java b/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java
index b11cfef..992ef99 100644
--- a/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java
+++ b/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java
@@ -17,6 +17,7 @@
 package org.apache.geode.management;
 
 import java.beans.ConstructorProperties;
+import java.io.Serializable;
 
 import org.apache.geode.cache.Region;
 
@@ -28,7 +29,7 @@ import org.apache.geode.cache.Region;
  * @since GemFire 7.0
  *
  */
-public class JVMMetrics {
+public class JVMMetrics implements Serializable {
 
   /**
    * Number of GCs performed

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java b/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java
index 07dab6c..48974ba 100644
--- a/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java
+++ b/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java
@@ -17,6 +17,7 @@
 package org.apache.geode.management;
 
 import java.beans.ConstructorProperties;
+import java.io.Serializable;
 
 /**
  * Composite data type used to distribute metrics for the operating system hosting
@@ -25,7 +26,7 @@ import java.beans.ConstructorProperties;
  * @since GemFire 7.0
  *
  */
-public class OSMetrics {
+public class OSMetrics implements Serializable {
   
   /**
    * Maximum number file descriptor which can be opened

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java b/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
index 29bbb15..65b71d6 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
@@ -357,7 +357,7 @@ public final class SystemManagementService extends BaseManagementService {
   }
 
 
-  public <T> T getMBeanProxy(ObjectName objectName, Class<T> interfaceClass) {
+  public <T> T getMBeanProxy(ObjectName objectName, Class<T> interfaceClass) { // TODO: this is too generic
     if (!isStartedAndOpen()) {
       return null;
     }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java b/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java
index 25d6013..e391aba 100755
--- a/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java
@@ -100,7 +100,7 @@ public class DistributedLockServiceDUnitTest extends JUnit4DistributedTestCase {
   @Override
   public final void preTearDown() throws Exception {
     Invoke.invokeInEveryVM(() -> destroyAllDLockServices());
-//    invokeInEveryVM(DistributedLockServiceDUnitTest.class,
+//    invokeInEveryVMAndController(DistributedLockServiceDUnitTest.class,
 //                    "remoteDumpAllDLockServices"); 
                     
     //InternalDistributedLockService.destroyAll();

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java
index 9b6030a..162c3a5 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java
@@ -42,7 +42,7 @@ public class ConnectDisconnectDUnitTest extends JUnit4CacheTestCase {
   // see bugs #50785 and #46438
   @Test
   public void testManyConnectsAndDisconnects() throws Throwable {
-//    invokeInEveryVM(new SerializableRunnable() {
+//    invokeInEveryVMAndController(new SerializableRunnable() {
 //
 //      @Override
 //      public void run() {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java
index 91bafea..07546a0 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java
@@ -462,7 +462,7 @@ public class PartitionedRegionBucketCreationDistributionDUnitTest extends Partit
     
 //    final int bucketPerHost = (int) Math.ceil(((double) maxBuckets / Host.getHostCount()));
 
-//    invokeInEveryVM(new SerializableRunnable("") {
+//    invokeInEveryVMAndController(new SerializableRunnable("") {
 //      
 //    }
     

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java
index b835cbc..3b54cc6 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java
@@ -98,7 +98,7 @@ public class TXLockServiceDUnitTest extends JUnit4DistributedTestCase {
 
   @Override
   public final void preTearDown() throws Exception {
-//    invokeInEveryVM(TXLockServiceDUnitTest.class,
+//    invokeInEveryVMAndController(TXLockServiceDUnitTest.class,
 //                    "remoteDumpAllDLockServices");
                     
     Invoke.invokeInEveryVM(TXLockServiceDUnitTest.class,
@@ -123,7 +123,7 @@ public class TXLockServiceDUnitTest extends JUnit4DistributedTestCase {
   @Test
   public void testGetAndDestroy() {
     forEachVMInvoke("checkGetAndDestroy", new Object[] {});
-    /*invokeInEveryVM(TXLockServiceDUnitTest.class,
+    /*invokeInEveryVMAndController(TXLockServiceDUnitTest.class,
                     "destroyServices"); 
     forEachVMInvoke("checkGetAndDestroy", new Object[] {});*/
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/internal/logging/log4j/Configuration.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/logging/log4j/Configuration.java b/geode-core/src/test/java/org/apache/geode/internal/logging/log4j/Configuration.java
index 8f7ca1a..d55b768 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/logging/log4j/Configuration.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/logging/log4j/Configuration.java
@@ -1,3 +1,19 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package org.apache.geode.internal.logging.log4j;
 
 import static org.assertj.core.api.Assertions.assertThat;

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java
index 8c57aab..0e750e9 100644
--- a/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java
@@ -16,11 +16,14 @@
  */
 package org.apache.geode.management;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static com.jayway.awaitility.Awaitility.*;
+import static java.util.concurrent.TimeUnit.*;
+import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.assertj.core.api.Assertions.*;
 import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
 
+import java.io.Serializable;
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -28,13 +31,16 @@ import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import javax.management.InstanceNotFoundException;
+
 import javax.management.JMException;
 import javax.management.Notification;
 import javax.management.NotificationListener;
 import javax.management.ObjectName;
 
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -45,54 +51,69 @@ import org.apache.geode.cache.RegionShortcut;
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.internal.DistributionConfig;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.management.internal.LocalManager;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.ManagementConstants;
 import org.apache.geode.management.internal.NotificationHub.NotificationHubListener;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.test.dunit.AsyncInvocation;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableRunnable;
+import org.apache.geode.test.dunit.Invoke;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
 
 /**
  * This class checks and verifies various data and operations exposed through
  * MemberMXBean interface.
  * <p>
- * Goal of the Test : MemberMBean gets created once cache is created. Data like
+ * <p>Goal of the Test : MemberMBean gets created once cache is created. Data like
  * config data and stats are of proper value To check proper federation of
  * MemberMBean including remote ops and remote data access
+ * <p>
+ * <p>This test is a mess and needs to be rewritten.
  */
 @Category(DistributedTest.class)
-public class CacheManagementDUnitTest extends ManagementTestBase {
+@SuppressWarnings({ "serial", "unused" })
+public class CacheManagementDUnitTest implements Serializable {
+
+  /** used in memberVMs */
+  private static final String NOTIFICATION_REGION_NAME = "NotifTestRegion_";
+
+  /** used in managerVM */
+  private static final List<Notification> notifications = new ArrayList<>();
+
+  @Manager
+  private VM managerVM;
+
+  @Member
+  private VM[] memberVMs;
 
-  private final String VERIFY_CONFIG_METHOD = "verifyConfigData";
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-  private final String VERIFY_REMOTE_CONFIG_METHOD = "verifyConfigDataRemote";
+  @Rule
+  public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
 
-  static final List<Notification> notifList = new ArrayList<Notification>();
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
 
-  // This must be bigger than the dunit ack-wait-threshold for the revoke
-  // tests. The command line is setting the ack-wait-threshold to be
-  // 60 seconds.
-  private static final int MAX_WAIT = 70 * 1000;
+  @Before
+  public void before() throws Exception {
+    this.managerVM.invoke(() -> notifications.clear());
+  }
 
   @Test
   public void testGemFireConfigData() throws Exception {
-    initManagement(false);
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
 
-    Map<DistributedMember, DistributionConfig> configMap = new HashMap<DistributedMember, DistributionConfig>();
-    for (VM vm : getManagedNodeList()) {
-      Map<DistributedMember, DistributionConfig> configMapMember = (Map<DistributedMember, DistributionConfig>) vm.invoke(CacheManagementDUnitTest.class, VERIFY_CONFIG_METHOD);
+    Map<DistributedMember, DistributionConfig> configMap = new HashMap<>();
+    for (VM memberVM : this.memberVMs) {
+      Map<DistributedMember, DistributionConfig> configMapMember = memberVM.invoke(() -> verifyConfigData());
       configMap.putAll(configMapMember);
     }
 
-    Object[] args = new Object[1];
-    args[0] = configMap;
-    getManagingNode().invoke(CacheManagementDUnitTest.class, VERIFY_REMOTE_CONFIG_METHOD, args);
+    this.managerVM.invoke(() -> verifyConfigDataRemote(configMap));
   }
 
   /**
@@ -100,29 +121,34 @@ public class CacheManagementDUnitTest extends ManagementTestBase {
    */
   @Test
   public void testMemberMBeanOperations() throws Exception {
-    initManagement(false);
+    int i = 1;
+    for (VM memberVM : this.memberVMs) {
+      Properties props = new Properties();
+      props.setProperty(LOG_FILE, this.temporaryFolder.newFile(this.testName.getMethodName() + "-VM" + i + ".log").getAbsolutePath());
+      this.managementTestRule.createMember(memberVM, props);
+      i++;
+    }
 
-    for (VM vm : managedNodeList) {
+    this.managementTestRule.createManagers();
 
-      //Do some operations to fill the logs
+    for (VM memberVM : this.memberVMs) {
+      String logMessage = "This line should be in the log";
+      memberVM.invoke(() -> this.managementTestRule.getCache().getLogger().info(logMessage));
 
-      createLocalRegion(vm, "testRegion");
+      String log = memberVM.invoke(() -> fetchLog(30));
+      assertThat(log).isNotNull();
+      assertThat(log).contains(logMessage);
 
-      String log = (String) vm.invoke(() -> CacheManagementDUnitTest.fetchLog());
-      assertNotNull(log);
-      LogWriterUtils.getLogWriter().info("<ExpectedString> Log Of Member is " + log.toString() + "</ExpectedString> ");
+      JVMMetrics jvmMetrics = memberVM.invoke(() -> fetchJVMMetrics());
 
-      vm.invoke(() -> CacheManagementDUnitTest.fetchJVMMetrics());
+      OSMetrics osMetrics = memberVM.invoke(() -> fetchOSMetrics());
 
-      vm.invoke(() -> CacheManagementDUnitTest.fetchOSMetrics());
+      // TODO: need assertions
 
-      vm.invoke(() -> CacheManagementDUnitTest.shutDownMember());
+      memberVM.invoke(() -> shutDownMember());
     }
 
-    VM managingNode = getManagingNode();
-    Object[] args = new Object[1];
-    args[0] = 1;// Only locator member wont be shutdown
-    managingNode.invoke(CacheManagementDUnitTest.class, "assertExpectedMembers", args);
+    this.managerVM.invoke(() -> verifyExpectedMembers(0));
   }
 
   /**
@@ -130,263 +156,254 @@ public class CacheManagementDUnitTest extends ManagementTestBase {
    */
   @Test
   public void testMemberMBeanOpsRemote() throws Exception {
-    initManagement(false);
-    getManagingNode().invoke(() -> CacheManagementDUnitTest.invokeRemoteOps());
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
+    this.managerVM.invoke(() -> invokeRemoteMemberMXBeanOps());
   }
 
   /**
-   * Creates and starts a manager.
+   * Creates and starts a managerVM.
    * Multiple Managers
    */
   @Test
   public void testManager() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
 
-    createCache(node1);
-    createCache(node2);
-    createManagementCache(node3);
+    this.managementTestRule.createManager(this.memberVMs[2], false);
 
-    // Only creates a cache in Managing Node
-    // Does not start the manager
-    createManagementCache(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
 
-    node3.invoke(() -> CacheManagementDUnitTest.startManager());
+    this.memberVMs[2].invoke(() -> startManager());
 
-    // Now start Managing node manager. System will have two Managers now which
+    // Now start Managing node managerVM. System will have two Managers now which
     // should be OK
-    DistributedMember member = getMember(node3);
-    startManagingNode(managingNode);
-    checkManagerView(managingNode, member);
-    stopManagingNode(managingNode);
+    DistributedMember member = this.managementTestRule.getDistributedMember(this.memberVMs[2]);
+    this.managementTestRule.startManager(this.managerVM);
+
+    verifyManagerStarted(this.managerVM, member);
+    this.managementTestRule.stopManager(this.managerVM);
   }
 
   /**
-   * Creates and starts a manager.
+   * Creates and starts a managerVM.
    * Multiple Managers
    */
   @Test
   public void testManagerShutdown() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-    // Only creates a cache in Managing Node
-    // Does not start the manager
-    createManagementCache(managingNode);
+    verifyManagerStarted(this.managerVM, this.managementTestRule.getDistributedMember(this.memberVMs[0]));
 
-    startManagingNode(managingNode);
-    DistributedMember member = getMember(managingNode);
-    checkManagerView(managingNode, member);
-    stopManagingNode(managingNode);
-    checkNonManagerView(managingNode);
+    this.managementTestRule.stopManager(this.managerVM);
+    verifyManagerStopped(this.managerVM, this.memberVMs.length);
   }
 
   @Test
-  public void testServiceCloseManagedNode() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+  public void closeCacheShouldStopLocalManager() throws Exception {
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
 
-    createCache(node1);
-    createCache(node2);
-    createManagementCache(node3);
+    this.managementTestRule.createManager(this.memberVMs[2], false);
 
     // Only creates a cache in Managing Node
-    // Does not start the manager
-    createManagementCache(managingNode);
-
-    node3.invoke(() -> CacheManagementDUnitTest.startManager());
-
-    closeCache(node3);
-    validateServiceResource(node3);
+    // Does not start the managerVM
+    this.managementTestRule.createManager(this.managerVM, false);
+
+    this.memberVMs[2].invoke(() -> startManager());
+
+    this.memberVMs[2].invoke(() -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+      LocalManager localManager = service.getLocalManager();
+      this.managementTestRule.getCache().close();
+      assertThat(localManager.isRunning()).isFalse();
+      assertThat(service.isManager()).isFalse();
+      assertThat(service.getLocalManager()).isNull();
+    });
   }
 
   @Test
   public void testGetMBean() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
+    this.managementTestRule.createManager(this.managerVM, false);
 
-    createManagementCache(managingNode);
+    this.managementTestRule.startManager(this.managerVM);
 
-    startManagingNode(managingNode);
-
-    checkGetMBean(managingNode);
+    verifyGetMBeanInstance(this.managerVM);
   }
 
   @Test
   public void testQueryMBeans() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
-
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-    createManagementCache(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
 
-    startManagingNode(managingNode);
+    this.managementTestRule.startManager(this.managerVM);
 
-    checkQueryMBeans(managingNode);
+    verifyQueryMBeans(this.managerVM);
   }
 
-  protected void checkQueryMBeans(final VM vm) {
-    SerializableRunnable validateServiceResource = new SerializableRunnable("Check Query MBeans") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-        Set<DistributedMember> otherMembers = cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-        Set<ObjectName> superSet = new HashSet<ObjectName>();
+  @Test
+  public void testNotification() throws Exception {
+    // Step : 1 : Create Managed Node Caches
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-        for (DistributedMember member : otherMembers) {
+    // Step : 2 : Create Managing Node Cache, start managerVM, add a notification
+    // handler to DistributedSystemMXBean
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
+    attachListenerToDistributedSystemMXBean(this.managerVM);
 
-          ObjectName memberMBeanName = managementService.getMemberMBeanName(member);
+    // Step : 3 : Verify Notification count, notification region sizes
+    verifyNotificationsAndRegionSize(this.memberVMs[0], this.memberVMs[1], this.memberVMs[2], this.managerVM);
+  }
 
-          waitForProxy(memberMBeanName, MemberMXBean.class);
-          Set<ObjectName> names = managementService.queryMBeanNames(member);
-          superSet.addAll(names);
-          assertTrue(names.contains(memberMBeanName));
+  @Test
+  public void testNotificationManagingNodeFirst() throws Exception {
+    // Step : 1 : Create Managing Node Cache, start managerVM, add a notification
+    // handler to DistributedSystemMXBean
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-        }
+    attachListenerToDistributedSystemMXBean(this.managerVM);
 
-        Set<ObjectName> names = managementService.queryMBeanNames(cache.getDistributedSystem().getDistributedMember());
-        assertTrue(!superSet.contains(names));
-      }
-    };
-    vm.invoke(validateServiceResource);
+    // Step : 2 : Create Managed Node Caches
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
+    // Step : 3 : Verify Notification count, notification region sizes
+    verifyNotificationsAndRegionSize(this.memberVMs[0], this.memberVMs[1], this.memberVMs[2], this.managerVM);
   }
 
-  protected void checkGetMBean(final VM vm) {
-    SerializableRunnable validateServiceResource = new SerializableRunnable("Check Get MBean") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMembers = cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+  @Test
+  public void testRedundancyZone() throws Exception {
+    String redundancyZone = "ARMY_ZONE";
+
+    Properties props = new Properties();
+    props.setProperty(REDUNDANCY_ZONE, redundancyZone);
 
-        for (DistributedMember member : otherMembers) {
+    this.managementTestRule.createMember(this.memberVMs[0], props);
 
-          ObjectName memberMBeanName = managementService.getMemberMBeanName(member);
+    this.memberVMs[0].invoke("verifyRedundancyZone", () -> {
+      ManagementService service = this.managementTestRule.getExistingManagementService();
+      MemberMXBean memberMXBean = service.getMemberMXBean();
+      assertThat(memberMXBean.getRedundancyZone()).isEqualTo(redundancyZone);
+    });
+  }
 
-          waitForProxy(memberMBeanName, MemberMXBean.class);
+  private void verifyQueryMBeans(final VM vm) {
+    vm.invoke("validateQueryMBeans", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+      Set<ObjectName> superSet = new HashSet<>();
 
-          MemberMXBean bean = managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
-          assertNotNull(bean);
-        }
+      for (DistributedMember member : otherMembers) {
+        ObjectName memberMBeanName = service.getMemberMBeanName(member);
 
-        DistributedMember thisMember = cache.getDistributedSystem().getDistributedMember();
-        ObjectName memberMBeanName = managementService.getMemberMBeanName(thisMember);
-        MemberMXBean bean = managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
-        assertNotNull(bean);
+        awaitMemberMXBeanProxy(member);
 
+        Set<ObjectName> objectNames = service.queryMBeanNames(member);
+        superSet.addAll(objectNames);
+        assertThat(objectNames.contains(memberMBeanName)).isTrue();
       }
-    };
-    vm.invoke(validateServiceResource);
+
+      Set<ObjectName> names = service.queryMBeanNames(this.managementTestRule.getDistributedMember());
+      ObjectName[] arrayOfNames = names.toArray(new ObjectName[names.size()]);
+
+      assertThat(superSet).doesNotContain(arrayOfNames); // TODO: what value does this method have?
+    });
   }
 
-  protected void validateServiceResource(final VM vm) {
-    SerializableRunnable validateServiceResource = new SerializableRunnable("Valideate Management Service Resource") {
-      public void run() {
+  private void verifyGetMBeanInstance(final VM vm) {
+    vm.invoke("verifyGetMBeanInstance", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+
+      for (DistributedMember member : otherMembers) {
+        ObjectName memberMBeanName = service.getMemberMBeanName(member);
 
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        assertNull(cache);
-        assertFalse(managementService.isManager());
+        awaitMemberMXBeanProxy(member);
 
-        SystemManagementService service = (SystemManagementService) managementService;
-        assertNull(service.getLocalManager());
+        MemberMXBean memberMXBean = service.getMBeanInstance(memberMBeanName, MemberMXBean.class);
+        assertThat(memberMXBean).isNotNull();
       }
-    };
-    vm.invoke(validateServiceResource);
+
+      DistributedMember distributedMember = this.managementTestRule.getDistributedMember();
+      ObjectName memberMBeanName = service.getMemberMBeanName(distributedMember);
+      MemberMXBean memberMXBean = service.getMBeanInstance(memberMBeanName, MemberMXBean.class);
+      assertThat(memberMXBean).isNotNull();
+    });
   }
 
-  /**
-   * Creates a Distributed Region
-   */
-  protected AsyncInvocation checkManagerView(final VM vm, final DistributedMember oneManager) {
-    SerializableRunnable createRegion = new SerializableRunnable("Check Manager View") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        ObjectName memberMBeanName = service.getMemberMBeanName(oneManager);
-        MemberMXBean bean = service.getMBeanProxy(memberMBeanName, MemberMXBean.class);
-        assertNotNull(bean);
-        //Ensure Data getting federated from Managing node
-        long t1 = bean.getMemberUpTime();
-        try {
-          this.wait(ManagementConstants.REFRESH_TIME * 3);
-        } catch (InterruptedException e) {
-          fail("interrupted");
-        }
-        long t2 = bean.getMemberUpTime();
+  private void verifyManagerStarted(final VM managerVM, final DistributedMember otherMember) {
+    managerVM.invoke("verifyManagerStarted", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+      assertThat(service.isManager()).isTrue();
 
-        assertTrue(t2 > t1);
+      assertThat(service.getLocalManager().isRunning()).isTrue();
 
-      }
-    };
-    return vm.invokeAsync(createRegion);
+      assertThat(service.getLocalManager().getFederationSheduler().isShutdown()).isFalse();
+
+      ObjectName memberMBeanName = service.getMemberMBeanName(otherMember);
+
+      await().until(() -> assertThat(service.getMBeanProxy(memberMBeanName, MemberMXBean.class)).isNotNull());
+      MemberMXBean memberMXBean = service.getMBeanProxy(memberMBeanName, MemberMXBean.class);
+
+      //Ensure Data getting federated from Managing node
+      long start = memberMXBean.getMemberUpTime();
+      await().until(() -> assertThat(memberMXBean.getMemberUpTime()).isGreaterThan(start));
+    });
   }
 
   /**
    * Add any Manager clean up asserts here
    */
-  protected void checkNonManagerView(final VM vm) {
-    SerializableRunnable checkNonManagerView = new SerializableRunnable("Check Non Manager View") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        assertNotNull(cache);
-        assertFalse(managementService.isManager());
-
-        SystemManagementService service = (SystemManagementService) managementService;
-        assertTrue(service.getLocalManager().isRunning());
-        assertFalse(service.getLocalManager().getFederationSheduler().isShutdown());
-
-        // Check for Proxies
-        Set<DistributedMember> otherMembers = cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-        assertTrue(otherMembers.size() > 0);
-        for (DistributedMember member : otherMembers) {
-          Set<ObjectName> proxyNames = service.getFederatingManager().getProxyFactory().findAllProxies(member);
-          assertTrue(proxyNames.isEmpty());
-          ObjectName proxyMBeanName = service.getMemberMBeanName(member);
-          assertFalse(MBeanJMXAdapter.mbeanServer.isRegistered(proxyMBeanName));
-        }
+  private void verifyManagerStopped(final VM managerVM, final int otherMembersCount) {
+    managerVM.invoke("verifyManagerStopped", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+
+      assertThat(service.isManager()).isFalse();
+      assertThat(service.getLocalManager().isRunning()).isTrue();
+      assertThat(service.getLocalManager().getFederationSheduler().isShutdown()).isFalse();
 
+      // Check for Proxies
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+      assertThat(otherMembers).hasSize(otherMembersCount);
+
+      for (DistributedMember member : otherMembers) {
+        Set<ObjectName> proxyNames = service.getFederatingManager().getProxyFactory().findAllProxies(member);
+        assertThat(proxyNames).isEmpty();
+
+        ObjectName proxyMBeanName = service.getMemberMBeanName(member);
+        assertThat(MBeanJMXAdapter.mbeanServer.isRegistered(proxyMBeanName)).isFalse();
       }
-    };
-    vm.invoke(checkNonManagerView);
+    });
   }
 
-  public static Map<DistributedMember, DistributionConfig> verifyConfigData() {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    ManagementService service = getManagementService();
-    DistributionConfig config = ((InternalDistributedSystem) cache.getDistributedSystem()).getConfig();
+  private Map<DistributedMember, DistributionConfig> verifyConfigData() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    InternalDistributedSystem ids = (InternalDistributedSystem) this.managementTestRule.getCache().getDistributedSystem();
+    DistributionConfig config = ids.getConfig();
+
     MemberMXBean bean = service.getMemberMXBean();
     GemFireProperties data = bean.listGemFireProperties();
-    assertConfigEquals(config, data);
-    Map<DistributedMember, DistributionConfig> configMap = new HashMap<DistributedMember, DistributionConfig>();
-    configMap.put(cache.getMyId(), config);
+    verifyGemFirePropertiesData(config, data);
+
+    Map<DistributedMember, DistributionConfig> configMap = new HashMap<>();
+    configMap.put(ids.getDistributedMember(), config);
     return configMap;
   }
 
@@ -394,15 +411,15 @@ public class CacheManagementDUnitTest extends ManagementTestBase {
    * This is to check whether the config data has been propagated to the
    * Managing node properly or not.
    */
-  public static void verifyConfigDataRemote(Map<DistributedMember, DistributionConfig> configMap) throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    Set<DistributedMember> otherMemberSet = cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+  private void verifyConfigDataRemote(final Map<DistributedMember, DistributionConfig> configMap) throws Exception {
+    Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+
+    for (DistributedMember member : otherMembers) {
+      MemberMXBean memberMXBean = awaitMemberMXBeanProxy(member);
 
-    for (DistributedMember member : otherMemberSet) {
-      MemberMXBean bean = MBeanUtil.getMemberMbeanProxy(member);
-      GemFireProperties data = bean.listGemFireProperties();
+      GemFireProperties data = memberMXBean.listGemFireProperties();
       DistributionConfig config = configMap.get(member);
-      assertConfigEquals(config, data);
+      verifyGemFirePropertiesData(config, data);
     }
   }
 
@@ -410,358 +427,238 @@ public class CacheManagementDUnitTest extends ManagementTestBase {
    * Asserts that distribution config and gemfireProperty composite types hold
    * the same values
    */
-  public static void assertConfigEquals(DistributionConfig config, GemFireProperties data) {
+  private void verifyGemFirePropertiesData(final DistributionConfig config, final GemFireProperties data) {
+    assertThat(data.getMemberName()).isEqualTo(config.getName());
 
-    assertEquals(data.getMemberName(), config.getName());
     // **TODO **
     String memberGroups = null;
 
-    assertEquals(data.getMcastPort(), config.getMcastPort());
-    assertEquals(data.getMcastAddress(), config.getMcastAddress().getHostAddress());
-    assertEquals(data.getBindAddress(), config.getBindAddress());
-    assertEquals(data.getTcpPort(), config.getTcpPort());
-    assertEquals(removeVMDir(data.getCacheXMLFile()), removeVMDir(config.getCacheXmlFile().getAbsolutePath()));
+    assertThat(data.getMcastPort()).isEqualTo(config.getMcastPort());
+    assertThat(data.getMcastAddress()).isEqualTo(config.getMcastAddress().getHostAddress());
+    assertThat(data.getBindAddress()).isEqualTo(config.getBindAddress());
+    assertThat(data.getTcpPort()).isEqualTo(config.getTcpPort());
+    assertThat(removeVMDir(data.getCacheXMLFile())).isEqualTo(removeVMDir(config.getCacheXmlFile().getAbsolutePath()));
+
     // **TODO **
-    assertEquals(data.getMcastTTL(), config.getMcastTtl());
-    assertEquals(data.getServerBindAddress(), config.getServerBindAddress());
-    assertEquals(data.getLocators(), config.getLocators());
+    assertThat(data.getMcastTTL()).isEqualTo(config.getMcastTtl());
+    assertThat(data.getServerBindAddress()).isEqualTo(config.getServerBindAddress());
+    assertThat(data.getLocators()).isEqualTo(config.getLocators());
+
     //The start locator may contain a directory
-    assertEquals(removeVMDir(data.getStartLocator()), removeVMDir(config.getStartLocator()));
-    assertEquals(removeVMDir(data.getLogFile()), removeVMDir(config.getLogFile().getAbsolutePath()));
-    assertEquals(data.getLogLevel(), config.getLogLevel());
-    assertEquals(data.isStatisticSamplingEnabled(), config.getStatisticSamplingEnabled());
-    assertEquals(removeVMDir(data.getStatisticArchiveFile()), removeVMDir(config.getStatisticArchiveFile().getAbsolutePath()));
+    assertThat(removeVMDir(data.getStartLocator())).isEqualTo(removeVMDir(config.getStartLocator()));
+    assertThat(removeVMDir(data.getLogFile())).isEqualTo(removeVMDir(config.getLogFile().getAbsolutePath()));
+    assertThat(data.getLogLevel()).isEqualTo(config.getLogLevel());
+    assertThat(data.isStatisticSamplingEnabled()).isEqualTo(config.getStatisticSamplingEnabled());
+    assertThat(removeVMDir(data.getStatisticArchiveFile())).isEqualTo(removeVMDir(config.getStatisticArchiveFile().getAbsolutePath()));
+
     // ** TODO **
     String includeFile = null;
-    assertEquals(data.getAckWaitThreshold(), config.getAckWaitThreshold());
-    assertEquals(data.getAckSevereAlertThreshold(), config.getAckSevereAlertThreshold());
-    assertEquals(data.getArchiveFileSizeLimit(), config.getArchiveFileSizeLimit());
-    assertEquals(data.getArchiveDiskSpaceLimit(), config.getArchiveDiskSpaceLimit());
-    assertEquals(data.getLogFileSizeLimit(), config.getLogFileSizeLimit());
-    assertEquals(data.getLogDiskSpaceLimit(), config.getLogDiskSpaceLimit());
-    assertEquals(data.isClusterSSLEnabled(), config.getClusterSSLEnabled());
-
-    assertEquals(data.getClusterSSLCiphers(), config.getClusterSSLCiphers());
-    assertEquals(data.getClusterSSLProtocols(), config.getClusterSSLProtocols());
-    assertEquals(data.isClusterSSLRequireAuthentication(), config.getClusterSSLRequireAuthentication());
-    assertEquals(data.getSocketLeaseTime(), config.getSocketLeaseTime());
-    assertEquals(data.getSocketBufferSize(), config.getSocketBufferSize());
-    assertEquals(data.getMcastSendBufferSize(), config.getMcastSendBufferSize());
-    assertEquals(data.getMcastRecvBufferSize(), config.getMcastRecvBufferSize());
-    assertEquals(data.getMcastByteAllowance(), config.getMcastFlowControl().getByteAllowance());
-    assertEquals(data.getMcastRechargeThreshold(), config.getMcastFlowControl().getRechargeThreshold(), 0);
-    assertEquals(data.getMcastRechargeBlockMs(), config.getMcastFlowControl().getRechargeBlockMs());
-    assertEquals(data.getUdpFragmentSize(), config.getUdpFragmentSize());
-    assertEquals(data.getUdpSendBufferSize(), config.getUdpSendBufferSize());
-    assertEquals(data.getUdpRecvBufferSize(), config.getUdpRecvBufferSize());
-    assertEquals(data.isDisableTcp(), config.getDisableTcp());
-    assertEquals(data.isEnableTimeStatistics(), config.getEnableTimeStatistics());
-    assertEquals(data.isEnableNetworkPartitionDetection(), config.getEnableNetworkPartitionDetection());
-    assertEquals(data.getMemberTimeout(), config.getMemberTimeout());
-
-    int[] configPortRange = config.getMembershipPortRange();
-    int[] dataPortRange = data.getMembershipPortRange();
-
-    assertEquals(dataPortRange.length, configPortRange.length);
-    for (int i = 0; i < dataPortRange.length; i++) {
-      assertEquals(dataPortRange[i], configPortRange[i]);
-    }
-    assertEquals(data.isConserveSockets(), config.getConserveSockets());
-    assertEquals(data.getRoles(), config.getRoles());
-    assertEquals(data.getMaxWaitTimeForReconnect(), config.getMaxWaitTimeForReconnect());
-    assertEquals(data.getMaxNumReconnectTries(), config.getMaxNumReconnectTries());
-    assertEquals(data.getAsyncDistributionTimeout(), config.getAsyncDistributionTimeout());
-    assertEquals(data.getAsyncQueueTimeout(), config.getAsyncQueueTimeout());
-    assertEquals(data.getAsyncMaxQueueSize(), config.getAsyncMaxQueueSize());
-    assertEquals(data.getClientConflation(), config.getClientConflation());
-    assertEquals(data.getDurableClientId(), config.getDurableClientId());
-    assertEquals(data.getDurableClientTimeout(), config.getDurableClientTimeout());
-    assertEquals(data.getSecurityClientAuthInit(), config.getSecurityClientAuthInit());
-    assertEquals(data.getSecurityClientAuthenticator(), config.getSecurityClientAuthenticator());
-    assertEquals(data.getSecurityClientDHAlgo(), config.getSecurityClientDHAlgo());
-    assertEquals(data.getSecurityPeerAuthInit(), config.getSecurityPeerAuthInit());
-    assertEquals(data.getSecurityClientAuthenticator(), config.getSecurityPeerAuthenticator());
-    assertEquals(data.getSecurityClientAccessor(), config.getSecurityClientAccessor());
-    assertEquals(data.getSecurityClientAccessorPP(), config.getSecurityClientAccessorPP());
-    assertEquals(data.getSecurityLogLevel(), config.getSecurityLogLevel());
-    assertEquals(removeVMDir(data.getSecurityLogFile()), removeVMDir(config.getSecurityLogFile().getAbsolutePath()));
-    assertEquals(data.getSecurityPeerMembershipTimeout(), config.getSecurityPeerMembershipTimeout());
-    assertEquals(data.isRemoveUnresponsiveClient(), config.getRemoveUnresponsiveClient());
-    assertEquals(data.isDeltaPropagation(), config.getDeltaPropagation());
-    assertEquals(data.getRedundancyZone(), config.getRedundancyZone());
-    assertEquals(data.isEnforceUniqueHost(), config.getEnforceUniqueHost());
-    assertEquals(data.getStatisticSampleRate(), config.getStatisticSampleRate());
+    assertThat(data.getAckWaitThreshold()).isEqualTo(config.getAckWaitThreshold());
+    assertThat(data.getAckSevereAlertThreshold()).isEqualTo(config.getAckSevereAlertThreshold());
+    assertThat(data.getArchiveFileSizeLimit()).isEqualTo(config.getArchiveFileSizeLimit());
+    assertThat(data.getArchiveDiskSpaceLimit()).isEqualTo(config.getArchiveDiskSpaceLimit());
+    assertThat(data.getLogFileSizeLimit()).isEqualTo(config.getLogFileSizeLimit());
+    assertThat(data.getLogDiskSpaceLimit()).isEqualTo(config.getLogDiskSpaceLimit());
+    assertThat(data.isClusterSSLEnabled()).isEqualTo(config.getClusterSSLEnabled());
+
+    assertThat(data.getClusterSSLCiphers()).isEqualTo(config.getClusterSSLCiphers());
+    assertThat(data.getClusterSSLProtocols()).isEqualTo(config.getClusterSSLProtocols());
+    assertThat(data.isClusterSSLRequireAuthentication()).isEqualTo(config.getClusterSSLRequireAuthentication());
+    assertThat(data.getSocketLeaseTime()).isEqualTo(config.getSocketLeaseTime());
+    assertThat(data.getSocketBufferSize()).isEqualTo(config.getSocketBufferSize());
+    assertThat(data.getMcastSendBufferSize()).isEqualTo(config.getMcastSendBufferSize());
+    assertThat(data.getMcastRecvBufferSize()).isEqualTo(config.getMcastRecvBufferSize());
+    assertThat(data.getMcastByteAllowance()).isEqualTo(config.getMcastFlowControl().getByteAllowance());
+    assertThat(data.getMcastRechargeThreshold()).isEqualTo(config.getMcastFlowControl().getRechargeThreshold());
+    assertThat(data.getMcastRechargeBlockMs()).isEqualTo(config.getMcastFlowControl().getRechargeBlockMs());
+    assertThat(data.getUdpFragmentSize()).isEqualTo(config.getUdpFragmentSize());
+    assertThat(data.getUdpSendBufferSize()).isEqualTo(config.getUdpSendBufferSize());
+    assertThat(data.getUdpRecvBufferSize()).isEqualTo(config.getUdpRecvBufferSize());
+    assertThat(data.isDisableTcp()).isEqualTo(config.getDisableTcp());
+    assertThat(data.isEnableTimeStatistics()).isEqualTo(config.getEnableTimeStatistics());
+    assertThat(data.isEnableNetworkPartitionDetection()).isEqualTo(config.getEnableNetworkPartitionDetection());
+    assertThat(data.getMemberTimeout()).isEqualTo(config.getMemberTimeout());
+
+    assertThat(data.getMembershipPortRange()).containsExactly(config.getMembershipPortRange());
+
+    assertThat(data.isConserveSockets()).isEqualTo(config.getConserveSockets());
+    assertThat(data.getRoles()).isEqualTo(config.getRoles());
+    assertThat(data.getMaxWaitTimeForReconnect()).isEqualTo(config.getMaxWaitTimeForReconnect());
+    assertThat(data.getMaxNumReconnectTries()).isEqualTo(config.getMaxNumReconnectTries());
+    assertThat(data.getAsyncDistributionTimeout()).isEqualTo(config.getAsyncDistributionTimeout());
+    assertThat(data.getAsyncMaxQueueSize()).isEqualTo(config.getAsyncMaxQueueSize());
+    assertThat(data.getClientConflation()).isEqualTo(config.getClientConflation());
+    assertThat(data.getDurableClientId()).isEqualTo(config.getDurableClientId());
+    assertThat(data.getDurableClientTimeout()).isEqualTo(config.getDurableClientTimeout());
+    assertThat(data.getSecurityClientAuthInit()).isEqualTo(config.getSecurityClientAuthInit());
+    assertThat(data.getSecurityClientAuthenticator()).isEqualTo(config.getSecurityClientAuthenticator());
+    assertThat(data.getSecurityClientDHAlgo()).isEqualTo(config.getSecurityClientDHAlgo());
+    assertThat(data.getSecurityPeerAuthInit()).isEqualTo(config.getSecurityPeerAuthInit());
+    assertThat(data.getSecurityClientAuthenticator()).isEqualTo(config.getSecurityPeerAuthenticator());
+    assertThat(data.getSecurityClientAccessor()).isEqualTo(config.getSecurityClientAccessor());
+    assertThat(data.getSecurityClientAccessorPP()).isEqualTo(config.getSecurityClientAccessorPP());
+    assertThat(data.getSecurityLogLevel()).isEqualTo(config.getSecurityLogLevel());
+    assertThat(removeVMDir(data.getSecurityLogFile())).isEqualTo(removeVMDir(config.getSecurityLogFile().getAbsolutePath()));
+    assertThat(data.getSecurityPeerMembershipTimeout()).isEqualTo(config.getSecurityPeerMembershipTimeout());
+    assertThat(data.isRemoveUnresponsiveClient()).isEqualTo(config.getRemoveUnresponsiveClient());
+    assertThat(data.isDeltaPropagation()).isEqualTo(config.getDeltaPropagation());
+    assertThat(data.getRedundancyZone()).isEqualTo(config.getRedundancyZone());
+    assertThat(data.isEnforceUniqueHost()).isEqualTo(config.getEnforceUniqueHost());
+    assertThat(data.getStatisticSampleRate()).isEqualTo(config.getStatisticSampleRate());
   }
 
   private static String removeVMDir(String string) {
     return string.replaceAll("vm.", "");
   }
 
-  public static void startManager() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    // When the cache is created if jmx-manager is true then we create the manager.
-    // So it may already exist when we get here.
-    if (!bean.isManagerCreated()) {
-      if (!bean.createManager()) {
-        fail("Could not create Manager");
-      } else if (!bean.isManagerCreated()) {
-        fail("Should have been a manager after createManager returned true.");
-      }
+  private void startManager() throws JMException {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    if (memberMXBean.isManagerCreated()) {
+      return;
     }
-    ManagerMXBean mngrBean = getManagementService().getManagerMXBean();
-    try {
-      mngrBean.start();
-    } catch (JMException e) {
-      fail("Could not start Manager " + e);
-    }
-    assertTrue(mngrBean.isRunning());
-    assertTrue(getManagementService().isManager());
-    assertTrue(bean.isManager());
-  }
-
-  public static void isManager() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    if (bean.createManager()) {
-      ManagerMXBean mngrBean = getManagementService().getManagerMXBean();
-      try {
-        mngrBean.start();
-      } catch (JMException e) {
-        fail("Could not start Manager " + e);
-      }
-    } else {
-      fail(" Could not create Manager");
-    }
-  }
 
-  public static String fetchLog() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    String log = bean.showLog(30);
-    return log;
-  }
-
-  public static void fetchJVMMetrics() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    JVMMetrics metrics = bean.showJVMMetrics();
+    // TODO: cleanup this mess
+    // When the cache is created if jmx-managerVM is true then we create the managerVM.
+    // So it may already exist when we get here.
 
-    LogWriterUtils.getLogWriter().info("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
-  }
+    assertThat(memberMXBean.createManager()).isTrue();
+    assertThat(memberMXBean.isManagerCreated()).isTrue();
 
-  public static void fetchOSMetrics() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    OSMetrics metrics = bean.showOSMetrics();
+    ManagerMXBean managerMXBean = service.getManagerMXBean();
+    managerMXBean.start();
 
-    LogWriterUtils.getLogWriter().info("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
+    assertThat(managerMXBean.isRunning()).isTrue();
+    assertThat(memberMXBean.isManager()).isTrue();
+    assertThat(service.isManager()).isTrue();
   }
 
-  public static void shutDownMember() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    bean.shutDownMember();
+  private String fetchLog(final int numberOfLines) {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    return memberMXBean.showLog(numberOfLines);
   }
 
-  public static void assertExpectedMembers(int expectedMemberCount) {
-    Wait.waitForCriterion(new WaitCriterion() {
-      public String description() {
-        return "Waiting all nodes to shutDown";
-      }
-
-      public boolean done() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> setOfOtherMembers = cache.getDistributedSystem().getAllOtherMembers();
-        boolean done = (setOfOtherMembers != null && setOfOtherMembers.size() == 1);
-        return done;
-      }
-
-    }, MAX_WAIT, 500, true);
+  private JVMMetrics fetchJVMMetrics() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    JVMMetrics metrics = memberMXBean.showJVMMetrics();
+    return metrics;
   }
 
-  public static void invokeRemoteOps() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    Set<DistributedMember> otherMemberSet = cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-    for (DistributedMember member : otherMemberSet) {
-      MemberMXBean bean = MBeanUtil.getMemberMbeanProxy(member);
-      JVMMetrics metrics = bean.showJVMMetrics();
-
-      LogWriterUtils.getLogWriter().info("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
-      LogWriterUtils.getLogWriter().info("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
-
-      LogWriterUtils.getLogWriter().info("<ExpectedString> Boolean Data Check " + bean.isManager() + "</ExpectedString> ");
-    }
+  private OSMetrics fetchOSMetrics() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    OSMetrics metrics = memberMXBean.showOSMetrics();
+    return metrics;
   }
 
-  @Test
-  public void testNotification() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
-
-    // Step : 1 : Create Managed Node Caches
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
-
-    // Step : 2 : Create Managing Node Cache, start manager, add a notification
-    // handler to DistributedSystemMXBean
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    attchListenerToDSMBean(managingNode);
-
-    // Step : 3 : Verify Notification count, notification region sizes
-    countNotificationsAndCheckRegionSize(node1, node2, node3, managingNode);
+  private void shutDownMember() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    memberMXBean.shutDownMember();
   }
 
-  @Test
-  public void testNotificationManagingNodeFirst() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
-
-    // Step : 1 : Create Managing Node Cache, start manager, add a notification
-    // handler to DistributedSystemMXBean
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    attchListenerToDSMBean(managingNode);
-
-    // Step : 2 : Create Managed Node Caches
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
-
-    // Step : 3 : Verify Notification count, notification region sizes
-    countNotificationsAndCheckRegionSize(node1, node2, node3, managingNode);
+  private void verifyExpectedMembers(final int otherMembersCount) {
+    String alias = "awaiting " + this.managementTestRule.getOtherNormalMembers() + " to have size " + otherMembersCount;
+    await(alias).until(() -> assertThat(this.managementTestRule.getOtherNormalMembers()).hasSize(otherMembersCount));
   }
 
-  @Test
-  public void testRedundancyZone() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    Properties props = new Properties();
-    props.setProperty(REDUNDANCY_ZONE, "ARMY_ZONE");
+  private void invokeRemoteMemberMXBeanOps() throws Exception {
+    Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
 
-    createCache(node1, props);
+    for (DistributedMember member : otherMembers) {
+      MemberMXBean memberMXBean = awaitMemberMXBeanProxy(member);
 
-    node1.invoke(new SerializableRunnable("Assert Redundancy Zone") {
+      JVMMetrics metrics = memberMXBean.showJVMMetrics();
 
-      public void run() {
-        ManagementService service = ManagementService.getExistingManagementService(getCache());
-        MemberMXBean bean = service.getMemberMXBean();
-        assertEquals("ARMY_ZONE", bean.getRedundancyZone());
-      }
-    });
-  }
+      String value = metrics.toString();
+      boolean isManager = memberMXBean.isManager();
 
-  protected void attchListenerToDSMBean(final VM vm) {
-    SerializableRunnable attchListenerToDSMBean = new SerializableRunnable("Attach Listener to DS MBean") {
-      public void run() {
-        assertTrue(managementService.isManager());
-        DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean();
-
-        // First clear the notification list
-        notifList.clear();
-
-        NotificationListener nt = new NotificationListener() {
-          @Override
-          public void handleNotification(Notification notification, Object handback) {
-            if (notification.getType().equals(JMXNotificationType.REGION_CREATED)) {
-              notifList.add(notification);
-            }
-          }
-        };
-
-        try {
-          mbeanServer.addNotificationListener(MBeanJMXAdapter.getDistributedSystemName(), nt, null, null);
-        } catch (InstanceNotFoundException e) {
-          throw new AssertionError("Failed With Exception ", e);
-        }
+      // TODO: need assertions
 
-      }
-    };
-    vm.invoke(attchListenerToDSMBean);
+      //("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
+      //("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
+      //("<ExpectedString> Boolean Data Check " + bean.isManager() + "</ExpectedString> ");
+    }
   }
 
-  public void waitForManagerToRegisterListener() {
-    SystemManagementService service = (SystemManagementService) getManagementService();
-    final Map<ObjectName, NotificationHubListener> hubMap = service.getNotificationHub().getListenerObjectMap();
-
-    Wait.waitForCriterion(new WaitCriterion() {
-      public String description() {
-        return "Waiting for manager to register the listener";
-      }
+  private void attachListenerToDistributedSystemMXBean(final VM managerVM) {
+    managerVM.invoke("attachListenerToDistributedSystemMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      assertThat(service.isManager()).isTrue();
 
-      public boolean done() {
-        boolean done = (1 == hubMap.size());
-        return done;
-      }
+      NotificationListener listener = (final Notification notification, final Object handback) -> {
+        if (notification.getType().equals(JMXNotificationType.REGION_CREATED)) {
+          notifications.add(notification);
+        }
+      };
 
-    }, MAX_WAIT, 500, true);
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(MBeanJMXAdapter.getDistributedSystemName(), listener, null, null);
+    });
   }
 
-  public void countNotificationsAndCheckRegionSize(VM node1, VM node2, VM node3, VM managingNode) {
-
-    DistributedMember member1 = getMember(node1);
-    DistributedMember member2 = getMember(node2);
-    DistributedMember member3 = getMember(node3);
-
-    final String appender1 = MBeanJMXAdapter.getUniqueIDForMember(member1);
-    final String appender2 = MBeanJMXAdapter.getUniqueIDForMember(member2);
-    final String appender3 = MBeanJMXAdapter.getUniqueIDForMember(member3);
+  private void verifyNotificationsAndRegionSize(final VM memberVM1, final VM memberVM2, final VM memberVM3, final VM managerVM) {
+    DistributedMember member1 = this.managementTestRule.getDistributedMember(memberVM1);
+    DistributedMember member2 = this.managementTestRule.getDistributedMember(memberVM2);
+    DistributedMember member3 = this.managementTestRule.getDistributedMember(memberVM3);
 
-    node1.invoke("Create Regions", () -> createNotifTestRegion(appender1));
-    node2.invoke("Create Regions", () -> createNotifTestRegion(appender2));
-    node3.invoke("Create Regions", () -> createNotifTestRegion(appender3));
+    String memberId1 = MBeanJMXAdapter.getUniqueIDForMember(member1);
+    String memberId2 = MBeanJMXAdapter.getUniqueIDForMember(member2);
+    String memberId3 = MBeanJMXAdapter.getUniqueIDForMember(member3);
 
-    managingNode.invoke(new SerializableRunnable("Validate Notification Count") {
+    memberVM1.invoke("createNotificationRegion", () -> createNotificationRegion(memberId1));
+    memberVM2.invoke("createNotificationRegion", () -> createNotificationRegion(memberId2));
+    memberVM3.invoke("createNotificationRegion", () -> createNotificationRegion(memberId3));
 
-      public void run() {
+    managerVM.invoke("verify notifications size", () -> {
+      await().until(() -> assertThat(notifications.size()).isEqualTo(45));
 
-        Wait.waitForCriterion(new WaitCriterion() {
-          public String description() {
-            return "Waiting for all the RegionCreated notification to reach the manager " + notifList.size();
-          }
+      Cache cache = this.managementTestRule.getCache();
 
-          public boolean done() {
-            boolean done = (45 == notifList.size());
-            return done;
-          }
+      Region region1 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId1);
+      Region region2 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId2);
+      Region region3 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId3);
 
-        }, MAX_WAIT, 500, true);
+      // Even though we got 15 notification only 10 should be there due to
+      // eviction attributes set in notification region
 
-        assertEquals(45, notifList.size());
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
+      await().until(() -> assertThat(region1).hasSize(10));
+      await().until(() -> assertThat(region2).hasSize(10));
+      await().until(() -> assertThat(region3).hasSize(10));
+    });
+  }
 
-        Region member1NotifRegion = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender1);
-        Region member2NotifRegion = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender2);
-        Region member3NotifRegion = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender3);
+  private void createNotificationRegion(final String memberId) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    Map<ObjectName, NotificationHubListener> notificationHubListenerMap = service.getNotificationHub().getListenerObjectMap();
 
-        // Even though we got 15 notification only 10 should be there due to
-        // eviction attributes set in notification region
+    await().until(() -> assertThat(notificationHubListenerMap.size()).isEqualTo(1));
 
-        waitAtMost(5, TimeUnit.SECONDS).untilCall(to(member1NotifRegion).size(), equalTo(10));
-        waitAtMost(5, TimeUnit.SECONDS).untilCall(to(member2NotifRegion).size(), equalTo(10));
-        waitAtMost(5, TimeUnit.SECONDS).untilCall(to(member3NotifRegion).size(), equalTo(10));
-      }
-    });
+    RegionFactory regionFactory = this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE);
+    for (int i = 1; i <= 15; i++) {
+      regionFactory.create(NOTIFICATION_REGION_NAME + i);
+    }
+    Region region = this.managementTestRule.getCache().getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId);
 
+    assertThat(region).isEmpty();
   }
 
-  private void createNotifTestRegion(final String appender1) {
-    Cache cache = getCache();
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getMemberMBeanName(member);
 
-    waitForManagerToRegisterListener();
-    RegionFactory rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-    for (int i = 1; i <= 15; i++) {
-      rf.create("NotifTestRegion_" + i);
-    }
-    Region member1NotifRegion = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender1);
+    String alias = "awaiting MemberMXBean proxy for " + member;
+    await(alias).until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
 
-    assertEquals(0, member1NotifRegion.size());
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
   }
 
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
+  }
+
+  private ConditionFactory await(final String alias) {
+    return Awaitility.await(alias).atMost(2, MINUTES);
+  }
 }


[7/8] incubator-geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java
index a62bb06..523c98f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java
@@ -16,13 +16,25 @@
  */
 package org.apache.geode.management;
 
+import static java.util.concurrent.TimeUnit.*;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Assert.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.IgnoredException.*;
+import static org.apache.geode.test.dunit.Invoke.*;
+import static org.apache.geode.test.dunit.NetworkUtils.*;
+import static org.assertj.core.api.Assertions.*;
 
+import java.io.Serializable;
 import java.util.Collection;
-import java.util.Iterator;
 import java.util.Properties;
 
+import javax.management.ObjectName;
+
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -31,412 +43,360 @@ import org.apache.geode.cache.EntryEvent;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
 import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.client.ClientCache;
 import org.apache.geode.cache.client.ClientCacheFactory;
 import org.apache.geode.cache.client.ClientRegionFactory;
 import org.apache.geode.cache.client.ClientRegionShortcut;
 import org.apache.geode.cache.server.CacheServer;
 import org.apache.geode.cache.util.CacheListenerAdapter;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
 import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
-import org.apache.geode.internal.i18n.LocalizedStrings;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.IgnoredException;
+import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
  * Client health stats check
  */
 @Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class ClientHealthStatsDUnitTest extends JUnit4DistributedTestCase {
-
-  private static final String k1 = "k1";
-  private static final String k2 = "k2";
-  private static final String client_k1 = "client-k1";
-  private static final String client_k2 = "client-k2";
-
-  /** name of the test region */
-  private static final String REGION_NAME = "ClientHealthStatsDUnitTest_Region";
-
-  private static VM client = null;
-  private static VM client2 = null;
-  private static VM managingNode = null;
-
-  private static ManagementTestBase helper = new ManagementTestBase(){};
-  
-  private static int numOfCreates = 0;
-  private static int numOfUpdates = 0;
-  private static int numOfInvalidates = 0;
-  private static boolean lastKeyReceived = false;
-  
-  private static GemFireCacheImpl cache = null;
-
-  private VM server = null;
-
-  @Override
-  public final void postSetUp() throws Exception {
-    disconnectAllFromDS();
-
-    final Host host = Host.getHost(0);
-    managingNode = host.getVM(0);
-    server = host.getVM(1);
-    client = host.getVM(2);
-    client2 = host.getVM(3);
-
-    IgnoredException.addIgnoredException("Connection reset");
-  }
+@SuppressWarnings({ "serial", "unused" })
+public class ClientHealthStatsDUnitTest implements Serializable {
+
+  private static final int NUMBER_PUTS = 100;
+
+  private static final String KEY1 = "KEY1";
+  private static final String KEY2 = "KEY2";
+  private static final String VALUE1 = "VALUE1";
+  private static final String VALUE2 = "VALUE2";
+
+  private static final String REGION_NAME = ClientHealthStatsDUnitTest.class.getSimpleName() + "_Region";
+
+  // client1VM and client2VM VM fields
+  private static ClientCache clientCache;
+
+  // TODO: assert following values in each client VM
+  private static int numOfCreates;
+  private static int numOfUpdates;
+  private static int numOfInvalidates;
+  private static boolean lastKeyReceived;
+
+  private VM managerVM;
+  private VM serverVM;
+  private VM client1VM;
+  private VM client2VM;
+
+  private String hostName;
+
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-  @Override
-  public final void preTearDown() throws Exception {
-    reset();
-    helper.closeCache(managingNode);
-    helper.closeCache(client);
-    helper.closeCache(client2);
-    helper.closeCache(server);
+  @Before
+  public void before() throws Exception {
+    this.hostName = getServerHostName(getHost(0));
 
-    disconnectAllFromDS();
+    this.managerVM = getHost(0).getVM(0);
+    this.serverVM = getHost(0).getVM(1);
+    this.client1VM = getHost(0).getVM(2);
+    this.client2VM = getHost(0).getVM(3);
+
+    addIgnoredException("Connection reset");
   }
 
-  private static void reset() throws Exception {
-    lastKeyReceived = false;
-    numOfCreates = 0;
-    numOfUpdates = 0;
-    numOfInvalidates = 0;
+  @After
+  public void after() throws Exception {
+    invokeInEveryVM(() -> {
+      lastKeyReceived = false;
+      numOfCreates = 0;
+      numOfUpdates = 0;
+      numOfInvalidates = 0;
+      clientCache = null;
+    });
   }
 
   @Test
   public void testClientHealthStats_SubscriptionEnabled() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
+
+    int port = this.serverVM.invoke(() -> createServerCache());
 
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, true));
 
-    DistributedMember serverMember = helper.getMember(server);
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> put());
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, false));
-    
-    client2.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 2, true, false));
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    this.managerVM.invoke(() -> verifyClientStats(serverMember, port, 2));
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.put());
-    client2.invoke(() -> ClientHealthStatsDUnitTest.put());
-    
-    managingNode.invoke(() -> ClientHealthStatsDUnitTest.verifyClientStats(serverMember, port, 2));
-    helper.stopManagingNode(managingNode);
+    this.managementTestRule.stopManager(this.managerVM);
   }
-  
+
   @Test
   public void testClientHealthStats_SubscriptionDisabled() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
+    int port = this.serverVM.invoke(() -> createServerCache());
 
-    DistributedMember serverMember = helper.getMember(server);
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, false));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, false));
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, false, false));
-    
-    client2.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 2, false, false));
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> put());
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.put());
-    client2.invoke(() -> ClientHealthStatsDUnitTest.put());
-    
-    managingNode.invoke(() -> ClientHealthStatsDUnitTest.verifyClientStats(serverMember, port, 0));
-    helper.stopManagingNode(managingNode);
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    this.managerVM.invoke(() -> verifyClientStats(serverMember, port, 0));
+    this.managementTestRule.stopManager(this.managerVM);
   }
-  
+
   @Test
   public void testClientHealthStats_DurableClient() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
-
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
-
-    DistributedMember serverMember = helper.getMember(server);
-
-    client.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, true));
-    
-    client2.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 2, true, true));
-
-    client.invoke(() -> ClientHealthStatsDUnitTest.put());
-    client2.invoke(() -> ClientHealthStatsDUnitTest.put());
-    
-    client.invoke(() -> ClientHealthStatsDUnitTest.closeClientCache());
-    
-    client2.invoke(() -> ClientHealthStatsDUnitTest.closeClientCache());
-    
-    managingNode.invoke(() -> ClientHealthStatsDUnitTest.verifyClientStats(serverMember, port, 2));
-    helper.stopManagingNode(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
+
+    int port = this.serverVM.invoke(() -> createServerCache());
+
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, true));
+
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> put());
+
+    this.client1VM.invoke(() -> clientCache.close(true));
+    this.client2VM.invoke(() -> clientCache.close(true));
+
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    this.managerVM.invoke(() -> verifyClientStats(serverMember, port, 2));
+    this.managementTestRule.stopManager(this.managerVM);
   }
-  
+
   @Test
   public void testStatsMatchWithSize() throws Exception {
-    // start a server
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
-    // create durable client, with durable RI
-    client.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, false));
-    // do puts on server from three different threads, pause after 500 puts each.
-    server.invoke(() -> ClientHealthStatsDUnitTest.doPuts());
-    // close durable client
-    client.invoke(() -> ClientHealthStatsDUnitTest.closeClientCache());
-    
-    server.invoke("verifyProxyHasBeenPaused", () -> verifyProxyHasBeenPaused() );
-    // resume puts on server, add another 100.
-    server.invokeAsync(() -> ClientHealthStatsDUnitTest.resumePuts());
-    // start durable client
-    client.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, false));
-    // wait for full queue dispatch
-    client.invoke(() -> ClientHealthStatsDUnitTest.waitForLastKey());
-    // verify the stats
-    server.invoke(() -> ClientHealthStatsDUnitTest.verifyStats(port));
-  }
-  
-  private static void verifyProxyHasBeenPaused() {	  
-	  
-	  WaitCriterion criterion = new WaitCriterion() {
-      
-      @Override
-      public boolean done() {
-        CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-        Collection<CacheClientProxy> ccProxies = ccn.getClientProxies();
-        
-        Iterator<CacheClientProxy> itr =  ccProxies.iterator();
-        
-        while(itr.hasNext()) {
-          CacheClientProxy ccp = itr.next(); 
-          System.out.println("proxy status " + ccp.getState());
-          if(ccp.isPaused())
-            return true;
-        }
-        return false;
-      }
-      
-      @Override
-      public String description() {
-        return "Proxy has not paused yet";
-      }
-    };
-    
-    Wait.waitForCriterion(criterion, 15 * 1000, 200, true);	  
+    int port = this.serverVM.invoke(() -> createServerCache()); // start a serverVM
+
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true)); // create durable client1VM, with durable RI
+
+    this.serverVM.invoke(() -> doPuts()); // do puts on serverVM from three different threads, pause after 500 puts each.
+
+    this.client1VM.invoke(() -> clientCache.close(true)); // close durable client1VM
+
+    this.serverVM.invoke(() -> await().atMost(2, MINUTES).until(() -> cacheClientProxyHasBeenPause()));
+
+    this.serverVM.invoke(() -> resumePuts()); // resume puts on serverVM, add another 100.
+
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true)); // start durable client1VM
+
+    this.client1VM.invoke(() -> await().atMost(1, MINUTES).until(() -> lastKeyReceived)); // wait for full queue dispatch
+
+    this.serverVM.invoke(() -> verifyStats(port)); // verify the stats
   }
 
-  private static int createServerCache() throws Exception {
-    Cache cache = helper.createCache(false);
+  /**
+   * Invoked in serverVM
+   */
+  private boolean cacheClientProxyHasBeenPause() {
+    CacheClientNotifier clientNotifier = CacheClientNotifier.getInstance(); // TODO
+    //CacheClientNotifier clientNotifier = ((CacheServerImpl)this.managementTestRule.getCache().getCacheServers().get(0)).getAcceptor().getCacheClientNotifier();
 
-    RegionFactory<String, String> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-    rf.setConcurrencyChecksEnabled(false);
-    rf.create(REGION_NAME);
+    Collection<CacheClientProxy> clientProxies = clientNotifier.getClientProxies();
 
-    CacheServer server1 = cache.addCacheServer();
-    server1.setPort(0);
-    server1.start();
-    return server1.getPort();
+    for (CacheClientProxy clientProxy: clientProxies) {
+      if (clientProxy.isPaused()) {
+        return true;
+      }
+    }
+    return false;
   }
 
-  private static void closeClientCache() throws Exception {
-    cache.close(true);
+  /**
+   * Invoked in serverVM
+   */
+  private int createServerCache() throws Exception {
+    Cache cache = this.managementTestRule.getCache();
+
+    RegionFactory<String, String> regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+    regionFactory.setConcurrencyChecksEnabled(false);
+    regionFactory.create(REGION_NAME);
+
+    CacheServer cacheServer = cache.addCacheServer();
+    cacheServer.setPort(0);
+    cacheServer.start();
+    return cacheServer.getPort();
   }
 
-  private static void createClientCache(Host host, Integer port, int clientNum, boolean subscriptionEnabled, boolean durable) throws Exception {
+  /**
+   * Invoked in client1VM and client2VM
+   */
+  private void createClientCache(final String hostName,
+                                 final Integer port,
+                                 final int clientNum,
+                                 final boolean subscriptionEnabled) throws Exception {
     Properties props = new Properties();
-    props.setProperty(DURABLE_CLIENT_ID, "durable-"+clientNum);
-    props.setProperty(DURABLE_CLIENT_TIMEOUT, "300000");
-    props.setProperty(LOG_LEVEL, "info");
-    props.setProperty(STATISTIC_ARCHIVE_FILE, getTestMethodName() + "_client_" + clientNum + ".gfs");
     props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
 
-    ClientCacheFactory ccf = new ClientCacheFactory(props);
-    if(subscriptionEnabled){
-      ccf.setPoolSubscriptionEnabled(true);
-      ccf.setPoolSubscriptionAckInterval(50);
-      ccf.setPoolSubscriptionRedundancy(0);
-    }
-    
-    if(durable){
-      ccf.set(DURABLE_CLIENT_ID, "DurableClientId_" + clientNum);
-      ccf.set(DURABLE_CLIENT_TIMEOUT, "" + 300);
+    ClientCacheFactory cacheFactory = new ClientCacheFactory(props);
+    if (subscriptionEnabled) {
+      cacheFactory.setPoolSubscriptionEnabled(true);
+      cacheFactory.setPoolSubscriptionAckInterval(50);
+      cacheFactory.setPoolSubscriptionRedundancy(0);
     }
 
-    ccf.addPoolServer(host.getHostName(), port);
-    cache = (GemFireCacheImpl) ccf.create();
+    cacheFactory.set(DURABLE_CLIENT_ID, "DurableClientId_" + clientNum);
+    cacheFactory.set(DURABLE_CLIENT_TIMEOUT, "" + 30000);
+
+    cacheFactory.addPoolServer(hostName, port);
+    clientCache = cacheFactory.create();
 
-    ClientRegionFactory<String, String> crf = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
-    crf.setConcurrencyChecksEnabled(false);
+    ClientRegionFactory<String, String> regionFactory = clientCache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
+    regionFactory.setConcurrencyChecksEnabled(false);
 
-    crf.addCacheListener(new CacheListenerAdapter<String, String>() {
-      public void afterInvalidate(EntryEvent<String, String> event) {
-        cache.getLoggerI18n().fine(
-            "Invalidate Event: " + event.getKey() + ", " + event.getNewValue());
+    regionFactory.addCacheListener(new CacheListenerAdapter<String, String>() {
+      @Override
+      public void afterInvalidate(final EntryEvent<String, String> event) {
         numOfInvalidates++;
       }
-      public void afterCreate(EntryEvent<String, String> event) {
-        if (((String) event.getKey()).equals("last_key")) {
+
+      @Override
+      public void afterCreate(final EntryEvent<String, String> event) {
+        if ("last_key".equals(event.getKey())) {
           lastKeyReceived = true;
         }
-        cache.getLoggerI18n().fine(
-            "Create Event: " + event.getKey() + ", " + event.getNewValue());
         numOfCreates++;
       }
-      public void afterUpdate(EntryEvent<String, String> event) {
-        cache.getLoggerI18n().fine(
-            "Update Event: " + event.getKey() + ", " + event.getNewValue());
+
+      @Override
+      public void afterUpdate(final EntryEvent<String, String> event) {
         numOfUpdates++;
       }
     });
 
-    Region<String, String> r = crf.create(REGION_NAME);
-    if(subscriptionEnabled){
-      r.registerInterest("ALL_KEYS", true);
-      cache.readyForEvents();
+    Region<String, String> region = regionFactory.create(REGION_NAME);
+    if (subscriptionEnabled) {
+      region.registerInterest("ALL_KEYS", true);
+      clientCache.readyForEvents();
     }
   }
 
-  private static void doPuts() throws Exception {
-    Cache cache = GemFireCacheImpl.getInstance();
-    final Region<String, String> r = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-    Thread t1 = new Thread(new Runnable() {
-      public void run() {
-        for (int i = 0; i < 500; i++) {
-          r.put("T1_KEY_"+i, "VALUE_"+i);
-        }
+  /**
+   * Invoked in serverVM
+   */
+  private void doPuts() throws Exception {
+    Cache cache = this.managementTestRule.getCache();
+    Region<String, String> region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+
+    Thread thread1 = new Thread(() -> {
+      for (int i = 0; i < NUMBER_PUTS; i++) {
+        region.put("T1_KEY_" + i, "VALUE_" + i);
       }
     });
-    Thread t2 = new Thread(new Runnable() {
-      public void run() {
-        for (int i = 0; i < 500; i++) {
-          r.put("T2_KEY_"+i, "VALUE_"+i);
-        }
+    Thread thread2 = new Thread(() -> {
+      for (int i = 0; i < NUMBER_PUTS; i++) {
+        region.put("T2_KEY_" + i, "VALUE_" + i);
       }
     });
-    Thread t3 = new Thread(new Runnable() {
-      public void run() {
-        for (int i = 0; i < 500; i++) {
-          r.put("T3_KEY_"+i, "VALUE_"+i);
-        }
+    Thread thread3 = new Thread(() -> {
+      for (int i = 0; i < NUMBER_PUTS; i++) {
+        region.put("T3_KEY_" + i, "VALUE_" + i);
       }
     });
 
-    t1.start();
-    t2.start();
-    t3.start();
+    thread1.start();
+    thread2.start();
+    thread3.start();
 
-    t1.join();
-    t2.join();
-    t3.join();
+    thread1.join();
+    thread2.join();
+    thread3.join();
   }
 
-  private static void resumePuts() {
-    Cache cache = GemFireCacheImpl.getInstance();
-    Region<String, String> r = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-    for (int i = 0; i < 100; i++) {
-      r.put("NEWKEY_"+i, "NEWVALUE_"+i);
+  /**
+   * Invoked in serverVM
+   */
+  private void resumePuts() {
+    Cache cache = this.managementTestRule.getCache();
+    Region<String, String> region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+
+    for (int i = 0; i < NUMBER_PUTS; i++) {
+      region.put("NEWKEY_" + i, "NEWVALUE_" + i);
     }
-    r.put("last_key", "last_value");
+    region.put("last_key", "last_value");
   }
 
-  private static void waitForLastKey() {
-    WaitCriterion wc = new WaitCriterion() {
-      @Override
-      public boolean done() {
-        return lastKeyReceived;
-      }
-      @Override
-      public String description() {
-        return "Did not receive last key.";
-      }
-    };
-    Wait.waitForCriterion(wc, 60*1000, 500, true);
-  }
+  /**
+   * Invoked in managerVM
+   */
+  private void verifyClientStats(final DistributedMember serverMember, final int serverPort, final int numSubscriptions) throws Exception {
+    ManagementService service = this.managementTestRule.getManagementService();
+    CacheServerMXBean cacheServerMXBean = awaitCacheServerMXBean(serverMember, serverPort);
 
-  private static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
-  }
+    String[] clientIds = cacheServerMXBean.getClientIds();
+    assertThat(clientIds).hasSize(2);
 
-  private static void verifyClientStats(DistributedMember serverMember, int serverPort, int numSubscriptions) {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    try {
-      ManagementService service = ManagementService.getExistingManagementService(cache);
-      CacheServerMXBean bean = MBeanUtil.getCacheServerMbeanProxy(serverMember, serverPort);
-
-      String[] clientIds = bean.getClientIds();
-      assertTrue(clientIds.length == 2);
-      System.out.println("<ExpectedString> ClientId-1 of the Server is  " + clientIds[0] + "</ExpectedString> ");
-      System.out.println("<ExpectedString> ClientId-2 of the Server is  " + clientIds[1] + "</ExpectedString> ");
-      
-      ClientHealthStatus[] clientStatuses = bean.showAllClientStats();
-
-      ClientHealthStatus clientStatus1 = bean.showClientStats(clientIds[0]);
-      ClientHealthStatus clientStatus2 = bean.showClientStats(clientIds[1]);
-      assertNotNull(clientStatus1);
-      assertNotNull(clientStatus2);
-      System.out.println("<ExpectedString> ClientStats-1 of the Server is  " + clientStatus1 + "</ExpectedString> ");
-      System.out.println("<ExpectedString> ClientStats-2 of the Server is  " + clientStatus2 + "</ExpectedString> ");
-
-      System.out.println("<ExpectedString> clientStatuses " + clientStatuses + "</ExpectedString> ");
-      assertNotNull(clientStatuses);
-      
-      assertTrue(clientStatuses.length == 2);
-      for (ClientHealthStatus status : clientStatuses) {
-        System.out.println("<ExpectedString> ClientStats of the Server is  " + status + "</ExpectedString> ");
-      }
+    ClientHealthStatus[] clientStatuses = cacheServerMXBean.showAllClientStats();
 
-      DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
-      assertEquals(2, dsBean.getNumClients());
-      assertEquals(numSubscriptions, dsBean.getNumSubscriptions());
+    ClientHealthStatus clientStatus1 = cacheServerMXBean.showClientStats(clientIds[0]);
+    ClientHealthStatus clientStatus2 = cacheServerMXBean.showClientStats(clientIds[1]);
+    assertThat(clientStatus1).isNotNull();
+    assertThat(clientStatus2).isNotNull();
 
-    } catch (Exception e) {
-      fail("Error while verifying cache server from remote member", e);
-    }
+    assertThat(clientStatuses).isNotNull().hasSize(2);
+
+    DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
+    assertThat(dsBean.getNumClients()).isEqualTo(2);
+    assertThat(dsBean.getNumSubscriptions()).isEqualTo(numSubscriptions);
   }
 
-  private static void put() {
-    Cache cache = GemFireCacheImpl.getInstance();
-    Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-    assertNotNull(r1);
-
-    r1.put(k1, client_k1);
-    assertEquals(r1.getEntry(k1).getValue(), client_k1);
-    r1.put(k2, client_k2);
-    assertEquals(r1.getEntry(k2).getValue(), client_k2);
-    try {
-      Thread.sleep(10000);
-    } catch (Exception e) {
-      // sleep
-    }
-    r1.clear();
-
-    r1.put(k1, client_k1);
-    assertEquals(r1.getEntry(k1).getValue(), client_k1);
-    r1.put(k2, client_k2);
-    assertEquals(r1.getEntry(k2).getValue(), client_k2);
-    r1.clear();
-    try {
-      Thread.sleep(10000);
-    } catch (Exception e) {
-      // sleep
-    }
+  /**
+   * Invoked in client1VM and client2VM
+   */
+  private void put() throws Exception {
+    Cache cache = (Cache)clientCache;
+    Region<String, String> region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+
+    region.put(KEY1, VALUE1);
+    assertThat(region.getEntry(KEY1).getValue()).isEqualTo(VALUE1);
+
+    region.put(KEY2, VALUE2);
+    assertThat(region.getEntry(KEY2).getValue()).isEqualTo(VALUE2);
+
+    region.clear();
+
+    region.put(KEY1, VALUE1);
+    assertThat(region.getEntry(KEY1).getValue()).isEqualTo(VALUE1);
+
+    region.put(KEY2, VALUE2);
+    assertThat(region.getEntry(KEY2).getValue()).isEqualTo(VALUE2);
+
+    region.clear();
   }
 
-  private static void verifyStats(int serverPort) throws Exception {
-    Cache cache = GemFireCacheImpl.getInstance();
-    ManagementService service = ManagementService.getExistingManagementService(cache);
+  /**
+   * Invoked in serverVM
+   */
+  private void verifyStats(final int serverPort) throws Exception {
+    ManagementService service = this.managementTestRule.getManagementService();
     CacheServerMXBean serverBean = service.getLocalCacheServerMXBean(serverPort);
-    CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-    CacheClientProxy ccp = ccn.getClientProxies().iterator().next();
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getQueueSize() " + ccp.getQueueSize());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getQueueSizeStat() " + ccp.getQueueSizeStat());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getEventsEnqued() " + ccp.getHARegionQueue().getStatistics().getEventsEnqued());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getEventsDispatched() " + ccp.getHARegionQueue().getStatistics().getEventsDispatched());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getEventsRemoved() " + ccp.getHARegionQueue().getStatistics().getEventsRemoved());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getNumVoidRemovals() " + ccp.getHARegionQueue().getStatistics().getNumVoidRemovals());
-    assertEquals(ccp.getQueueSize(), ccp.getQueueSizeStat());
+
+    CacheClientNotifier clientNotifier = CacheClientNotifier.getInstance();
+    CacheClientProxy clientProxy = clientNotifier.getClientProxies().iterator().next();
+    assertThat(clientProxy.getQueueSizeStat()).isEqualTo(clientProxy.getQueueSize());
+
     ClientQueueDetail queueDetails = serverBean.showClientQueueDetails()[0];
-    assertEquals(queueDetails.getQueueSize(), ccp.getQueueSizeStat());
+    assertThat(clientProxy.getQueueSizeStat()).isEqualTo((int)queueDetails.getQueueSize());
+  }
+
+  private CacheServerMXBean awaitCacheServerMXBean(final DistributedMember serverMember, final int port) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getCacheServerMBeanName(port, serverMember);
+
+    await().until(() -> assertThat(service.getMBeanProxy(objectName, CacheServerMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, CacheServerMXBean.class);
+  }
+
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
   }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java
index 914aef0..683fefd 100644
--- a/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java
@@ -16,162 +16,86 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
+import static java.util.concurrent.TimeUnit.*;
+import static org.assertj.core.api.Assertions.*;
 
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
+import java.io.Serializable;
 
-import javax.management.MalformedObjectNameException;
 import javax.management.ObjectName;
 
-import org.apache.geode.internal.cache.GemFireCacheImpl;
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.ManagementConstants;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.junit.categories.DistributedTest;
 
 @Category(DistributedTest.class)
-public class CompositeTypeTestDUnitTest extends ManagementTestBase {
+@SuppressWarnings({ "serial", "unused" })
+public class CompositeTypeTestDUnitTest implements Serializable {
 
-  public CompositeTypeTestDUnitTest() {
-    super();
-    // TODO Auto-generated constructor stub
-  }
+  @Manager
+  private VM managerVM;
 
-  /**
-   * 
-   */
-  private static final long serialVersionUID = 1L;
-  
-  private static ObjectName objectName;
+  @Member
+  private VM memberVM;
+
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().start(true).build();
 
-  @Category(FlakyTest.class) // GEODE-1492
   @Test
   public void testCompositeTypeGetters() throws Exception{
-    
-    initManagement(false);
-    String member = getMemberId(managedNode1);
-    member = MBeanJMXAdapter.makeCompliantName(member);
-    
-    registerMBeanWithCompositeTypeGetters(managedNode1,member);
-
-    
-    checkMBeanWithCompositeTypeGetters(managingNode,member);
-    
+    registerMBeanWithCompositeTypeGetters(this.memberVM);
+
+    String memberName = MBeanJMXAdapter.makeCompliantName(getMemberId(this.memberVM));
+    verifyMBeanWithCompositeTypeGetters(this.managerVM, memberName);
   }
 
-  
-  /**
-   * Creates a Local region
-   *
-   * @param vm
-   *          reference to VM
-   */
-  protected void registerMBeanWithCompositeTypeGetters(VM vm,final String memberID)
-      throws Exception {
-    SerializableRunnable regMBean = new SerializableRunnable(
-        "Register CustomMBean with composite Type") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
- 
-        try {
-          ObjectName objectName = new ObjectName("GemFire:service=custom,type=composite");
-          CompositeTestMXBean mbean =  new CompositeTestMBean();
-          objectName = service.registerMBean(mbean, objectName);
-          service.federate(objectName, CompositeTestMXBean.class, false);
-        } catch (MalformedObjectNameException e) {
-          // TODO Auto-generated catch block
-          e.printStackTrace();
-        } catch (NullPointerException e) {
-          // TODO Auto-generated catch block
-          e.printStackTrace();
-        }
-
-        
-
-      }
-    };
-    vm.invoke(regMBean);
+  private void registerMBeanWithCompositeTypeGetters(final VM memberVM) throws Exception {
+    memberVM.invoke("registerMBeanWithCompositeTypeGetters", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+
+      ObjectName objectName = new ObjectName("GemFire:service=custom,type=composite");
+      CompositeTestMXBean compositeTestMXBean = new CompositeTestMBean();
+
+      objectName = service.registerMBean(compositeTestMXBean, objectName);
+      service.federate(objectName, CompositeTestMXBean.class, false);
+    });
   }
-  
-  
-  /**
-   * Creates a Local region
-   *
-   * @param vm
-   *          reference to VM
-   */
-  protected void checkMBeanWithCompositeTypeGetters(VM vm,final String memberID)
-      throws Exception {
-    SerializableRunnable checkMBean = new SerializableRunnable(
-        "Check CustomMBean with composite Type") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        final SystemManagementService service = (SystemManagementService) getManagementService();
-
-        try {
-          final ObjectName objectName = new ObjectName("GemFire:service=custom,type=composite,member="+memberID);
-          
-          Wait.waitForCriterion(new WaitCriterion() {
-            public String description() {
-              return "Waiting for Composite Type MBean";
-            }
-
-            public boolean done() {
-              CompositeTestMXBean bean = service.getMBeanInstance(objectName, CompositeTestMXBean.class);
-              boolean done = (bean != null);
-              return done;
-            }
-
-          },  ManagementConstants.REFRESH_TIME*4, 500, true);
-
-          
-          CompositeTestMXBean bean = service.getMBeanInstance(objectName, CompositeTestMXBean.class);
-          
-          CompositeStats listData = bean.listCompositeStats();
-          
-          System.out.println("connectionStatsType = "+listData.getConnectionStatsType());
-          System.out.println("connectionsOpened = "+listData.getConnectionsOpened());
-          System.out.println("connectionsClosed = "+listData.getConnectionsClosed());
-          System.out.println("connectionsAttempted = "+listData.getConnectionsAttempted());
-          System.out.println("connectionsFailed = "+listData.getConnectionsFailed());
-          
-          CompositeStats getsData = bean.getCompositeStats();
-          System.out.println("connectionStatsType = "+getsData.getConnectionStatsType());
-          System.out.println("connectionsOpened = "+getsData.getConnectionsOpened());
-          System.out.println("connectionsClosed = "+getsData.getConnectionsClosed());
-          System.out.println("connectionsAttempted = "+getsData.getConnectionsAttempted());
-          System.out.println("connectionsFailed = "+getsData.getConnectionsFailed());
-          
-          CompositeStats[] arrayData = bean.getCompositeArray();
-          Integer[] intArrayData = bean.getIntegerArray();
-          Thread.sleep(2*60*1000);
-        } catch (MalformedObjectNameException e) {
-          // TODO Auto-generated catch block
-          e.printStackTrace();
-        } catch (NullPointerException e) {
-          // TODO Auto-generated catch block
-          e.printStackTrace();
-        } catch (InterruptedException e) {
-          // TODO Auto-generated catch block
-          e.printStackTrace();
-        }
-        
-        
-
-      }
-    };
-    vm.invoke(checkMBean);
+
+  private void verifyMBeanWithCompositeTypeGetters(final VM managerVM, final String memberId) throws Exception {
+    managerVM.invoke("verifyMBeanWithCompositeTypeGetters", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+      ObjectName objectName = new ObjectName("GemFire:service=custom,type=composite,member=" + memberId);
+
+      await().until(() -> service.getMBeanInstance(objectName, CompositeTestMXBean.class) != null);
+
+      CompositeTestMXBean compositeTestMXBean = service.getMBeanInstance(objectName, CompositeTestMXBean.class);
+      assertThat(compositeTestMXBean).isNotNull();
+
+      CompositeStats listCompositeStatsData = compositeTestMXBean.listCompositeStats();
+      assertThat(listCompositeStatsData).isNotNull();
+
+      CompositeStats getCompositeStatsData = compositeTestMXBean.getCompositeStats();
+      assertThat(getCompositeStatsData).isNotNull();
+
+      CompositeStats[] getCompositeArrayData = compositeTestMXBean.getCompositeArray();
+      assertThat(getCompositeArrayData).isNotNull().isNotEmpty();
+
+      Integer[] getIntegerArrayData = compositeTestMXBean.getIntegerArray();
+      assertThat(getIntegerArrayData).isNotNull().isNotEmpty();
+    });
   }
 
-  
+  private String getMemberId(final VM memberVM) {
+    return memberVM.invoke("getMemberId", () -> this.managementTestRule.getDistributedMember().getId());
+  }
+
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
+  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java
index 890ee04..c4806fb 100644
--- a/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java
@@ -16,467 +16,272 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
+import static java.util.concurrent.TimeUnit.*;
+import static org.apache.geode.internal.process.ProcessUtils.*;
+import static org.assertj.core.api.Assertions.*;
 
+import java.io.Serializable;
 import java.util.Map;
 import java.util.Set;
 
 import javax.management.ObjectName;
 
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Rule;
+import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import org.apache.geode.distributed.DistributedLockService;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.distributed.internal.locks.DLockService;
-import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.test.dunit.Assert;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.junit.categories.FlakyTest;
+import org.apache.geode.test.junit.categories.DistributedTest;
 
 @Category(DistributedTest.class)
-public class DLockManagementDUnitTest extends ManagementTestBase {
+@SuppressWarnings({ "serial", "unused" })
+public class DLockManagementDUnitTest implements Serializable {
 
-  private static final long serialVersionUID = 1L;
+  private static final int MAX_WAIT_MILLIS = 120 * 1000; // 2 MINUTES
 
-  private static final String LOCK_SERVICE_NAME = "testLockService";
-  
-  // This must be bigger than the dunit ack-wait-threshold for the revoke
-  // tests. The command line is setting the ack-wait-threshold to be
-  // 60 seconds.
-  private static final int MAX_WAIT = 70 * 1000;
+  private static final String LOCK_SERVICE_NAME = DLockManagementDUnitTest.class.getSimpleName() + "_testLockService";
 
-  public DLockManagementDUnitTest() {
-    super();
+  @Manager
+  private VM managerVM;
 
-  }
+  @Member
+  private VM[] memberVMs;
 
-  /**
-   * Distributed Lock Service test
-   * 
-   * @throws Exception
-   */
-  @Category(FlakyTest.class) // GEODE-173: eats exceptions, HeadlessGFSH, time sensitive, waitForCriterions
-  @Test
-  public void testDLockMBean() throws Throwable {
-    
-    initManagement(false);
-    
-    VM[] managedNodes = new VM[getManagedNodeList()
-        .size()];
-    VM managingNode = getManagingNode();
-    
-    getManagedNodeList().toArray(managedNodes);
-
-    createGrantorLockService(managedNodes[0]);
-
-    createLockService(managedNodes[1]);
-
-    createLockService(managedNodes[2]);
-    
-    for (VM vm : getManagedNodeList()) {
-      verifyLockData(vm);
-    }
-    verifyLockDataRemote(managingNode);
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().managersFirst(false).start(true).build();
 
-    for (VM vm : getManagedNodeList()) {
-      closeLockService(vm);
-    }
-  }
-  
-  /**
-   * Distributed Lock Service test
-   * 
-   * @throws Exception
-   */
-  @Category(FlakyTest.class) // GEODE-553: waitForCriterion, eats exceptions, HeadlessGFSH
   @Test
-  public void testDLockAggregate() throws Throwable {
-    initManagement(false);
-    VM[] managedNodes = new VM[getManagedNodeList()
-        .size()];
-    VM managingNode = getManagingNode();
-    
-    getManagedNodeList().toArray(managedNodes);
-
-    createGrantorLockService(managedNodes[0]);
-
-    createLockService(managedNodes[1]);
-
-    createLockService(managedNodes[2]);
-    
-    checkAggregate(managingNode, 3);
-    DistributedMember member = getMember(managedNodes[2]);
-    checkNavigation(managingNode, member);
-    
-    createLockService(managingNode);
-    checkAggregate(managingNode, 4);
-   
-
-    for (VM vm : getManagedNodeList()) {
-      closeLockService(vm);
+  public void testLockServiceMXBean() throws Throwable {
+    createLockServiceGrantor(this.memberVMs[0]);
+    createLockService(this.memberVMs[1]);
+    createLockService(this.memberVMs[2]);
+
+    for (VM memberVM : this.memberVMs) {
+      verifyLockServiceMXBeanInMember(memberVM);
     }
-    ensureProxyCleanup(managingNode);
-    checkAggregate(managingNode, 1);
-    closeLockService(managingNode);
-    checkAggregate(managingNode, 0);
+    verifyLockServiceMXBeanInManager(this.managerVM);
 
+    for (VM memberVM : this.memberVMs) {
+      closeLockService(memberVM);
+    }
   }
-  
-  public void ensureProxyCleanup(final VM vm) {
-
-    SerializableRunnable ensureProxyCleanup = new SerializableRunnable(
-        "Ensure Proxy cleanup") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet = cache.getDistributionManager()
-            .getOtherNormalDistributionManagerIds();
-        final SystemManagementService service = (SystemManagementService) getManagementService();
- 
-
-        for (final DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
 
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              LockServiceMXBean bean = null;
+  @Test
+  public void testDistributedLockServiceMXBean() throws Throwable {
+    createLockServiceGrantor(this.memberVMs[0]);
+    createLockService(this.memberVMs[1]);
+    createLockService(this.memberVMs[2]);
 
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
+    verifyDistributedLockServiceMXBean(this.managerVM, 3);
 
-              public boolean done() {
-                ObjectName objectName = service.getRegionMBeanName(member, LOCK_SERVICE_NAME);
-                bean = service.getMBeanProxy(objectName, LockServiceMXBean.class);
-                boolean done = (bean == null);
-                return done;
-              }
+    DistributedMember member = this.managementTestRule.getDistributedMember(this.memberVMs[2]);
+    verifyFetchOperations(this.managerVM, member);
 
-            }, MAX_WAIT, 500, true);
+    createLockService(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 4);
 
-          } catch (Exception e) {
-            throw new AssertionError("could not remove proxies in required time", e);
+    for (VM memberVM : this.memberVMs) {
+      closeLockService(memberVM);
+    }
+    verifyProxyCleanupInManager(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 1);
 
-          }
-          assertNull(bean);
+    closeLockService(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 0);
+  }
 
-        }
+  private void verifyProxyCleanupInManager(final VM managerVM) {
+    managerVM.invoke("verifyProxyCleanupInManager", () -> {
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
+      for (final DistributedMember member : otherMembers) {
+        ObjectName objectName = service.getRegionMBeanName(member, LOCK_SERVICE_NAME);
+        await().until(() -> assertThat(service.getMBeanProxy(objectName, LockServiceMXBean.class)).isNull());
       }
-    };
-    vm.invoke(ensureProxyCleanup);
+    });
   }
 
-  /**
-   * Creates a grantor lock service
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void createGrantorLockService(final VM vm) {
-    SerializableRunnable createGrantorLockService = new SerializableRunnable(
-        "Create Grantor LockService") {
-      public void run() {
-        GemFireCacheImpl cache  = GemFireCacheImpl.getInstance();
-        assertNull(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME));
+  private void createLockServiceGrantor(final VM memberVM) {
+    memberVM.invoke("createLockServiceGrantor", () -> {
+      assertThat(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME)).isNull();
 
-        DLockService service = (DLockService) DistributedLockService.create(
-            LOCK_SERVICE_NAME, cache.getDistributedSystem());
+      DLockService lockService = (DLockService) DistributedLockService.create(LOCK_SERVICE_NAME, this.managementTestRule.getCache().getDistributedSystem());
+      DistributedMember grantor = lockService.getLockGrantorId().getLockGrantorMember();
+      assertThat(grantor).isNotNull();
 
-        assertSame(service, DistributedLockService
-            .getServiceNamed(LOCK_SERVICE_NAME));
+      LockServiceMXBean lockServiceMXBean = awaitLockServiceMXBean(LOCK_SERVICE_NAME);
 
-        InternalDistributedMember grantor = service.getLockGrantorId()
-            .getLockGrantorMember();
+      assertThat(lockServiceMXBean).isNotNull();
+      assertThat(lockServiceMXBean.isDistributed()).isTrue();
+      assertThat(lockServiceMXBean.getName()).isEqualTo(LOCK_SERVICE_NAME);
+      assertThat(lockServiceMXBean.isLockGrantor()).isTrue();
+      assertThat(lockServiceMXBean.fetchGrantorMember()).isEqualTo(this.managementTestRule.getDistributedMember().getId());
+    });
+  }
 
-        assertNotNull(grantor);
+  private void createLockService(final VM anyVM) {
+    anyVM.invoke("createLockService", () -> {
+      assertThat(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME)).isNull();
 
-        LogWriterUtils.getLogWriter().info("In identifyLockGrantor - grantor is " + grantor);
+      DistributedLockService.create(LOCK_SERVICE_NAME, this.managementTestRule.getCache().getDistributedSystem());
 
-       
+      LockServiceMXBean lockServiceMXBean = awaitLockServiceMXBean(LOCK_SERVICE_NAME);
 
-        ManagementService mgmtService = getManagementService();
+      assertThat(lockServiceMXBean).isNotNull();
+      assertThat(lockServiceMXBean.isDistributed()).isTrue();
+      assertThat(lockServiceMXBean.isLockGrantor()).isFalse();
+    });
+  }
 
-        LockServiceMXBean bean = mgmtService
-            .getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+  private void closeLockService(final VM anyVM) {
+    anyVM.invoke("closeLockService", () -> {
+      assertThat(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME)).isNotNull();
+      DistributedLockService.destroy(LOCK_SERVICE_NAME);
 
-        assertNotNull(bean);
+      awaitLockServiceMXBeanIsNull(LOCK_SERVICE_NAME);
 
-        assertTrue(bean.isDistributed());
+      ManagementService service = this.managementTestRule.getManagementService();
+      LockServiceMXBean lockServiceMXBean = service.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+      assertThat(lockServiceMXBean).isNull();
+    });
+  }
 
-        assertEquals(bean.getName(), LOCK_SERVICE_NAME);
+  private void verifyLockServiceMXBeanInMember(final VM memberVM) {
+    memberVM.invoke("verifyLockServiceMXBeanInManager", () -> {
+      DistributedLockService lockService = DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME);
+      lockService.lock("lockObject_" + identifyPid(), MAX_WAIT_MILLIS, -1);
 
-        assertTrue(bean.isLockGrantor());
+      ManagementService service = this.managementTestRule.getManagementService();
+      LockServiceMXBean lockServiceMXBean = service.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+      assertThat(lockServiceMXBean).isNotNull();
 
-        assertEquals(cache.getDistributedSystem().getMemberId(), bean
-            .fetchGrantorMember());
+      String[] listHeldLock = lockServiceMXBean.listHeldLocks();
+      assertThat(listHeldLock).hasSize(1);
 
-      }
-    };
-    vm.invoke(createGrantorLockService);
+      Map<String, String> lockThreadMap = lockServiceMXBean.listThreadsHoldingLock();
+      assertThat(lockThreadMap).hasSize(1);
+    });
   }
 
   /**
-   * Creates a named lock service
-   * @param vm
+   * Verify lock data from remote Managing node
    */
-  @SuppressWarnings("serial")
-  protected void createLockService(final VM vm) {
-    SerializableRunnable createLockService = new SerializableRunnable(
-        "Create LockService") {
-      public void run() {
-        assertNull(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME));
-        GemFireCacheImpl cache  = GemFireCacheImpl.getInstance();
-        DistributedLockService service = DistributedLockService.create(
-            LOCK_SERVICE_NAME, cache.getDistributedSystem());
-
-        assertSame(service, DistributedLockService
-            .getServiceNamed(LOCK_SERVICE_NAME));
+  private void verifyLockServiceMXBeanInManager(final VM managerVM) throws Exception {
+    managerVM.invoke("verifyLockServiceMXBeanInManager", () -> {
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
 
-        
+      for (DistributedMember member : otherMembers) {
+        LockServiceMXBean lockServiceMXBean = awaitLockServiceMXBeanProxy(member, LOCK_SERVICE_NAME);
+        assertThat(lockServiceMXBean).isNotNull();
 
-        ManagementService mgmtService = getManagementService();
+        String[] listHeldLock = lockServiceMXBean.listHeldLocks();
+        assertThat(listHeldLock).hasSize(1);
 
-        LockServiceMXBean bean = mgmtService
-            .getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+        Map<String, String> lockThreadMap = lockServiceMXBean.listThreadsHoldingLock();
+        assertThat(lockThreadMap).hasSize(1);
+      }
+    });
+  }
 
-        assertNotNull(bean);
+  private void verifyFetchOperations(final VM memberVM, final DistributedMember member) {
+    memberVM.invoke("verifyFetchOperations", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
 
-        assertTrue(bean.isDistributed());
+      DistributedSystemMXBean distributedSystemMXBean = awaitDistributedSystemMXBean();
+      ObjectName distributedLockServiceMXBeanName = MBeanJMXAdapter.getDistributedLockServiceName(LOCK_SERVICE_NAME);
+      assertThat(distributedSystemMXBean.fetchDistributedLockServiceObjectName(LOCK_SERVICE_NAME)).isEqualTo(distributedLockServiceMXBeanName);
 
-        assertFalse(bean.isLockGrantor());
-      }
-    };
-    vm.invoke(createLockService);
+      ObjectName lockServiceMXBeanName = MBeanJMXAdapter.getLockServiceMBeanName(member.getId(), LOCK_SERVICE_NAME);
+      assertThat(distributedSystemMXBean.fetchLockServiceObjectName(member.getId(), LOCK_SERVICE_NAME)).isEqualTo(lockServiceMXBeanName);
+    });
   }
 
   /**
-   * Closes a named lock service
-   * @param vm
+   * Verify Aggregate MBean
    */
-  @SuppressWarnings("serial")
-  protected void closeLockService(final VM vm) {
-    SerializableRunnable closeLockService = new SerializableRunnable(
-        "Close LockService") {
-      public void run() {
+  private void verifyDistributedLockServiceMXBean(final VM managerVM, final int memberCount) {
+    managerVM.invoke("verifyDistributedLockServiceMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
 
-        DistributedLockService service = DistributedLockService
-            .getServiceNamed(LOCK_SERVICE_NAME);
-
-        DistributedLockService.destroy(LOCK_SERVICE_NAME);
-
-        ManagementService mgmtService = getManagementService();
-
-        LockServiceMXBean bean = null;
-        try {
+      if (memberCount == 0) {
+        await().until(() -> assertThat(service.getDistributedLockServiceMXBean(LOCK_SERVICE_NAME)).isNull());
+        return;
+      }
 
-          bean = mgmtService.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+      DistributedLockServiceMXBean distributedLockServiceMXBean = awaitDistributedLockServiceMXBean(LOCK_SERVICE_NAME, memberCount);
+      assertThat(distributedLockServiceMXBean).isNotNull();
+      assertThat(distributedLockServiceMXBean.getName()).isEqualTo(LOCK_SERVICE_NAME);
+    });
+  }
 
-        } catch (ManagementException mgs) {
+  private DistributedSystemMXBean awaitDistributedSystemMXBean() {
+    ManagementService service = this.managementTestRule.getManagementService();
 
-        }
-        assertNull(bean);
+    await().until(() -> assertThat(service.getDistributedSystemMXBean()).isNotNull());
 
-      }
-    };
-    vm.invoke(closeLockService);
+    return service.getDistributedSystemMXBean();
   }
 
   /**
-   * Lock data related verifications
-   * @param vm
+   * Await and return a DistributedRegionMXBean proxy with specified member
+   * count.
    */
-  @SuppressWarnings("serial")
-  protected void verifyLockData(final VM vm) {
-    SerializableRunnable verifyLockData = new SerializableRunnable(
-        "Verify LockService") {
-      public void run() {
-
-        DistributedLockService service = DistributedLockService
-            .getServiceNamed(LOCK_SERVICE_NAME);
-
-        final String LOCK_OBJECT = "lockObject_" + vm.getPid();
-
-        Wait.waitForCriterion(new WaitCriterion() {
-          DistributedLockService service = null;
-
-          public String description() {
-            return "Waiting for the lock service to be initialised";
-          }
-
-          public boolean done() {
-            DistributedLockService service = DistributedLockService
-                .getServiceNamed(LOCK_SERVICE_NAME);
-            boolean done = service != null;
-            return done;
-          }
-
-        }, MAX_WAIT, 500, true);
+  private DistributedLockServiceMXBean awaitDistributedLockServiceMXBean(final String lockServiceName, final int memberCount) {
+    ManagementService service = this.managementTestRule.getManagementService();
 
-        service.lock(LOCK_OBJECT, 1000, -1);
-        
+    await().until(() -> {
+      assertThat(service.getDistributedLockServiceMXBean(lockServiceName)).isNotNull();
+      assertThat(service.getDistributedLockServiceMXBean(lockServiceName).getMemberCount()).isEqualTo(memberCount);
+    });
 
-        ManagementService mgmtService = getManagementService();
-
-        LockServiceMXBean bean = null;
-        try {
+    return service.getDistributedLockServiceMXBean(lockServiceName);
+  }
 
-          bean = mgmtService.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+  /**
+   * Await and return a LockServiceMXBean proxy for a specific member and
+   * lockServiceName.
+   */
+  private LockServiceMXBean awaitLockServiceMXBeanProxy(final DistributedMember member, final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName lockServiceMXBeanName = service.getLockServiceMBeanName(member, lockServiceName);
 
-        } catch (ManagementException mgs) {
+    await().until(() -> assertThat(service.getMBeanProxy(lockServiceMXBeanName, LockServiceMXBean.class)).isNotNull());
 
-        }
-        assertNotNull(bean);
-        String[] listHeldLock = bean.listHeldLocks();
-        assertEquals(listHeldLock.length, 1);
-        LogWriterUtils.getLogWriter().info("List Of Lock Object is  " + listHeldLock[0]);
-        Map<String, String> lockThreadMap = bean.listThreadsHoldingLock();
-        assertEquals(lockThreadMap.size(), 1);
-        LogWriterUtils.getLogWriter().info(
-            "List Of Lock Thread is  " + lockThreadMap.toString());
-      }
-    };
-    vm.invoke(verifyLockData);
+    return service.getMBeanProxy(lockServiceMXBeanName, LockServiceMXBean.class);
   }
 
   /**
-   * Verify lock data from remote Managing node
-   * @param vm
+   * Await creation of local LockServiceMXBean for specified lockServiceName.
    */
-  @SuppressWarnings("serial")
-  protected void verifyLockDataRemote(final VM vm) {
-    SerializableRunnable verifyLockDataRemote = new SerializableRunnable(
-        "Verify LockService Remote") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet = cache.getDistributionManager()
-            .getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-          LockServiceMXBean bean = null;
-          try {
-            bean = MBeanUtil.getLockServiceMbeanProxy(member, LOCK_SERVICE_NAME);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n().fine(
-                "Undesired Result , LockServiceMBean Should not be null", e);
-
-          }
-          assertNotNull(bean);
-          String[] listHeldLock = bean.listHeldLocks();
-          assertEquals(listHeldLock.length, 1);
-          LogWriterUtils.getLogWriter().info("List Of Lock Object is  " + listHeldLock[0]);
-          Map<String, String> lockThreadMap = bean.listThreadsHoldingLock();
-          assertEquals(lockThreadMap.size(), 1);
-          LogWriterUtils.getLogWriter().info(
-              "List Of Lock Thread is  " + lockThreadMap.toString());
-        }
+  private LockServiceMXBean awaitLockServiceMXBean(final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-      }
-    };
-    vm.invoke(verifyLockDataRemote);
-  }
-  
-  protected void checkNavigation(final VM vm,
-      final DistributedMember lockServiceMember) {
-    SerializableRunnable checkNavigation = new SerializableRunnable(
-        "Check Navigation") {
-      public void run() {
-
-        final ManagementService service = getManagementService();
-
-        DistributedSystemMXBean disMBean = service.getDistributedSystemMXBean();
-        try {
-          ObjectName expected = MBeanJMXAdapter
-              .getDistributedLockServiceName(LOCK_SERVICE_NAME);
-          ObjectName actual = disMBean
-              .fetchDistributedLockServiceObjectName(LOCK_SERVICE_NAME);
-          assertEquals(expected, actual);
-        } catch (Exception e) {
-          throw new AssertionError("Lock Service Navigation Failed ", e);
-        }
-
-        try {
-          ObjectName expected = MBeanJMXAdapter.getLockServiceMBeanName(
-              lockServiceMember.getId(), LOCK_SERVICE_NAME);
-          ObjectName actual = disMBean.fetchLockServiceObjectName(
-              lockServiceMember.getId(), LOCK_SERVICE_NAME);
-          assertEquals(expected, actual);
-        } catch (Exception e) {
-          throw new AssertionError("Lock Service Navigation Failed ", e);
-        }
+    await().until(() -> assertThat(service.getLocalLockServiceMBean(lockServiceName)).isNotNull());
 
-      }
-    };
-    vm.invoke(checkNavigation);
+    return service.getLocalLockServiceMBean(lockServiceName);
   }
 
   /**
-   * Verify Aggregate MBean
-   * @param vm
+   * Await destruction of local LockServiceMXBean for specified
+   * lockServiceName.
    */
-  @SuppressWarnings("serial")
-  protected void checkAggregate(final VM vm, final int expectedMembers) {
-    SerializableRunnable checkAggregate = new SerializableRunnable(
-        "Verify Aggregate MBean") {
-      public void run() {
-        
-        final ManagementService service = getManagementService();
-        if (expectedMembers == 0) {
-          try {
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              DistributedLockServiceMXBean bean = null;
-
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
-
-              public boolean done() {
-                bean = service
-                    .getDistributedLockServiceMXBean(LOCK_SERVICE_NAME);
-
-                boolean done = (bean == null);
-                return done;
-              }
-
-            }, MAX_WAIT, 500, true);
-
-          } catch (Exception e) {
-            throw new AssertionError("could not remove Aggregate Bean in required time", e);
-
-          }
-          return;
-        }
-
-        DistributedLockServiceMXBean bean = null;
-          try {
-            bean = MBeanUtil.getDistributedLockMbean(LOCK_SERVICE_NAME, expectedMembers);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n().fine(
-                "Undesired Result , LockServiceMBean Should not be null", e);
-
-          }
-          assertNotNull(bean);
-          assertEquals(bean.getName(),LOCK_SERVICE_NAME);
-   
-      }
-    };
-    vm.invoke(checkAggregate);
+  private void awaitLockServiceMXBeanIsNull(final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+
+    await().until(() -> assertThat(service.getLocalLockServiceMBean(lockServiceName)).isNull());
+  }
+
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(MAX_WAIT_MILLIS, MILLISECONDS);
   }
 }
+


[2/8] incubator-geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/86a3fb5a/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java
index f042f2c..71359be 100644
--- a/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java
@@ -14,22 +14,46 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package org.apache.geode.management;
 
-import static org.junit.Assert.*;
+import static java.util.concurrent.TimeUnit.MINUTES;
+import static org.apache.geode.cache.Region.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.assertj.core.api.Assertions.*;
 
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
 
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
 import javax.management.Notification;
 import javax.management.NotificationListener;
 import javax.management.ObjectName;
 
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.After;
+import org.junit.Before;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -43,757 +67,505 @@ import org.apache.geode.cache.PartitionAttributes;
 import org.apache.geode.cache.PartitionAttributesFactory;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionAttributes;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
 import org.apache.geode.cache.Scope;
 import org.apache.geode.cache.query.data.Portfolio;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.distributed.internal.DM;
+import org.apache.geode.internal.cache.AbstractRegion;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.LocalRegion;
 import org.apache.geode.internal.cache.TestObjectSizerImpl;
 import org.apache.geode.internal.cache.lru.LRUStatistics;
 import org.apache.geode.internal.cache.partitioned.fixed.SingleHopQuarterPartitionResolver;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.test.dunit.Assert;
 import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.Wait;
 import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
 
 /**
  * This class checks and verifies various data and operations exposed through
  * RegionMXBean interface.
- * 
+ * <p>
  * Goal of the Test : RegionMBean gets created once region is created. Data like
  * Region Attributes data and stats are of proper value
- * 
- * 
  */
 @Category(DistributedTest.class)
+@SuppressWarnings({ "serial", "unused" })
 public class RegionManagementDUnitTest extends ManagementTestBase {
 
-  private static final long serialVersionUID = 1L;
-
-  private final String VERIFY_CONFIG_METHOD = "verifyConfigData";
+  private static final String REGION_NAME = "MANAGEMENT_TEST_REGION";
+  private static final String PARTITIONED_REGION_NAME = "MANAGEMENT_PAR_REGION";
+  private static final String FIXED_PR_NAME = "MANAGEMENT_FIXED_PR";
+  private static final String LOCAL_REGION_NAME = "TEST_LOCAL_REGION";
+  private static final String LOCAL_SUB_REGION_NAME = "TEST_LOCAL_SUB_REGION";
 
-  private final String VERIFY_REMOTE_CONFIG_METHOD = "verifyConfigDataRemote";
+  private static final String REGION_PATH = SEPARATOR + REGION_NAME;
+  private static final String PARTITIONED_REGION_PATH = SEPARATOR + PARTITIONED_REGION_NAME;
+  private static final String FIXED_PR_PATH = SEPARATOR + FIXED_PR_NAME;
+  private static final String LOCAL_SUB_REGION_PATH = SEPARATOR + LOCAL_REGION_NAME + SEPARATOR + LOCAL_SUB_REGION_NAME;
 
-  static final String REGION_NAME = "MANAGEMENT_TEST_REGION";
+  // field used in manager VM
+  private static Region fixedPartitionedRegion;
 
-  static final String PARTITIONED_REGION_NAME = "MANAGEMENT_PAR_REGION";
+  private static final AtomicReference<List<Notification>> MEMBER_NOTIFICATIONS_REF = new AtomicReference<>();
+  private static final AtomicReference<List<Notification>> SYSTEM_NOTIFICATIONS_REF = new AtomicReference<>();
 
-  static final String FIXED_PR_NAME = "MANAGEMENT_FIXED_PR";
-  
-  static final String REGION_PATH = "/MANAGEMENT_TEST_REGION";
+  @Manager
+  private VM managerVM;
 
-  static final String PARTITIONED_REGION_PATH = "/MANAGEMENT_PAR_REGION";
+  @Member
+  private VM[] memberVMs;
 
-  static final String FIXED_PR_PATH = "/MANAGEMENT_FIXED_PR";
-  
-  static final String LOCAL_REGION_NAME = "TEST_LOCAL_REGION";
-  static final String LOCAL_SUB_REGION_NAME = "TEST_LOCAL_SUB_REGION";
-  static final String LOCAL_REGION_PATH = "/TEST_LOCAL_REGION";
-  static final String LOCAL_SUB_REGION_PATH = "/TEST_LOCAL_REGION/TEST_LOCAL_SUB_REGION";
-  
-  private static final int MAX_WAIT = 70 * 1000;
+  @Before
+  public void before() throws Exception {
+    this.managerVM = getHost(0).getVM(0);
 
-  protected static final Region DiskRegion = null;
+    this.memberVMs = new VM[3];
+    this.memberVMs[0] = getHost(0).getVM(1);
+    this.memberVMs[1] = getHost(0).getVM(2);
+    this.memberVMs[2] = getHost(0).getVM(3);
+  }
 
-  static List<FixedPartitionAttributes> fpaList = new ArrayList<FixedPartitionAttributes>();
+  @After
+  public void after() throws Exception {
+    invokeInEveryVM(() -> MEMBER_NOTIFICATIONS_REF.set(null));
+    invokeInEveryVM(() -> SYSTEM_NOTIFICATIONS_REF.set(null));
+    disconnectAllFromDS_tmp();
+  }
 
+  private void createMembersAndThenManagers_tmp() throws Exception {
+    initManagement(false);
+  }
 
-  private static Region fixedPrRegion;
+  private void createManagersAndThenMembers_tmp() throws Exception {
+    initManagement(true);
+  }
 
+  private void disconnectAllFromDS_tmp() {
+    disconnectAllFromDS();
+  }
 
-  public RegionManagementDUnitTest() {
-    super();
+  private ManagementService getManagementService_tmp() {
+    return getManagementService();
+  }
 
+  private Cache getCache_tmp() {
+    return getCache();
   }
 
   /**
    * Tests all Region MBean related Management APIs
-   * 
+   * <p>
    * a) Notification propagated to member MBean while a region is created
-   * 
+   * <p>
    * b) Creates and check a Distributed Region
-   * 
-   * 
-   * @throws Exception
    */
-
-  @Category(FlakyTest.class) // GEODE-1538
   @Test
   public void testDistributedRegion() throws Exception {
+    createMembersAndThenManagers_tmp();
 
-    initManagement(false);
-
-
-    VM[] managedNodes = new VM[getManagedNodeList()
-        .size()];
-
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
-    addMemberListener(managingNode);
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
+    for (VM memberVM : this.memberVMs) {
+      createDistributedRegion_tmp(memberVM, REGION_NAME);
+      verifyReplicateRegionAfterCreate(memberVM);
+    }
 
-      createDistributedRegion(vm, REGION_NAME);
-      validateReplicateRegionAfterCreate(vm);
+    verifyRemoteDistributedRegion(this.managerVM, 3);
 
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
+      verifyReplicatedRegionAfterClose(memberVM);
     }
 
-    verifyRemoteDistributedRegion(managingNode, 3);
+    verifyProxyCleanup(this.managerVM);
 
-
-    for (VM vm : getManagedNodeList()) {
-      closeRegion(vm, REGION_PATH);
-      validateReplicatedRegionAfterClose(vm);
-    }
-    
-    ensureProxyCleanup(managingNode);
+    verifyMemberNotifications(this.managerVM, REGION_NAME, 3);
   }
-  
+
   /**
    * Tests all Region MBean related Management APIs
-   * 
+   * <p>
    * a) Notification propagated to member MBean while a region is created
-   * 
+   * <p>
    * b) Created and check a Partitioned Region
-   * 
-   * @throws Exception
    */
   @Test
   public void testPartitionedRegion() throws Exception {
-    initManagement(false);
-
-    VM managingNode = getManagingNode();
-
-    VM[] managedNodes = new VM[getManagedNodeList()
-        .size()];
-
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
+    createMembersAndThenManagers_tmp();
 
-    addMemberListener(managingNode);
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
-      createPartitionRegion(vm, PARTITIONED_REGION_NAME);
-      validatePartitionRegionAfterCreate(vm);
+    for (VM memberVM : this.memberVMs) {
+      createPartitionRegion_tmp(memberVM, PARTITIONED_REGION_NAME);
+      verifyPartitionRegionAfterCreate(memberVM);
     }
-    
-
-    validateRemotePartitionRegion(managingNode);
 
-    for (VM vm : getManagedNodeList()) {
+    verifyRemotePartitionRegion(this.managerVM);
 
-      closeRegion(vm, PARTITIONED_REGION_PATH);
-      validatePartitionRegionAfterClose(vm);
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, PARTITIONED_REGION_PATH);
+      verifyPartitionRegionAfterClose(memberVM);
     }
+
+    verifyMemberNotifications(this.managerVM, PARTITIONED_REGION_NAME, 3);
   }
-  
+
   /**
    * Tests all Region MBean related Management APIs
-   * 
+   * <p>
    * a) Notification propagated to member MBean while a region is created
-   * 
+   * <p>
    * b) Creates and check a Fixed Partitioned Region
-   * 
-   * @throws Exception
    */
   @Test
   public void testFixedPRRegionMBean() throws Exception {
+    createMembersAndThenManagers_tmp();
 
-    initManagement(false);
-
-    VM managingNode = getManagingNode();
-
-    VM[] managedNodes = new VM[getManagedNodeList()
-        .size()];
-
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
-    addMemberListener(managingNode);
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
+    int primaryIndex = 0;
+    for (VM memberVM : this.memberVMs) {
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(primaryIndex + 1);
+      memberVM.invoke(() -> createFixedPartitionRegion(fixedPartitionAttributesList));
+      primaryIndex++;
+    }
 
-      createFixedPartitionList(j + 1);
-      Object[] args = new Object[1];
-      args[0] = fpaList;
-      vm.invoke(RegionManagementDUnitTest.class, "createFixedPartitionRegion",
-          args);
+//    // TODO: Workaround for bug 46683. Reenable validation when bug is fixed.
+    verifyRemoteFixedPartitionRegion(this.managerVM);
 
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, FIXED_PR_PATH);
     }
-    // Workaround for bug 46683. Renable validation when bug is fixed.
-    validateRemoteFixedPartitionRegion(managingNode);
 
-    for (VM vm : getManagedNodeList()) {
-      closeFixedPartitionRegion(vm);
-    }
+    verifyMemberNotifications(this.managerVM, FIXED_PR_PATH, 3);
   }
 
   /**
    * Tests a Distributed Region at Managing Node side
    * while region is created in a member node asynchronously.
-   * @throws Exception
    */
   @Test
-  public void testRegionAggregate() throws Exception{
-    initManagement(true);
+  public void testRegionAggregate() throws Exception {
+    createManagersAndThenMembers_tmp();
 
-    VM managingNode = getManagingNode();
-
-    VM[] managedNodes = new VM[getManagedNodeList()
-        .size()];
-
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
-    addDistrListener(managingNode);
-
-
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
-
-      createDistributedRegion(vm, REGION_NAME);
+    // Adding notification listener for remote cache memberVMs
+    addSystemNotificationListener(this.managerVM); // TODO: why?
 
+    for (VM memberVM : this.memberVMs) {
+      createDistributedRegion_tmp(memberVM, REGION_NAME);
     }
 
-    
-    validateDistributedMBean(managingNode, 3);
-    
-    createDistributedRegion(managingNode, REGION_NAME);
-    validateDistributedMBean(managingNode, 4);
-    
-
-
-    for (int j = 0; j < managedNodes.length; j++) {
+    verifyDistributedMBean(this.managerVM, 3);
+    createDistributedRegion_tmp(this.managerVM, REGION_NAME);
+    verifyDistributedMBean(this.managerVM, 4);
 
-      VM vm = managedNodes[j];
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
+    }
 
-      closeRegion(vm, REGION_PATH);
+    verifyProxyCleanup(this.managerVM);
 
-    }
-    ensureProxyCleanup(managingNode);
-    
-    validateDistributedMBean(managingNode, 1);
-    
-    closeRegion(managingNode, REGION_PATH);
-    validateDistributedMBean(managingNode, 0);
-    
+    verifyDistributedMBean(this.managerVM, 1);
+    closeRegion(this.managerVM, REGION_PATH);
+    verifyDistributedMBean(this.managerVM, 0);
 
+    verifySystemNotifications(this.managerVM, REGION_NAME, 3);
   }
-  
+
   @Test
   public void testNavigationAPIS() throws Exception {
-    initManagement(true);
-    for(VM vm : managedNodeList){
-      createDistributedRegion(vm, REGION_NAME);
-      createPartitionRegion(vm, PARTITIONED_REGION_NAME);
-    }
-    createDistributedRegion(managingNode, REGION_NAME);
-    createPartitionRegion(managingNode, PARTITIONED_REGION_NAME);
-    List<String> memberIds = new ArrayList<String>();
-    
-    for(VM vm : managedNodeList){
-      memberIds.add(getMemberId(vm));
+    createManagersAndThenMembers_tmp();
+
+    for (VM memberVM : this.memberVMs) {
+      createDistributedRegion_tmp(memberVM, REGION_NAME);
+      createPartitionRegion_tmp(memberVM, PARTITIONED_REGION_NAME);
     }
-    checkNavigationAPIS(managingNode, memberIds);
-    
 
+    createDistributedRegion_tmp(this.managerVM, REGION_NAME);
+    createPartitionRegion_tmp(this.managerVM, PARTITIONED_REGION_NAME);
+    List<String> memberIds = new ArrayList<>();
 
-    for(VM vm : managedNodeList){
-      closeRegion(vm, REGION_PATH);
+    for (VM memberVM : this.memberVMs) {
+      memberIds.add(getDistributedMemberId_tmp(memberVM));
     }
- 
-    closeRegion(managingNode, REGION_PATH);
 
-  }
+    verifyNavigationApis(this.managerVM, memberIds);
 
- 
-  
-  @Test
-  public void testSubRegions() throws Exception{
-    initManagement(false);
-    for (VM vm : managedNodeList) {
-      createLocalRegion(vm, LOCAL_REGION_NAME);
-      createSubRegion(vm, LOCAL_REGION_NAME, LOCAL_SUB_REGION_NAME);
-    }
-    
-    for (VM vm : managedNodeList) {
-      checkSubRegions(vm, LOCAL_SUB_REGION_PATH);
-    }
-    
-    for (VM vm : managedNodeList) {
-      closeRegion(vm, LOCAL_REGION_NAME);
-      checkNullRegions(vm, LOCAL_SUB_REGION_NAME);
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
     }
-    
+    closeRegion(this.managerVM, REGION_PATH);
   }
-  
-  
-  
-  
+
   @Test
-  public void testSpecialRegions() throws Exception{
-    initManagement(false);
-    createSpecialRegion(managedNodeList.get(0));
-    DistributedMember member = getMember(managedNodeList.get(0));
-    checkSpecialRegion(managingNode,member);
-  }
-  
-  
-  public void createSpecialRegion(VM vm1) throws Exception{
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
-          Cache cache = getCache();
-          AttributesFactory attributesFactory = new AttributesFactory();
-          attributesFactory.setValueConstraint(Portfolio.class);
-          RegionAttributes regionAttributes = attributesFactory.create();
-          
-          cache.createRegion("p-os",regionAttributes);
-          cache.createRegion("p_os",regionAttributes);
-        }
-      });
+  public void testSubRegions() throws Exception {
+    createMembersAndThenManagers_tmp();
 
+    for (VM memberVM : this.memberVMs) {
+      createLocalRegion_tmp(memberVM, LOCAL_REGION_NAME);
+      createSubRegion_tmp(memberVM, LOCAL_REGION_NAME, LOCAL_SUB_REGION_NAME);
     }
-  }
-  
-  public void checkSpecialRegion(VM vm1, final DistributedMember member)
-      throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
-
-          ManagementService service = getManagementService();
-          
-          try {
-            MBeanUtil.getDistributedRegionMbean("/p-os", 1);
-            MBeanUtil.getDistributedRegionMbean("/p_os", 1);
-
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n().fine(
-                "Undesired Result , DistributedRegionMXBean Should not be null"
-                    + e);
-          }
-
-        }
-      });
 
+    for (VM memberVM : this.memberVMs) {
+      verifySubRegions(memberVM, LOCAL_SUB_REGION_PATH);
     }
 
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, LOCAL_REGION_NAME);
+      verifyNullRegions(memberVM, LOCAL_SUB_REGION_NAME);
+    }
   }
-  
+
   @Test
-  public void testLruStats() throws Exception{
-    initManagement(false);
-    for (VM vm : managedNodeList) {
-      createDiskRegion(vm);
+  public void testSpecialRegions() throws Exception {
+    createMembersAndThenManagers_tmp();
+    createSpecialRegion(this.memberVMs[0]);
+    verifySpecialRegion(this.managerVM);
+  }
 
+  @Test
+  public void testLruStats() throws Exception {
+    createMembersAndThenManagers_tmp();
+    for (VM memberVM : this.memberVMs) {
+      createDiskRegion(memberVM);
     }
-    checkEntrySize(managingNode,3);
+    verifyEntrySize(this.managerVM, 3);
   }
-  
-  public void createDiskRegion(VM vm1) throws Exception{
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
-          AttributesFactory factory = new AttributesFactory();
-          factory.setScope(Scope.LOCAL);
-          factory.setEvictionAttributes(EvictionAttributes
-                .createLRUMemoryAttributes(20, new TestObjectSizerImpl(),
-                    EvictionAction.LOCAL_DESTROY));
-          /*File d = new File("DiskRegions" + OSProcess.getId());
-          d.mkdirs();
-
-          DiskStoreFactory dsf = getCache().createDiskStoreFactory();
-          dsf.setDiskDirs(new File[]{d});
-          factory.setDiskSynchronous(true);
-          DiskStore ds = dsf.create(REGION_NAME);
-          factory.setDiskStoreName(ds.getName());
-*/
-          Region region = getCache().createRegion(REGION_NAME, factory.create());
-
-          LRUStatistics lruStats = getLRUStats(region);
-
-          assertNotNull(lruStats);
-          
-          RegionMXBean bean = managementService.getLocalRegionMBean(REGION_PATH);
-          
-          assertNotNull(bean);
-          
-          int total;
-          for (total = 0; total < 10000; total++) {
-            int[] array = new int[250];
-            array[0] = total;
-            region.put(new Integer(total), array);
-          }
-          assertTrue(bean.getEntrySize() > 0);
-          LogWriterUtils.getLogWriter().info("DEBUG: EntrySize =" + bean.getEntrySize());
-          
 
+  private void closeRegion(final VM anyVM, final String regionPath) {
+    anyVM.invoke("closeRegion", () -> getCache_tmp().getRegion(regionPath).close());
+  }
 
-        }
-      });
+  private void createSpecialRegion(final VM memberVM) throws Exception {
+    memberVM.invoke("createSpecialRegion", () -> {
+      AttributesFactory attributesFactory = new AttributesFactory();
+      attributesFactory.setValueConstraint(Portfolio.class);
+      RegionAttributes regionAttributes = attributesFactory.create();
 
-    }
-    
+      Cache cache = getCache_tmp();
+      cache.createRegion("p-os", regionAttributes);
+      cache.createRegion("p_os", regionAttributes);
+    });
   }
 
-  public void checkEntrySize(VM vm1, final int expectedMembers)
-      throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
+  private void verifySpecialRegion(final VM managerVM) throws Exception {
+    managerVM.invoke("verifySpecialRegion", () -> {
+      awaitDistributedRegionMXBean("/p-os", 1); // TODO: why?
+      awaitDistributedRegionMXBean("/p_os", 1);
+    });
+  }
 
-        public void run() {
+  private void createDiskRegion(final VM memberVM) throws Exception {
+    memberVM.invoke("createDiskRegion", () -> {
+      AttributesFactory factory = new AttributesFactory();
+      factory.setScope(Scope.LOCAL);
+      factory.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes(20, new TestObjectSizerImpl(), EvictionAction.LOCAL_DESTROY));
 
-          DistributedRegionMXBean bean = null;
-          try {
-            bean = MBeanUtil.getDistributedRegionMbean(REGION_PATH,
-                expectedMembers);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n().fine(
-                "Undesired Result , DistributedRegionMXBean Should not be null"
-                    + e);
-          }
+      Region region = getCache_tmp().createRegion(REGION_NAME, factory.create());
 
-          assertNotNull(bean);
+      LRUStatistics lruStats = ((AbstractRegion) region).getEvictionController().getLRUHelper().getStats();
+      assertThat(lruStats).isNotNull();
 
-          assertTrue(bean.getEntrySize() > 0);
-          LogWriterUtils.getLogWriter().info("DEBUG: EntrySize =" + bean.getEntrySize());
-        }
-      });
+      RegionMXBean regionMXBean = getManagementService_tmp().getLocalRegionMBean(REGION_PATH);
+      assertThat(regionMXBean).isNotNull();
 
-    }
+      int total;
+      for (total = 0; total < 10000; total++) { // TODO: why so many?
+        int[] array = new int[250];
+        array[0] = total;
+        region.put(new Integer(total), array);
+      }
+      assertThat(regionMXBean.getEntrySize()).isGreaterThan(0);
+    });
+  }
 
+  private void verifyEntrySize(final VM managerVM, final int expectedMembers) throws Exception {
+    managerVM.invoke("verifyEntrySize", () -> {
+      DistributedRegionMXBean distributedRegionMXBean = awaitDistributedRegionMXBean(REGION_PATH, expectedMembers);
+      assertThat(distributedRegionMXBean).isNotNull();
+      assertThat(distributedRegionMXBean.getEntrySize()).isGreaterThan(0);
+    });
   }
-  
-  protected LRUStatistics getLRUStats(Region region) {
-    final LocalRegion l = (LocalRegion) region;
-    return l.getEvictionController().getLRUHelper().getStats();
+
+  private void verifySubRegions(final VM memberVM, final String subRegionPath) throws Exception {
+    memberVM.invoke("verifySubRegions", () -> {
+      RegionMXBean regionMXBean = getManagementService_tmp().getLocalRegionMBean(subRegionPath);
+      assertThat(regionMXBean).isNotNull();
+    });
   }
-  
-  @SuppressWarnings("serial")
-  public void checkSubRegions(VM vm1, final String subRegionPath) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
 
-        public void run() {
+  private void verifyNullRegions(final VM memberVM, final String subRegionPath) throws Exception {
+    memberVM.invoke("verifyNullRegions", () -> {
+      RegionMXBean regionMXBean = getManagementService_tmp().getLocalRegionMBean(subRegionPath);
+      assertThat(regionMXBean).isNull();
+    });
+  }
 
-          RegionMXBean bean = managementService
-              .getLocalRegionMBean(subRegionPath);
-          assertNotNull(bean);
+  private void verifyNavigationApis(final VM managerVM, final List<String> memberIds) {
+    managerVM.invoke("verifyNavigationApis", () -> {
+      ManagementService service = getManagementService_tmp();
+      assertThat(service.getDistributedSystemMXBean()).isNotNull();
 
-        }
-      });
+      awaitMemberCount(4);
 
-    }
-  }
-  
-  @SuppressWarnings("serial")
-  public void checkNullRegions(VM vm1, final String subRegionPath) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      assertThat(distributedSystemMXBean.listDistributedRegionObjectNames()).hasSize(2);
 
-        public void run() {
+      assertThat(distributedSystemMXBean.fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH)).isNotNull();
+      assertThat(distributedSystemMXBean.fetchDistributedRegionObjectName(REGION_PATH)).isNotNull();
 
-          RegionMXBean bean = managementService
-              .getLocalRegionMBean(subRegionPath);
-          assertNull(bean);
+      ObjectName actualName = distributedSystemMXBean.fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH);
+      ObjectName expectedName = MBeanJMXAdapter.getDistributedRegionMbeanName(PARTITIONED_REGION_PATH);
+      assertThat(actualName).isEqualTo(expectedName);
 
-        }
-      });
+      actualName = distributedSystemMXBean.fetchDistributedRegionObjectName(REGION_PATH);
+      expectedName = MBeanJMXAdapter.getDistributedRegionMbeanName(REGION_PATH);
+      assertThat(actualName).isEqualTo(expectedName);
 
-    }
-  }
+      for (String memberId : memberIds) {
+        ObjectName objectName = MBeanJMXAdapter.getMemberMBeanName(memberId);
+        awaitMemberMXBeanProxy(objectName);
 
-  
-  
-  
-  protected void checkNavigationAPIS(final VM vm,
-      final List<String> managedNodeMemberIds) {
-    SerializableRunnable checkNavigationAPIS = new SerializableRunnable(
-        "checkNavigationAPIS") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        ManagementService service = getManagementService();
-        final DistributedSystemMXBean bean = service
-            .getDistributedSystemMXBean();
-
-        assertNotNull(service.getDistributedSystemMXBean());
-
-        waitForAllMembers(4);
-        assertTrue(bean.listDistributedRegionObjectNames().length == 2);
-        try {
-          assertNotNull(bean
-              .fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH));
-          assertNotNull(bean.fetchDistributedRegionObjectName(REGION_PATH));
-          ObjectName actualName = bean
-              .fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH);
-          ObjectName expectedName = MBeanJMXAdapter
-              .getDistributedRegionMbeanName(PARTITIONED_REGION_PATH);
-          assertEquals(expectedName, actualName);
-
-          actualName = bean.fetchDistributedRegionObjectName(REGION_PATH);
-          expectedName = MBeanJMXAdapter
-              .getDistributedRegionMbeanName(REGION_PATH);
-          assertEquals(expectedName, actualName);
-
-        } catch (Exception e) {
-          fail("fetchDistributedRegionObjectName () Unsuccessful " + e);
-        }
+        ObjectName[] objectNames = distributedSystemMXBean.fetchRegionObjectNames(objectName);
+        assertThat(objectNames).isNotNull();
+        assertThat(objectNames).hasSize(2);
 
-        for (String memberId : managedNodeMemberIds) {
-          ObjectName memberMBeanName = MBeanJMXAdapter
-              .getMemberMBeanName(memberId);
-          ObjectName expectedName;
-          try {
-            waitForProxy(memberMBeanName, MemberMXBean.class);
-            
-            ObjectName[] regionMBeanNames = bean
-                .fetchRegionObjectNames(memberMBeanName);
-            assertNotNull(regionMBeanNames);
-            assertTrue(regionMBeanNames.length == 2);
-            List<ObjectName> listOfNames = Arrays.asList(regionMBeanNames);
-
-            expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId,
-                PARTITIONED_REGION_PATH);
-            listOfNames.contains(expectedName);
-            expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId,
-                REGION_PATH);
-            listOfNames.contains(expectedName);
-          } catch (Exception e) {
-            fail("fetchRegionObjectNames () Unsuccessful " + e);
-          }
-        }
+        List<ObjectName> listOfNames = Arrays.asList(objectNames);
 
-        for (String memberId : managedNodeMemberIds) {
-          ObjectName expectedName;
-          ObjectName actualName;
-          ObjectName memberMBeanName = MBeanJMXAdapter
-          .getMemberMBeanName(memberId);
-          try {
-            waitForProxy(memberMBeanName, MemberMXBean.class);
-            expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId,
-                PARTITIONED_REGION_PATH);
-            waitForProxy(expectedName, RegionMXBean.class);
-            actualName = bean.fetchRegionObjectName(memberId,
-                PARTITIONED_REGION_PATH);
-
-            assertEquals(expectedName, actualName);
-            expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId,
-                REGION_PATH);
-            waitForProxy(expectedName, RegionMXBean.class);
-            actualName = bean.fetchRegionObjectName(memberId, REGION_PATH);
-
-            assertEquals(expectedName, actualName);
-          } catch (Exception e) {
-            fail("fetchRegionObjectName () Unsuccessful ");
-          }
-        }
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, PARTITIONED_REGION_PATH);
+        assertThat(listOfNames).contains(expectedName);
 
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, REGION_PATH);
+        assertThat(listOfNames).contains(expectedName);
       }
-    };
-    vm.invoke(checkNavigationAPIS);
-  }
-  
-  
-  protected void putBulkData(final VM vm, final int numKeys) {
-    SerializableRunnable putBulkData = new SerializableRunnable("putBulkData") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Region region = cache.getRegion(REGION_PATH);
-        for (int i = 0; i < numKeys; i++) {
-          region.put(i, i * i);
-        }
 
+      for (String memberId : memberIds) {
+        ObjectName objectName = MBeanJMXAdapter.getMemberMBeanName(memberId);
+        awaitMemberMXBeanProxy(objectName);
+
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, PARTITIONED_REGION_PATH);
+        awaitRegionMXBeanProxy(expectedName);
+
+        actualName = distributedSystemMXBean.fetchRegionObjectName(memberId, PARTITIONED_REGION_PATH);
+        assertThat(actualName).isEqualTo(expectedName);
+
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, REGION_PATH);
+        awaitRegionMXBeanProxy(expectedName);
+
+        actualName = distributedSystemMXBean.fetchRegionObjectName(memberId, REGION_PATH);
+        assertThat(actualName).isEqualTo(expectedName);
       }
-    };
-    vm.invoke(putBulkData);
+    });
   }
- 
-  
 
   /**
-   * creates a Fixed Partition List to be used for Fixed Partition Region
-   * 
-   * @param primaryIndex
-   *          index for each fixed partition
+   * Invoked in controller VM
    */
-  private static void createFixedPartitionList(int primaryIndex) {
-    fpaList.clear();
+  private List<FixedPartitionAttributes> createFixedPartitionList(final int primaryIndex) {
+    List<FixedPartitionAttributes> fixedPartitionAttributesList = new ArrayList<>();
     if (primaryIndex == 1) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q1", true, 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
     }
     if (primaryIndex == 2) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q2", true, 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
     }
     if (primaryIndex == 3) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", true, 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q3", true, 3));
     }
-
+    return fixedPartitionAttributesList;
   }
-  
-
 
   /**
-   * Creates a Fixed Partitioned Region
-   * @param fpaList partition list
+   * Invoked in member VMs
    */
-  protected static void createFixedPartitionRegion(
-      List<FixedPartitionAttributes> fpaList) {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    SystemManagementService service = (SystemManagementService)getManagementService();
+  private void createFixedPartitionRegion(final List<FixedPartitionAttributes> fixedPartitionAttributesList) {
+    SystemManagementService service = getSystemManagementService_tmp();
 
-    PartitionAttributesFactory paf = new PartitionAttributesFactory();
+    PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
 
-    paf.setRedundantCopies(2).setTotalNumBuckets(12);
-    for (FixedPartitionAttributes fpa : fpaList) {
-      paf.addFixedPartitionAttributes(fpa);
+    partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
+    for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+      partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
     }
-    paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
-
-    AttributesFactory attr = new AttributesFactory();
-    attr.setPartitionAttributes(paf.create());
-    fixedPrRegion = cache.createRegion(FIXED_PR_NAME, attr.create());
-    assertNotNull(fixedPrRegion);
-    LogWriterUtils.getLogWriter().info(
-        "Partitioned Region " + FIXED_PR_NAME + " created Successfully :"
-            + fixedPrRegion.toString());
+    partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
 
-    RegionMXBean bean = service.getLocalRegionMBean(FIXED_PR_PATH);
-    RegionAttributes regAttrs = fixedPrRegion.getAttributes();
+    AttributesFactory attributesFactory = new AttributesFactory();
+    attributesFactory.setPartitionAttributes(partitionAttributesFactory.create());
 
-    LogWriterUtils.getLogWriter().info(
-        "FixedPartitionAttribute From GemFire :"
-            + regAttrs.getPartitionAttributes().getFixedPartitionAttributes());
+    fixedPartitionedRegion = getCache_tmp().createRegion(FIXED_PR_NAME, attributesFactory.create());
+    assertThat(fixedPartitionedRegion).isNotNull();
 
-    RegionAttributesData data = bean.listRegionAttributes();
+    RegionMXBean regionMXBean = service.getLocalRegionMBean(FIXED_PR_PATH);
+    RegionAttributes regionAttributes = fixedPartitionedRegion.getAttributes();
 
-    PartitionAttributesData parData = bean.listPartitionAttributes();
+    PartitionAttributesData partitionAttributesData = regionMXBean.listPartitionAttributes();
+    verifyPartitionData(regionAttributes, partitionAttributesData);
 
-    assertPartitionData(regAttrs, parData);
+    FixedPartitionAttributesData[] fixedPartitionAttributesData = regionMXBean.listFixedPartitionAttributes();
+    assertThat(fixedPartitionAttributesData).isNotNull();
+    assertThat(fixedPartitionAttributesData).hasSize(3);
 
-    FixedPartitionAttributesData[] fixedPrData = bean
-        .listFixedPartitionAttributes();
-
-    assertNotNull(fixedPrData);
-
-    assertEquals(3, fixedPrData.length);
-    for (int i = 0; i < fixedPrData.length; i++) {
-      LogWriterUtils.getLogWriter().info(
-          "<ExpectedString> Fixed PR Data is " + fixedPrData[i]
-              + "</ExpectedString> ");
+    for (int i = 0; i < fixedPartitionAttributesData.length; i++) {
+      //LogWriterUtils.getLogWriter().info("<ExpectedString> Fixed PR Data is " + fixedPartitionAttributesData[i] + "</ExpectedString> ");
     }
   }
 
-  /**
-   * Verifies the Fixed Partition Region for partition related attributes
-   * 
-   * @param vm
-   */
-  protected void validateRemoteFixedPartitionRegion(final VM vm) throws Exception {
-    SerializableRunnable verifyFixedRegion = new SerializableRunnable(
-        "Verify Partition region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet = cache.getDistributionManager()
-            .getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-            bean = MBeanUtil.getRegionMbeanProxy(member, FIXED_PR_PATH);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n().fine(
-                "Undesired Result , RegionMBean Should not be null");
-          }
-          PartitionAttributesData data = bean.listPartitionAttributes();
-          assertNotNull(data);
-          FixedPartitionAttributesData[] fixedPrData = bean
-              .listFixedPartitionAttributes();
-          assertNotNull(fixedPrData);
-          assertEquals(3, fixedPrData.length);
-          for (int i = 0; i < fixedPrData.length; i++) {
-            LogWriterUtils.getLogWriter().info(
-                "<ExpectedString> Remote PR Data is " + fixedPrData[i]
-                    + "</ExpectedString> ");
-          }
-        }
-
+//  /**
+//   * Invoked in manager VM
+//   */
+//  private void verifyRemoteFixedPartitionRegion(final VM vm) throws Exception {
+//    vm.invoke("Verify Partition region", () -> {
+//      Set<DistributedMember> otherMemberSet = getDistributionManager_tmp().getOtherNormalDistributionManagerIds();
+//
+//      for (DistributedMember member : otherMemberSet) {
+//        RegionMXBean regionMXBean = awaitRegionMXBeanProxy(member, FIXED_PR_PATH);
+//
+//        PartitionAttributesData partitionAttributesData = regionMXBean.listPartitionAttributes();
+//        assertNotNull(partitionAttributesData);
+//
+//        FixedPartitionAttributesData[] fixedPartitionAttributesData = regionMXBean.listFixedPartitionAttributes();
+//        assertNotNull(fixedPartitionAttributesData);
+//        assertEquals(3, fixedPartitionAttributesData.length);
+//
+//        for (int i = 0; i < fixedPartitionAttributesData.length; i++) {
+//          //LogWriterUtils.getLogWriter().info("<ExpectedString> Remote PR Data is " + fixedPartitionAttributesData[i] + "</ExpectedString> ");
+//        }
+//      }
+//    });
+//  }
+
+  private void addMemberNotificationListener(final VM managerVM, final int expectedMembers) {
+    managerVM.invoke("addMemberNotificationListener", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+      assertThat(otherMemberSet).hasSize(expectedMembers);
+
+      SystemManagementService service = getSystemManagementService_tmp();
+
+      List<Notification> notifications = new ArrayList<>();
+      MEMBER_NOTIFICATIONS_REF.set(notifications);
+
+      for (DistributedMember member : otherMemberSet) {
+        MemberNotificationListener listener = new MemberNotificationListener(notifications);
+        ObjectName objectName = service.getMemberMBeanName(member);
+        awaitMemberMXBeanProxy(objectName);
+
+        ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener, null, null);
       }
-
-    };
-    vm.invoke(verifyFixedRegion);
-  }
-
-  /**
-   * Add a Notification listener to MemberMBean 
-   * @param vm
-   */
-  protected void addMemberListener(final VM vm) {
-    SerializableRunnable addMemberListener = new SerializableRunnable(
-        "addMemberListener") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        
-        SystemManagementService service = (SystemManagementService) getManagementService();
-
-        Set<DistributedMember> otherMemberSet = cache.getDistributionManager()
-            .getOtherNormalDistributionManagerIds();
-         
-        for (DistributedMember member : otherMemberSet) {
-          
-          MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-
-          RegionNotif regionCreate = new RegionNotif();
-
-          ObjectName memberMBeanName;
-          try {
-            memberMBeanName = service.getMemberMBeanName(member);
-            Set<ObjectName> names = service.queryMBeanNames(member);
-            if(names != null){
-              for(ObjectName name : names){
-                LogWriterUtils.getLogWriter().info(
-                    "<ExpectedString> ObjectNames arr" + name
-                        + "</ExpectedString> ");
-              }
-            }
-            waitForProxy(memberMBeanName, MemberMXBean.class);
-            mbeanServer.addNotificationListener(memberMBeanName, regionCreate,
-                null, null);
-          } catch (NullPointerException e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          } catch (InstanceNotFoundException e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          } catch (Exception e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          }
-
-        }
-
-      }
-    };
-    vm.invoke(addMemberListener);
-
+    });
   }
 
   /**
@@ -801,651 +573,557 @@ public class RegionManagementDUnitTest extends ManagementTestBase {
    * all the notifications which are propagated through all individual
    * MemberMBeans Hence Region created/destroyed should be visible to this
    * listener
-   * 
-   * @param vm
    */
-  protected void addDistrListener(final VM vm) {
-    SerializableRunnable addDistrListener = new SerializableRunnable(
-        "addDistrListener") {
-      public void run() {
-        MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
+  private void addSystemNotificationListener(final VM managerVM) {
+    managerVM.invoke("addSystemNotificationListener", () -> {
+      awaitDistributedSystemMXBean();
 
-        DistrNotif regionCreate = new DistrNotif();
+      List<Notification> notifications = new ArrayList<>();
+      SYSTEM_NOTIFICATIONS_REF.set(notifications);
 
-        ObjectName systemMBeanName;
-        try {
-          systemMBeanName = MBeanJMXAdapter.getDistributedSystemName();
-          mbeanServer.addNotificationListener(systemMBeanName, regionCreate,
-              null, null);
-
-        } catch (NullPointerException e) {
-          Assert.fail("FAILED WITH EXCEPION", e);
-        } catch (InstanceNotFoundException e) {
-          Assert.fail("FAILED WITH EXCEPION", e);
+      DistributedSystemNotificationListener listener = new DistributedSystemNotificationListener(notifications);
+      ObjectName objectName = MBeanJMXAdapter.getDistributedSystemName();
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener, null, null);
+    });
+  }
 
+  private void verifyMemberNotifications(final VM managerVM, final String regionName, final int expectedMembers) {
+    managerVM.invoke("verifyMemberNotifications", () -> {
+      assertThat(MEMBER_NOTIFICATIONS_REF.get()).isNotNull();
+      assertThat(MEMBER_NOTIFICATIONS_REF.get()).hasSize(expectedMembers * 2);
+
+      int regionCreatedCount = 0;
+      int regionDestroyedCount = 0;
+      for (Notification notification : MEMBER_NOTIFICATIONS_REF.get()) {
+        if (JMXNotificationType.REGION_CREATED.equals(notification.getType())) {
+          regionCreatedCount++;
+          assertThat(notification.getMessage()).contains(regionName);
+        } else if (JMXNotificationType.REGION_CLOSED.equals(notification.getType())) {
+          regionDestroyedCount++;
+          assertThat(notification.getMessage()).contains(regionName);
+        } else {
+          fail("Unexpected notification type: " + notification.getType());
         }
-
       }
-    };
-    vm.invoke(addDistrListener);
 
+      assertThat(regionCreatedCount).isEqualTo(expectedMembers);
+      assertThat(regionDestroyedCount).isEqualTo(expectedMembers);
+    });
   }
-  
-  public void ensureProxyCleanup(final VM vm) {
-
-    SerializableRunnable ensureProxyCleanup = new SerializableRunnable(
-        "Ensure Proxy cleanup") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet = cache.getDistributionManager()
-            .getOtherNormalDistributionManagerIds();
-
-        final SystemManagementService service = (SystemManagementService) getManagementService();
-
-        for (final DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              RegionMXBean bean = null;
-
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
-
-              public boolean done() {
-                ObjectName objectName = service.getRegionMBeanName(member, REGION_PATH);
-                bean = service.getMBeanProxy(objectName, RegionMXBean.class);
-                boolean done = (bean == null);
-                return done;
-              }
-
-            }, MAX_WAIT, 500, true);
-
-          } catch (Exception e) {
-            fail("could not remove proxies in required time");
-
-          }
-          assertNull(bean);
 
+  //  <[javax.management.Notification[source=10.118.33.232(17632)<v1>-32770][type=gemfire.distributedsystem.cache.region.created][message=Region Created With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=10.118.33.232(17633)<v2>-32771][type=gemfire.distributedsystem.cache.region.created][message=Region Created With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=10.118.33.232(17634)<v3>-32772][type=gemfire.distributedsystem.cache.region.created][message=Region Created With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=10.118.33.232(17632)<v1>-32770][type=gemfire.distributedsystem.cache.region.closed][message=Region Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=10.118.33.232(17633)<v2>-32771][type=gemfire.distributedsystem.cache.region.closed][message=Region Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=10.118.33.232(17634)<v3>-32772][type=gemfire.distributedsystem.cache.region.closed][message=Region Destroyed/Closed With Name /MANAGEMENT_TEST_REGION]]>
+
+  private void verifySystemNotifications(final VM managerVM, final String regionName, final int expectedMembers) {
+    managerVM.invoke("verifySystemNotifications", () -> {
+      assertThat(SYSTEM_NOTIFICATIONS_REF.get()).isNotNull();
+      assertThat(SYSTEM_NOTIFICATIONS_REF.get()).hasSize(expectedMembers + 2); // 2 for the manager
+
+
+      int regionCreatedCount = 0;
+      int regionDestroyedCount = 0;
+      for (Notification notification : SYSTEM_NOTIFICATIONS_REF.get()) {
+        if (JMXNotificationType.REGION_CREATED.equals(notification.getType())) {
+          regionCreatedCount++;
+          assertThat(notification.getMessage()).contains(regionName);
+        } else if (JMXNotificationType.REGION_CLOSED.equals(notification.getType())) {
+          regionDestroyedCount++;
+          assertThat(notification.getMessage()).contains(regionName);
+        } else {
+          fail("Unexpected notification type: " + notification.getType());
         }
-
       }
-    };
-    vm.invoke(ensureProxyCleanup);
+
+      assertThat(regionCreatedCount).isEqualTo(1); // just the manager
+      assertThat(regionDestroyedCount).isEqualTo(expectedMembers + 1); // all 3 members + manager
+    });
   }
 
-  /**
-   * Verifies a Remote Distributed Region
-   * 
-   * @param vm
-   */
-  protected void verifyRemoteDistributedRegion(final VM vm, final int expectedMembers) throws Exception {
-    SerializableRunnable verifyRegion = new SerializableRunnable(
-        "Verify Distributed region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet = cache.getDistributionManager()
-            .getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-            bean = MBeanUtil.getRegionMbeanProxy(member, REGION_PATH);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n().fine(
-                "Undesired Result , RegionMBean Should not be null" + e);
-
-          }
-          assertNotNull(bean);
-
-          RegionAttributesData data = bean.listRegionAttributes();
-          assertNotNull(data);
-          MembershipAttributesData membershipData = bean
-              .listMembershipAttributes();
-          EvictionAttributesData evictionData = bean.listEvictionAttributes();
-          assertNotNull(membershipData);
-          assertNotNull(evictionData);
-          LogWriterUtils.getLogWriter().info(
-              "<ExpectedString> Membership Data is "
-                  + membershipData.toString() + "</ExpectedString> ");
-          LogWriterUtils.getLogWriter().info(
-              "<ExpectedString> Eviction Data is " + membershipData.toString()
-                  + "</ExpectedString> ");
- 
-        }
-        DistributedRegionMXBean bean = null;
-        try {
-          bean = MBeanUtil.getDistributedRegionMbean(REGION_PATH, expectedMembers);
-        } catch (Exception e) {
-          InternalDistributedSystem.getLoggerI18n().fine(
-              "Undesired Result , DistributedRegionMXBean Should not be null"
-                  + e);
-        }
+  //  <[javax.management.Notification[source=192.168.1.72(18496)<v27>-32770][type=gemfire.distributedsystem.cache.region.created][message=Region Created With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=192.168.1.72(18497)<v28>-32771][type=gemfire.distributedsystem.cache.region.closed][message=Region Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=192.168.1.72(18498)<v29>-32772][type=gemfire.distributedsystem.cache.region.closed][message=Region Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=192.168.1.72(18499)<v30>-32773][type=gemfire.distributedsystem.cache.region.closed][message=Region Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  //  javax.management.Notification[source=192.168.1.72(18496)<v27>-32770][type=gemfire.distributedsystem.cache.region.closed][message=Region Destroyed/Closed With Name /MANAGEMENT_TEST_REGION]]>
 
-        assertNotNull(bean);
-        assertEquals(REGION_PATH, bean.getFullPath());
-        
+  private void verifyProxyCleanup(final VM managerVM) {
+    managerVM.invoke("verifyProxyCleanup", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
 
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+      for (final DistributedMember member : otherMemberSet) {
+        String alias = "Waiting for the proxy to get deleted at managing node";
+        await(alias).until(() -> assertThat(service.getMBeanProxy(service.getRegionMBeanName(member, REGION_PATH), RegionMXBean.class)).isNull());
       }
-    };
-    vm.invoke(verifyRegion);
+    });
   }
 
-  
-  protected void validateDistributedMBean(final VM vm, final int expectedMembers) {
-    SerializableRunnable verifyRegion = new SerializableRunnable(
-        "Verify Distributed region") {
-      public void run() {
-        DistributedRegionMXBean bean = null;
-        DistributedSystemMXBean sysMBean = null;
-        final ManagementService service = getManagementService();
-
-        if (expectedMembers == 0) {
-          try {
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              RegionMXBean bean = null;
+  private void verifyRemoteDistributedRegion(final VM managerVM, final int expectedMembers) throws Exception {
+    managerVM.invoke("verifyRemoteDistributedRegion", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+      assertThat(otherMemberSet).hasSize(expectedMembers);
 
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
+      for (DistributedMember member : otherMemberSet) {
+        RegionMXBean regionMXBean = awaitRegionMXBeanProxy(member, REGION_PATH);
 
-              public boolean done() {
-                DistributedRegionMXBean bean = service
-                    .getDistributedRegionMXBean(REGION_PATH);
-                boolean done = (bean == null);
-                return done;
-              }
+        RegionAttributesData regionAttributesData = regionMXBean.listRegionAttributes();
+        assertThat(regionAttributesData).isNotNull();
 
-            }, MAX_WAIT, 500, true);
+        MembershipAttributesData membershipAttributesData = regionMXBean.listMembershipAttributes();
+        assertThat(membershipAttributesData).isNotNull();
 
-          } catch (Exception e) {
-            fail("could not remove Aggregate Bean in required time");
-
-          }
-          return;
-        }
+        EvictionAttributesData evictionAttributesData = regionMXBean.listEvictionAttributes();
+        assertThat(evictionAttributesData).isNotNull();
+      }
 
-        try {
-          bean = MBeanUtil.getDistributedRegionMbean(REGION_PATH,
-              expectedMembers);
-          sysMBean = service.getDistributedSystemMXBean();
-        } catch (Exception e) {
-          InternalDistributedSystem.getLoggerI18n().fine(
-              "Undesired Result , DistributedRegionMXBean Should not be null"
-                  + e);
-        }
+      DistributedRegionMXBean distributedRegionMXBean = awaitDistributedRegionMXBean(REGION_PATH, expectedMembers);
 
-        assertNotNull(bean);
-        assertEquals(REGION_PATH, bean.getFullPath());
-        assertEquals(expectedMembers, bean.getMemberCount());
-        assertEquals(expectedMembers, bean.getMembers().length);
-
-        // Check Stats related Data
-        // Add Mock testing
-        LogWriterUtils.getLogWriter()
-            .info(
-                "<ExpectedString> CacheListenerCallsAvgLatency is "
-                    + bean.getCacheListenerCallsAvgLatency()
-                    + "</ExpectedString> ");
-        LogWriterUtils.getLogWriter().info(
-            "<ExpectedString> CacheWriterCallsAvgLatency is "
-                + bean.getCacheWriterCallsAvgLatency() + "</ExpectedString> ");
-        LogWriterUtils.getLogWriter().info(
-            "<ExpectedString> CreatesRate is " + bean.getCreatesRate()
-                + "</ExpectedString> ");
+      assertThat(distributedRegionMXBean).isNotNull();
+      assertThat(distributedRegionMXBean.getFullPath()).isEqualTo(REGION_PATH);
+    });
+  }
 
+  private void verifyDistributedMBean(final VM managerVM, final int expectedMembers) {
+    managerVM.invoke("verifyDistributedMBean", () -> {
+      if (expectedMembers == 0) {
+        ManagementService service = getManagementService_tmp();
+        String alias = "Waiting for the proxy to get deleted at managing node";
+        await(alias).until(() -> assertThat(service.getDistributedRegionMXBean(REGION_PATH)).isNull());
+        return;
       }
-    };
-    // Test DistributedRegionMXBean
 
-    vm.invoke(verifyRegion);
-  }
-  /**
-   * Verifies a Remote Partition Region
-   * 
-   * @param vm
-   */
-  protected void validateRemotePartitionRegion(final VM vm) throws Exception {
-    SerializableRunnable verifyRegion = new SerializableRunnable(
-        "Verify Partition region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet = cache.getDistributionManager()
-            .getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-            bean = MBeanUtil.getRegionMbeanProxy(member,
-                PARTITIONED_REGION_PATH);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n().fine(
-                "Undesired Result , RegionMBean Should not be null");
-          }
-          PartitionAttributesData data = bean.listPartitionAttributes();
-          assertNotNull(data);
-        }
-        
-        ManagementService service = getManagementService();
-        DistributedRegionMXBean bean = service.getDistributedRegionMXBean(PARTITIONED_REGION_PATH);
-        assertEquals(3,bean.getMembers().length);
+      DistributedRegionMXBean distributedRegionMXBean = awaitDistributedRegionMXBean(REGION_PATH, expectedMembers);
 
-      }
+      assertThat(distributedRegionMXBean.getFullPath()).isEqualTo(REGION_PATH);
+      assertThat(distributedRegionMXBean.getMemberCount()).isEqualTo(expectedMembers);
+      assertThat(distributedRegionMXBean.getMembers()).hasSize(expectedMembers);
 
-    };
-    vm.invoke(verifyRegion);
+      // Check Stats related Data
+      //LogWriterUtils.getLogWriter().info("<ExpectedString> CacheListenerCallsAvgLatency is " + distributedRegionMXBean.getCacheListenerCallsAvgLatency() + "</ExpectedString> ");
+      //LogWriterUtils.getLogWriter().info("<ExpectedString> CacheWriterCallsAvgLatency is " + distributedRegionMXBean.getCacheWriterCallsAvgLatency() + "</ExpectedString> ");
+      //LogWriterUtils.getLogWriter().info("<ExpectedString> CreatesRate is " + distributedRegionMXBean.getCreatesRate() + "</ExpectedString> ");
+    });
   }
 
+  private void verifyRemotePartitionRegion(final VM managerVM) throws Exception {
+    managerVM.invoke("verifyRemotePartitionRegion", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
 
-  
-  
-
-  /**
-   * Creates a Distributed Region
-   * 
-   * @param vm
-   */
-  protected void validateReplicateRegionAfterCreate(final VM vm) {
-    SerializableRunnable checkDistributedRegion = new SerializableRunnable(
-        "Check Distributed region") {
-      public void run() {
+      for (DistributedMember member : otherMemberSet) {
+        RegionMXBean regionMXBean = awaitRegionMXBeanProxy(member, PARTITIONED_REGION_PATH);
+        PartitionAttributesData partitionAttributesData = regionMXBean.listPartitionAttributes();
+        assertThat(partitionAttributesData).isNotNull();
+      }
 
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService)getManagementService();
+      ManagementService service = getManagementService_tmp();
+      DistributedRegionMXBean distributedRegionMXBean = service.getDistributedRegionMXBean(PARTITIONED_REGION_PATH);
+      assertThat(distributedRegionMXBean.getMembers()).hasSize(3);
+    });
+  }
 
-        MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-        RegionNotif test = new RegionNotif();
+  private void verifyReplicateRegionAfterCreate(final VM memberVM) {
+    memberVM.invoke("verifyReplicateRegionAfterCreate", () -> {
+      Cache cache = getCache_tmp();
 
-        String memberId = MBeanJMXAdapter.getMemberNameOrId(cache
-            .getDistributedSystem().getDistributedMember());
+      String memberId = MBeanJMXAdapter.getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());
+      ObjectName objectName = ObjectName.getInstance("GemFire:type=Member,member=" + memberId);
 
-        ObjectName memberMBeanName;
-        try {
-          memberMBeanName = ObjectName
-              .getInstance("GemFire:type=Member,member=" + memberId);
-          mbeanServer
-              .addNotificationListener(memberMBeanName, test, null, null);
-        } catch (MalformedObjectNameException e) {
+//      List<Notification> notifications = new ArrayList<>();
+//      MEMBER_NOTIFICATIONS_REF.set(notifications);
+//
+//      MemberNotificationListener listener = new MemberNotificationListener(notifications);
+//      ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener, null, null);
 
-          Assert.fail("FAILED WITH EXCEPION", e);
-        } catch (NullPointerException e) {
-          Assert.fail("FAILED WITH EXCEPION", e);
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(REGION_PATH);
+      assertThat(regionMXBean).isNotNull();
 
-        } catch (InstanceNotFoundException e) {
-          Assert.fail("FAILED WITH EXCEPION", e);
+      Region region = cache.getRegion(REGION_PATH);
+      RegionAttributes regionAttributes = region.getAttributes();
 
-        }
+      RegionAttributesData regionAttributesData = regionMXBean.listRegionAttributes();
+      verifyRegionAttributes(regionAttributes, regionAttributesData);
 
-        assertNotNull(service.getLocalRegionMBean(REGION_PATH));
+      MembershipAttributesData membershipData = regionMXBean.listMembershipAttributes();
+      assertThat(membershipData).isNotNull();
 
-        RegionMXBean bean = service.getLocalRegionMBean(REGION_PATH);
-        Region region = cache.getRegion(REGION_PATH);
+      EvictionAttributesData evictionData = regionMXBean.listEvictionAttributes();
+      assertThat(evictionData).isNotNull();
+    });
+  }
 
-        RegionAttributes regAttrs = region.getAttributes();
+  private void verifyPartitionRegionAfterCreate(final VM memberVM) {
+    memberVM.invoke("verifyPartitionRegionAfterCreate", () -> {
+      Region region = getCache_tmp().getRegion(PARTITIONED_REGION_PATH);
 
-        RegionAttributesData data = bean.listRegionAttributes();
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
 
-        assertRegionAttributes(regAttrs, data);
-        MembershipAttributesData membershipData = bean
-            .listMembershipAttributes();
-        EvictionAttributesData evictionData = bean.listEvictionAttributes();
-        assertNotNull(membershipData);
-        assertNotNull(evictionData);
-        LogWriterUtils.getLogWriter().info(
-            "<ExpectedString> Membership Data is " + membershipData.toString()
-                + "</ExpectedString> ");
-        LogWriterUtils.getLogWriter().info(
-            "<ExpectedString> Eviction Data is " + membershipData.toString()
-                + "</ExpectedString> ");
-      }
-    };
-    vm.invoke(checkDistributedRegion);
+      verifyPartitionData(region.getAttributes(), regionMXBean.listPartitionAttributes());
+    });
   }
 
-  /**
-   * Creates a partition Region
-   * 
-   * @param vm
-   */
-  protected void validatePartitionRegionAfterCreate(final VM vm) {
-    SerializableRunnable createParRegion = new SerializableRunnable(
-        "Create Partitioned region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService)getManagementService();
-        assertNotNull(service.getLocalRegionMBean(PARTITIONED_REGION_PATH));
-        RegionMXBean bean = service
-            .getLocalRegionMBean(PARTITIONED_REGION_PATH);
-        Region partitionedRegion = cache.getRegion(PARTITIONED_REGION_PATH);
-        RegionAttributes regAttrs = partitionedRegion.getAttributes();
-        RegionAttributesData data = bean.listRegionAttributes();
-        PartitionAttributesData parData = bean.listPartitionAttributes();
-        assertPartitionData(regAttrs, parData);
-        
-      }
-    };
-    vm.invoke(createParRegion);
-  }
+  private void verifyReplicatedRegionAfterClose(final VM memberVM) {
+    memberVM.invoke("verifyReplicatedRegionAfterClose", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(REGION_PATH);
+      assertThat(regionMXBean).isNull();
 
-  /**
-   * closes a Distributed Region
-   * 
-   * @param vm
-   */
-  protected void validateReplicatedRegionAfterClose(final VM vm) {
-    SerializableRunnable closeRegion = new SerializableRunnable(
-        "Close Distributed region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService)getManagementService();
-        RegionMXBean bean = null;
-        try {
-          bean = service.getLocalRegionMBean(REGION_PATH);
-        } catch (ManagementException mgtEx) {
-          LogWriterUtils.getLogWriter().info(
-              "<ExpectedString> Expected Exception  "
-                  + mgtEx.getLocalizedMessage() + "</ExpectedString> ");
-        }
-        assertNull(bean);
-        ObjectName regionObjectName = service.getRegionMBeanName(cache
-            .getDistributedSystem().getDistributedMember(), REGION_PATH);
-        assertNull(service.getLocalManager().getManagementResourceRepo()
-            .getEntryFromLocalMonitoringRegion(regionObjectName));
-      }
-    };
-    vm.invoke(closeRegion);
+      ObjectName objectName = service.getRegionMBeanName(getCache_tmp().getDistributedSystem().getDistributedMember(), REGION_PATH);
+      assertThat(service.getLocalManager().getManagementResourceRepo().getEntryFromLocalMonitoringRegion(objectName)).isNull();
+    });
   }
 
-  /**
-   * close a partition Region
-   * 
-   * @param vm
-   */
-  protected void validatePartitionRegionAfterClose(final VM vm) {
-    SerializableRunnable closeParRegion = new SerializableRunnable(
-        "Close Partition region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        ManagementService service = getManagementService();
-        LogWriterUtils.getLogWriter().info("Closing Par Region");
-        RegionMXBean bean = null;
-        try {
-          bean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
-        } catch (ManagementException mgtEx) {
-          LogWriterUtils.getLogWriter().info(
-              "<ExpectedString> Expected Exception  "
-                  + mgtEx.getLocalizedMessage() + "</ExpectedString> ");
-        }
-        assertNull(bean);
-      }
-    };
-    vm.invoke(closeParRegion);
+  private void verifyPartitionRegionAfterClose(final VM memberVM) {
+    memberVM.invoke("verifyPartitionRegionAfterClose", () -> {
+      ManagementService service = getManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
+      assertThat(regionMXBean).isNull();
+    });
   }
 
   /**
-   * Closes Fixed Partition region
-   * 
-   * @param vm
-   */
-  protected void closeFixedPartitionRegion(final VM vm) {
-    SerializableRunnable closeParRegion = new SerializableRunnable(
-        "Close Fixed Partition region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        ManagementService service = getManagementService();
-        LogWriterUtils.getLogWriter().info("Closing Fixed Par Region");
-        Region region = cache.getRegion(FIXED_PR_PATH);
-        region.close();
-        RegionMXBean bean = null;
-        try {
-          bean = service.getLocalRegionMBean(FIXED_PR_PATH);
-        } catch (ManagementException mgtEx) {
-          LogWriterUtils.getLogWriter().info(
-              "<ExpectedString> Expected Exception  "
-                  + mgtEx.getLocalizedMessage() + "</ExpectedString> ");
-        }
-        assertNull(bean);
-      }
-    };
-    vm.invoke(closeParRegion);
-  }
-
-  /**
-   * Asserts and verifies all the partition related data
-   * 
-   * @param regAttrs
-   * @param partitionAttributesData
+   * Invoked in member VMs
    */
+  private void verifyPartitionData(final RegionAttributes expectedRegionAttributes, final PartitionAttributesData partitionAttributesData) {
+    PartitionAttributes expectedPartitionAttributes = expectedRegionAttributes.getPartitionAttributes();
 
-  protected static void assertPartitionData(RegionAttributes regAttrs,
-      PartitionAttributesData partitionAttributesData) {
-    PartitionAttributesData data = partitionAttributesData;
+    assertThat(partitionAttributesData.getRedundantCopies()).isEqualTo(expectedPartitionAttributes.getRedundantCopies());
 
-    PartitionAttributes partAttrs = regAttrs.getPartitionAttributes();
+    assertThat(partitionAttributesData.getTotalMaxMemory()).isEqualTo(expectedPartitionAttributes.getTotalMaxMemory());
 
-    int redundantCopies = partAttrs.getRedundantCopies();
-    assertEquals(redundantCopies, data.getRedundantCopies());
-    long totalMaxMemory = partAttrs.getTotalMaxMemory();
-    assertEquals(totalMaxMemory, data.getTotalMaxMemory());
     // Total number of buckets for whole region
-    int totalNumBuckets = partAttrs.getTotalNumBuckets();
-    assertEquals(totalNumBuckets, data.getTotalNumBuckets());
+    assertThat(partitionAttributesData.getTotalNumBuckets()).isEqualTo(expectedPartitionAttributes.getTotalNumBuckets());
 
-    int localMaxMemory = partAttrs.getLocalMaxMemory();
-    assertEquals(localMaxMemory, data.getLocalMaxMemory());
+    assertThat(partitionAttributesData.getLocalMaxMemory()).isEqualTo(expectedPartitionAttributes.getLocalMaxMemory());
 
-    String colocatedWith = partAttrs.getColocatedWith();
-    assertEquals(colocatedWith, data.getColocatedWith());
+    assertThat(partitionAttributesData.getColocatedWith()).isEqualTo(expectedPartitionAttributes.getColocatedWith());
 
     String partitionResolver = null;
-    if (partAttrs.getPartitionResolver() != null) {
-      partitionResolver = partAttrs.getPartitionResolver().getName();
+    if (expectedPartitionAttributes.getPartitionResolver() != null) { // TODO: these conditionals should be deterministic
+      partitionResolver = expectedPartitionAttributes.getPartitionResolver().getName();
     }
+    assertThat(partitionAttributesData.getPartitionResolver()).isEqualTo(partitionResolver);
 
-    assertEquals(partitionResolver, data.getPartitionResolver());
+    assertThat(partitionAttributesData.getRecoveryDelay()).isEqualTo(expectedPartitionAttributes.getRecoveryDelay());
 
-    long recoveryDelay = partAttrs.getRecoveryDelay();
-    assertEquals(recoveryDelay, data.getRecoveryDelay());
+    assertThat(partitionAttributesData.getStartupRecoveryDelay()).isEqualTo(expectedPartitionAttributes.getStartupRecoveryDelay());
 
-    long startupRecoveryDelay = partAttrs.getStartupRecoveryDelay();
-    assertEquals(startupRecoveryDelay, data.getStartupRecoveryDelay());
+    if (expectedPartitionAttributes.getPartitionListeners() != null) {
+      for (int i = 0; i < expectedPartitionAttributes.getPartitionListeners().length; i++) {
+        //assertEquals((expectedPartitionAttributes.getPartitionListeners())[i].getClass().getCanonicalName(), partitionAttributesData.getPartitionListeners()[i]);
+        assertThat(partitionAttributesData.getPartitionListeners()[i])
+          .isEqualTo(expectedPartitionAttributes.getPartitionListeners()[i].getClass().getCanonicalName());
 
-    if (partAttrs.getPartitionListeners() != null) {
-      for (int i = 0; i < partAttrs.getPartitionListeners().length; i++) {
-        assertEquals((partAttrs.getPartitionListeners())[i].getClass()
-            .getCanonicalName(), data.getPartitionListeners()[i]);
       }
-
     }
-
   }
 
   /**
-   * Checks all Region Attributes
-   * 
-   * @param regAttrs
-   * @param data
+   * Invoked in member VMs
    */
-  protected static void assertRegionAttributes(RegionAttributes regAttrs,
-      RegionAttributesData data) {
-
+  private void verifyRegionAttributes(final RegionAttributes regionAttributes, final RegionAttributesData regionAttributesData) {
     String compressorClassName = null;
-    if (regAttrs.getCompressor() != null) {
-      compressorClassName = regAttrs.getCompressor().getClass()
-          .getCanonicalName();
+    if (regionAttributes.getCompressor() != null) { // TODO: these conditionals should be deterministic
+      compressorClassName = regionAttributes.getCompressor().getClass().getCanonicalName();
     }
-    assertEquals(compressorClassName, data.getCompressorClassName());
+    assertThat(regionAttributesData.getCompressorClassName()).isEqualTo(compressorClassName);
+
     String cacheLoaderClassName = null;
-    if (regAttrs.getCacheLoader() != null) {
-      cacheLoaderClassName = regAttrs.getCacheLoader().getClass()
-          .getCanonicalName();
+    if (regionAttributes.getCacheLoader() != null) {
+      cacheLoaderClassName = regionAttributes.getCacheLoader().getClass().getCanonicalName();
     }
-    assertEquals(cacheLoaderClassName, data.getCacheLoaderClassName());
+    assertThat(regionAttributesData.getCacheLoaderClassName()).isEqualTo(cacheLoaderClassName);
+
     String cacheWriteClassName = null;
-    if (regAttrs.getCacheWriter() != null) {
-      cacheWriteClassName = regAttrs.getCacheWriter().getClass()
-          .getCanonicalName();
+    if (regionAttributes.getCacheWriter() != null) {
+      cacheWriteClassName = regionAttributes.getCacheWriter().getClass().getCanonicalName();
     }
-    assertEquals(cacheWriteClassName, data.getCacheWriterClassName());
+    assertThat(regionAttributesData.getCacheWriterClassName()).isEqualTo(cacheWriteClassName);
+
     String keyConstraintClassName = null;
-    if (regAttrs.getKeyConstraint() != null) {
-      keyConstraintClassName = regAttrs.getKeyConstraint().getName();
+    if (regionAttributes.getKeyConstraint() != null) {
+      keyConstraintClassName = regionAttributes.getKeyConstraint().getName();
     }
-    assertEquals(keyConstraintClassName, data.getKeyConstraintClassName());
+    assertThat(regionAttributesData.getKeyConstraintClassName()).isEqualTo(keyConstraintClassName);
+
     String valueContstaintClassName = null;
-    if (regAttrs.getValueConstraint() != null) {
-      valueContstaintClassName = regAttrs.getValueConstraint().getName();
+    if (regionAttributes.getValueConstraint() != null) {
+      valueContstaintClassName = regionAttributes.getValueConstraint().getName();
     }
-    assertEquals(valueContstaintClassName, data.getValueConstraintClassName());
-    CacheListener[] listeners = regAttrs.getCacheListeners();
-    
+    assertThat(regionAttributesData.getValueConstraintClassName()).isEqualTo(valueContstaintClassName);
 
+    CacheListener[] listeners = regionAttributes.getCacheListeners();
     if (listeners != null) {
-      String[] value = data.getCacheListeners();
+      String[] value = regionAttributesData.getCacheListeners();
       for (int i = 0; i < listeners.length; i++) {
-        assertEquals(value[i], listeners[i].getClass().getName());
+        assertThat(listeners[i].getClass().getName()).isEqualTo(value[i]);
       }
-      
     }
-    
- 
-    
-
-    int regionTimeToLive = regAttrs.getRegionTimeToLive().getTimeout();
-
-    assertEquals(regionTimeToLive, data.getRegionTimeToLive());
-
-    int regionIdleTimeout = regAttrs.getRegionIdleTimeout().getTimeout();
 
-    assertEquals(regionIdleTimeout, data.getRegionIdleTimeout());
+    assertThat(regionAttributesData.getRegionTimeToLive()).isEqualTo(regionAttributes.getRegionTimeToLive().getTimeout());
 
-    int entryTimeToLive = regAttrs.getEntryTimeToLive().getTimeout();
+    assertThat(regionAttributesData.getRegionIdleTimeout()).isEqualTo(regionAttributes.getRegionIdleTimeout().getTimeout());
 
-    assertEquals(entryTimeToLive, data.getEntryTimeToLive());
+    assertThat(regionAttributesData.getEntryTimeToLive()).isEqualTo(regionAttributes.getEntryTimeToLive().getTimeout());
 
-    int entryIdleTimeout = regAttrs.getEntryIdleTimeout().getTimeout();
+    assertThat(regionAttributesData.getEntryIdleTimeout()).isEqualTo(regionAttributes.getEntryIdleTimeout().getTimeout());
 
-    assertEquals(entryIdleTimeout, data.getEntryIdleTimeout());
     String customEntryTimeToLive = null;
-    Object o1 = regAttrs.getCustomEntryTimeToLive();
+    Object o1 = regionAttributes.getCustomEntryTimeToLive();
     if (o1 != null) {
       customEntryTimeToLive = o1.toString();
     }
-    assertEquals(customEntryTimeToLive, data.getCustomEntryTimeToLive());
+    assertThat(regionAttributesData.getCustomEntryTimeToLive()).isEqualTo(customEntryTimeToLive);
 
     String customEntryIdleTimeout = null;
-    Object o2 = regAttrs.getCustomEntryIdleTimeout();
+    Object o2 = regionAttributes.getCustomEntryIdleTimeout();
     if (o2 != null) {
       customEntryIdleTimeout = o2.toString();
     }
-    assertEquals(customEntryIdleTimeout, data.getCustomEntryIdleTimeout());
+    assertThat(regionAttributesData.getCustomEntryIdleTimeout()).isEqualTo(customEntryIdleTimeout);
 
-    boolean ignoreJTA = regAttrs.getIgnoreJTA();
-    assertEquals(ignoreJTA, data.isIgnoreJTA());
+    assertThat(regionAttributesData.isIgnoreJTA()).isEqualTo(regionAttributes.getIgnoreJTA());
 
-    String dataPolicy = regAttrs.getDataPolicy().toString();
-    assertEquals(dataPolicy, data.getDataPolicy());
+    assertThat(regionAttributesData.getDataPolicy()).isEqualTo(regionAttributes.getDataPolicy().toString());
 
-    String scope = regAttrs.getScope().toString();
-    assertEquals(scope, data.getScope());
+    assertThat(regionAttributesData.getScope()).isEqualTo(regionAttributes.getScope().toString());
 
-    int initialCapacity = regAttrs.getInitialCapacity();
-    assertEquals(initialCapacity, data.getInitialCapacity());
-    float loadFactor = regAttrs.getLoadFactor();
-    assertEquals(loadFactor, data.getLoadFactor(),0);
+    assertThat(regionAttributesData.getInitialCapacity()).isEqualTo(regionAttributes.getInitialCapacity());
 
-    boolean lockGrantor = regAttrs.isLockGrantor();
-    assertEquals(lockGrantor, data.isLockGrantor());
+    assertThat(regionAttributesData.getLoadFactor()).isEqualTo(regionAttributes.getLoadFactor());
 
-    boolean multicastEnabled = regAttrs.getMulticastEnabled();
-    assertEquals(multicastEnabled, data.isMulticastEnabled());
+    assertThat(regionAttributesData.isLockGrantor()).isEqualTo(regionAttributes.isLockGrantor());
 
-    int concurrencyLevel = regAttrs.getConcurrencyLevel();
-    assertEquals(concurrencyLevel, data.getConcurrencyLevel());
+    assertThat(regionAttributesData.isMulticastEnabled()).isEqualTo(regionAttributes.getMulticastEnabled());
 
-    boolean indexMaintenanceSynchronous = regAttrs
-        .getIndexMaintenanceSynchronous();
-    assertEquals(indexMaintenanceSynchronous, data
-        .isIndexMaintenanceSynchronous());
+    assertThat(regionAttributesData.getConcurrencyLevel()).isEqualTo(regionAttributes.getConcurrencyLevel());
 
-    boolean statisticsEnabled = regAttrs.getStatisticsEnabled();
+    assertThat(regionAttributesData.isIndexMaintenanceSynchronous()).isEqualTo(regionAttributes.getIndexMaintenanceSynchronous());
 
-    assertEquals(statisticsEnabled, data.isStatisticsEnabled());
+    assertThat(regionAttributesData.isStatisticsEnabled()).isEqualTo(regionAttributes.getStatisticsEnabled());
 
-    boolean subsciptionConflationEnabled = regAttrs
-        .getEnableSubscriptionConflation();
-    assertEquals(subsciptionConflationEnabled, data
-        .isSubscriptionConflationEnabled());
+    assertThat(regionAttributesData.isSubscriptionConflationEnabled()).isEqualTo(regionAttributes.getEnableSubscriptionConflation());
 
-    boolean asyncConflationEnabled = regAttrs.getEnableAsyncConflation();
-    assertEquals(asyncConflationEnabled, data.isAsyncConflationEnabled());
+    assertThat(regionAttributesData.isAsyncConflationEnabled()).isEqualTo(regionAttributes.getEnableAsyncConflation());
 
-    String poolName = regAttrs.getPoolName();
-    assertEquals(poolName, data.getPoolName());
+    assertThat(regionAttributesData.getPoolName()).isEqualTo(regionAttributes.getPoolName());
 
-    boolean isCloningEnabled = regAttrs.getCloningEnabled();
-    assertEquals(isCloningEnabled, data.isCloningEnabled());
+    assertThat(regionAttributesData.isCloningEnabled()).isEqualTo(regionAttributes.getCloningEnabled());
 
-    String diskStoreName = regAttrs.getDiskStoreName();
-    assertEquals(diskStoreName, data.getDiskStoreName());
+    assertThat(regionAttributesData.getDiskStoreName()).isEqualTo(regionAttributes.getDiskStoreName());
 
     String interestPolicy = null;
-    if (regAttrs.getSubscriptionAttributes() != null) {
-      interestPolicy = regAttrs.getSubscriptionAttributes().getInterestPolicy()
-          .toString();
+    if (regionAttributes.getSubscriptionAttributes() != null) {
+      interestPolicy = regionAttributes.getSubscriptionAttributes().getInterestPolicy().toString();
     }
-    assertEquals(interestPolicy, data.getInterestPolicy());
-    boolean diskSynchronus = regAttrs.isDiskSynchronous();
-    assertEquals(diskSynchronus, data.isDiskSynchronous());
+    assertThat(regionAttributesData.getInterestPolicy()).isEqualTo(interestPolicy);
+
+    assertThat(regionAttributesData.isDiskSynchronous()).isEqualTo(regionAttributes.isDiskSynchronous());
   }
 
-  /**
-   * Verifies Region related Statistics
-   */
-  public void verifyStatistics() {
+  private void verifyRemoteFixedPartitionRegion(final VM managerVM) throws Exception {
+    managerVM.invoke("Verify Partition region", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+
+      for (DistributedMember member : otherMemberSet) {
+        RegionMXBean bean = awaitRegionMXBeanProxy(member, FIXED_PR_PATH);
+
+        PartitionAttributesData data = bean.listPartitionAttributes();
+        assertThat(data).isNotNull();
+
+        FixedPartitionAttributesData[] fixedPrData = bean.listFixedPartitionAttributes();
+        assertThat(fixedPrData).isNotNull();
+        assertThat(fixedPrData).hasSize(3);
+
+        for (int i = 0; i < fixedPrData.length; i++) {
+          //LogWriterUtils.getLogWriter().info("<ExpectedString> Remote PR Data is " + fixedPrData[i] + "</ExpectedString> ");
+        }
+      }
+    });
+  }
+
+  private void createDistributedRegion_tmp(final VM vm, final String regionName) {
+    vm.invoke(() -> createDistributedRegion_tmp(regionName));
+  }
+
+  private void createDistributedRegion_tmp(final String regionName) {
+    getCache_tmp().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
+  }
+
+  private void createPartitionRegion_tmp(final VM vm, final String partitionRegionName) {
+    vm.invoke("Create Partitioned region", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionFactory regionFactory = getCache_tmp().createRegionFactory(RegionShortcut.PARTITION_REDUNDANT);
+      regionFactory.create(partitionRegionName);
+    });
+  }
+
+  private void createLocalRegion_tmp(final VM vm, final String localRegionName) {
+    vm.invoke("Create Local region", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionFactory regionFactory = getCache_tmp().createRegionFactory(RegionShortcut.LOCAL);
+      regionFactory.create(localRegionName);
+    });
+  }
+
+  private void createSubRegion_tmp(final VM vm, final String parentRegionPath, final String subregionName) {
+    vm.invoke("Create Sub region", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      Region region = getCache_tmp().getRegion(parentRegionPath);
+      region.createSubregion(subregionName, region.getAttributes());
+    });
+  }
+
+  private String getDistributedMemberId_tmp(final VM vm) {
+    return vm.invoke("getMemberId", () -> getCache_tmp().getDistributedSystem().getDistributedMember().getId());
+  }
+
+  private DistributedMember getDistributedMember_tmp(final VM anyVM) {
+    return anyVM.invoke("getDistributedMember_tmp", () -> getCache_tmp().getDistributedSystem().getDistributedMember());
+  }
+
+  private SystemManagementService getSystemManagementService_tmp() {
+    return (SystemManagementService) getManagementService_tmp();
+  }
 
+  private DM getDistributionManager_tmp() {
+    return ((GemFireCacheImpl)getCache_tmp()).getDistributionManager();
   }
 
+  private DistributedMember getDistributedMember_tmp() {
+    return getCache_tmp().getDistributedSystem().getDistributedMember();
+  }
+
+  private Set<DistributedMember> getOtherNormalMembers_tmp() {
+    Set<DistributedMember> allMembers = new HashSet<>(getDistributionManager_tmp().getNormalDistributionManagerIds());
+    allMembers.remove(getDistributedMember_tmp());
+    return allMembers;
+  }
+
+  private void awaitMemberCount(final int expectedCount) {
+    DistributedSystemMXBean distributedSystemMXBean = awaitDistributedSystemMXBean();
+    await().until(() -> assertThat(distributedSystemMXBean.getMemberCount()).isEqualTo(expectedCount));
+  }
+
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name) {
+    SystemManagementService service = getSystemManagementService_tmp();
+
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
+
+    return service.getDistributedRegionMXBean(name);
+  }
+
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name, final int memberCount) {
+    SystemManagementService service = getSystemManagementService_tmp();
+
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name).getMemberCount()).isEqualTo(memberCount));
+
+    return service.getDistributedRegionMXBean(name);
+  }
+
+  private RegionMXBean awaitRegionMXBeanProxy(final DistributedMember member, final String name) {
+    SystemManagementService service = getSystemManagementService_tmp();
+    ObjectName objectName = service.getRegionMBeanName(member, name);
+    String alias = "awaiting RegionMXBean proxy for " + member;
+
+    await(alias).until(() -> assertThat(service.getMBeanProxy(objectName, RegionMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, RegionMXBean.class);
+  }
+
+  private RegionMXBean awaitRegionMXBeanProxy(final ObjectName objectName) {
+    SystemManagementService service = getSystemManagementService_tmp();
+
+    await().until(() -> assertThat(service.getMBeanProxy(objectName, RegionMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, RegionMXBean.class);
+  }
+
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = getSystemManagementService_tmp();
+    ObjectName objectName = service.getMemberMBeanName(member);
+    Stri

<TRUNCATED>