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/12/14 17:57:16 UTC

[01/50] [abbrv] geode git commit: Removing a bogus import of a javafx class. [Forced Update!]

Repository: geode
Updated Branches:
  refs/heads/feature/GEODE-1930 d261061e5 -> 914cbfdc5 (forced update)


Removing a bogus import of a javafx class.

This import failed on openjdk.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 033d14f585bafc142a0cf9183fe3350b59e8a112
Parents: 05c2388
Author: Dan Smith <up...@apache.org>
Authored: Tue Dec 6 11:22:36 2016 -0800
Committer: Dan Smith <up...@apache.org>
Committed: Tue Dec 6 16:53:20 2016 -0800

----------------------------------------------------------------------
 .../query/functional/TestNewFunctionSSorRSIntegrationTest.java      | 1 -
 1 file changed, 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/033d14f5/geode-core/src/test/java/org/apache/geode/cache/query/functional/TestNewFunctionSSorRSIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache/query/functional/TestNewFunctionSSorRSIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/cache/query/functional/TestNewFunctionSSorRSIntegrationTest.java
index 6723243..957ec29 100755
--- a/geode-core/src/test/java/org/apache/geode/cache/query/functional/TestNewFunctionSSorRSIntegrationTest.java
+++ b/geode-core/src/test/java/org/apache/geode/cache/query/functional/TestNewFunctionSSorRSIntegrationTest.java
@@ -19,7 +19,6 @@
  */
 package org.apache.geode.cache.query.functional;
 
-import static javafx.scene.input.KeyCode.Q;
 import static org.junit.Assert.*;
 
 import java.util.ArrayList;


[49/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 a3c8b27..cebfddc 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
@@ -14,13 +14,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;
 
@@ -29,438 +41,374 @@ 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;
-import org.apache.geode.test.junit.categories.FlakyTest;
 
 /**
  * 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";
+@SuppressWarnings({"serial", "unused"})
+public class ClientHealthStatsDUnitTest implements Serializable {
 
-  /** name of the test region */
-  private static final String REGION_NAME = "ClientHealthStatsDUnitTest_Region";
+  private static final int NUMBER_PUTS = 100;
 
-  private static VM client = null;
-  private static VM client2 = null;
-  private static VM managingNode = null;
+  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 ManagementTestBase helper = new ManagementTestBase() {};
+  private static final String REGION_NAME =
+      ClientHealthStatsDUnitTest.class.getSimpleName() + "_Region";
 
-  private static int numOfCreates = 0;
-  private static int numOfUpdates = 0;
-  private static int numOfInvalidates = 0;
-  private static boolean lastKeyReceived = false;
+  // client1VM and client2VM VM fields
+  private static ClientCache clientCache;
 
-  private static GemFireCacheImpl cache = null;
+  // 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 server = null;
+  private VM managerVM;
+  private VM serverVM;
+  private VM client1VM;
+  private VM client2VM;
 
-  @Override
-  public final void postSetUp() throws Exception {
-    disconnectAllFromDS();
+  private String hostName;
 
-    final Host host = Host.getHost(0);
-    managingNode = host.getVM(0);
-    server = host.getVM(1);
-    client = host.getVM(2);
-    client2 = host.getVM(3);
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-    IgnoredException.addIgnoredException("Connection reset");
-  }
+  @Before
+  public void before() throws Exception {
+    this.hostName = getServerHostName(getHost(0));
 
-  @Override
-  public final void preTearDown() throws Exception {
-    reset();
-    helper.closeCache(managingNode);
-    helper.closeCache(client);
-    helper.closeCache(client2);
-    helper.closeCache(server);
+    this.managerVM = getHost(0).getVM(0);
+    this.serverVM = getHost(0).getVM(1);
+    this.client1VM = getHost(0).getVM(2);
+    this.client2VM = getHost(0).getVM(3);
 
-    disconnectAllFromDS();
+    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 = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
+    int port = this.serverVM.invoke(() -> createServerCache());
 
-    DistributedMember serverMember = helper.getMember(server);
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, true));
 
-    client.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, false));
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> put());
 
-    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);
-
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
-
-    DistributedMember serverMember = helper.getMember(server);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1,
-        false, false));
+    int port = this.serverVM.invoke(() -> createServerCache());
 
-    client2.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 2,
-        false, false));
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, false));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, false));
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.put());
-    client2.invoke(() -> ClientHealthStatsDUnitTest.put());
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> 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);
+    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, true));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, true));
 
-    client.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, true));
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> put());
 
-    client2.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 2, true, true));
+    this.client1VM.invoke(() -> clientCache.close(true));
+    this.client2VM.invoke(() -> clientCache.close(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);
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    this.managerVM.invoke(() -> verifyClientStats(serverMember, port, 2));
+    this.managementTestRule.stopManager(this.managerVM);
   }
 
-  @Category(FlakyTest.class) // GEODE-337
   @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));
-  }
+    int port = this.serverVM.invoke(() -> createServerCache()); // start a serverVM
 
-  private static void verifyProxyHasBeenPaused() {
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true)); // create durable
+                                                                                  // client1VM, with
+                                                                                  // durable RI
 
-    WaitCriterion criterion = new WaitCriterion() {
+    this.serverVM.invoke(() -> doPuts()); // do puts on serverVM from three different threads, pause
+                                          // after 500 puts each.
 
-      @Override
-      public boolean done() {
-        CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-        Collection<CacheClientProxy> ccProxies = ccn.getClientProxies();
+    this.client1VM.invoke(() -> clientCache.close(true)); // close durable client1VM
 
-        Iterator<CacheClientProxy> itr = ccProxies.iterator();
+    this.serverVM
+        .invoke(() -> await().atMost(2, MINUTES).until(() -> cacheClientProxyHasBeenPause()));
 
-        while (itr.hasNext()) {
-          CacheClientProxy ccp = itr.next();
-          System.out.println("proxy status " + ccp.getState());
-          if (ccp.isPaused())
-            return true;
-        }
-        return false;
-      }
+    this.serverVM.invoke(() -> resumePuts()); // resume puts on serverVM, add another 100.
 
-      @Override
-      public String description() {
-        return "Proxy has not paused yet";
-      }
-    };
+    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
 
-    Wait.waitForCriterion(criterion, 15 * 1000, 200, true);
+    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);
+    ClientCacheFactory cacheFactory = new ClientCacheFactory(props);
     if (subscriptionEnabled) {
-      ccf.setPoolSubscriptionEnabled(true);
-      ccf.setPoolSubscriptionAckInterval(50);
-      ccf.setPoolSubscriptionRedundancy(0);
+      cacheFactory.setPoolSubscriptionEnabled(true);
+      cacheFactory.setPoolSubscriptionAckInterval(50);
+      cacheFactory.setPoolSubscriptionRedundancy(0);
     }
 
-    if (durable) {
-      ccf.set(DURABLE_CLIENT_ID, "DurableClientId_" + clientNum);
-      ccf.set(DURABLE_CLIENT_TIMEOUT, "" + 300);
-    }
+    cacheFactory.set(DURABLE_CLIENT_ID, "DurableClientId_" + clientNum);
+    cacheFactory.set(DURABLE_CLIENT_TIMEOUT, "" + 30000);
 
-    ccf.addPoolServer(host.getHostName(), port);
-    cache = (GemFireCacheImpl) ccf.create();
+    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);
+    Region<String, String> region = regionFactory.create(REGION_NAME);
     if (subscriptionEnabled) {
-      r.registerInterest("ALL_KEYS", true);
-      cache.readyForEvents();
+      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;
-      }
+  /**
+   * 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);
 
-      @Override
-      public String description() {
-        return "Did not receive last key.";
-      }
-    };
-    Wait.waitForCriterion(wc, 60 * 1000, 500, true);
-  }
+    String[] clientIds = cacheServerMXBean.getClientIds();
+    assertThat(clientIds).hasSize(2);
 
-  private static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
-  }
+    ClientHealthStatus[] clientStatuses = cacheServerMXBean.showAllClientStats();
 
-  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 clientStatus1 = cacheServerMXBean.showClientStats(clientIds[0]);
+    ClientHealthStatus clientStatus2 = cacheServerMXBean.showClientStats(clientIds[1]);
+    assertThat(clientStatus1).isNotNull();
+    assertThat(clientStatus2).isNotNull();
 
-      DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
-      assertEquals(2, dsBean.getNumClients());
-      assertEquals(numSubscriptions, dsBean.getNumSubscriptions());
+    assertThat(clientStatuses).isNotNull().hasSize(2);
 
-    } catch (Exception e) {
-      fail("Error while verifying cache server from remote member", e);
-    }
+    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/geode/blob/914cbfdc/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 9c33003..cdb55a9 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
@@ -14,163 +14,90 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
+import static java.util.concurrent.TimeUnit.*;
+import static org.assertj.core.api.Assertions.*;
 
-import static org.junit.Assert.*;
+import java.io.Serializable;
 
-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 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;
+  @Member
+  private VM memberVM;
 
-  private static ObjectName objectName;
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().start(true).build();
 
-  @Category(FlakyTest.class) // GEODE-1492
   @Test
   public void testCompositeTypeGetters() throws Exception {
+    registerMBeanWithCompositeTypeGetters(this.memberVM);
 
-    initManagement(false);
-    String member = getMemberId(managedNode1);
-    member = MBeanJMXAdapter.makeCompliantName(member);
-
-    registerMBeanWithCompositeTypeGetters(managedNode1, member);
+    String memberName = MBeanJMXAdapter.makeCompliantName(getMemberId(this.memberVM));
+    verifyMBeanWithCompositeTypeGetters(this.managerVM, memberName);
+  }
 
+  private void registerMBeanWithCompositeTypeGetters(final VM memberVM) throws Exception {
+    memberVM.invoke("registerMBeanWithCompositeTypeGetters", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-    checkMBeanWithCompositeTypeGetters(managingNode, member);
+      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 registerMBeanWithCompositeTypeGetters(VM vm, final String memberID)
+  private void verifyMBeanWithCompositeTypeGetters(final VM managerVM, 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);
-  }
+    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();
 
-  /**
-   * 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);
+      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/geode/blob/914cbfdc/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 86501c3..cc8e611 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
@@ -14,452 +14,289 @@
  */
 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";
+  private static final String LOCK_SERVICE_NAME =
+      DLockManagementDUnitTest.class.getSimpleName() + "_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;
+  @Manager
+  private VM managerVM;
 
-  public DLockManagementDUnitTest() {
-    super();
+  @Member
+  private VM[] memberVMs;
 
-  }
+  @Rule
+  public ManagementTestRule managementTestRule =
+      ManagementTestRule.builder().managersFirst(false).start(true).build();
 
-  /**
-   * 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);
+  public void testLockServiceMXBean() throws Throwable {
+    createLockServiceGrantor(this.memberVMs[0]);
+    createLockService(this.memberVMs[1]);
+    createLockService(this.memberVMs[2]);
 
-    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);
+    for (VM memberVM : this.memberVMs) {
+      verifyLockServiceMXBeanInMember(memberVM);
     }
-    verifyLockDataRemote(managingNode);
+    verifyLockServiceMXBeanInManager(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
-      closeLockService(vm);
+    for (VM memberVM : this.memberVMs) {
+      closeLockService(memberVM);
     }
   }
 
-  /**
-   * 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]);
+  public void testDistributedLockServiceMXBean() throws Throwable {
+    createLockServiceGrantor(this.memberVMs[0]);
+    createLockService(this.memberVMs[1]);
+    createLockService(this.memberVMs[2]);
 
-    createLockService(managedNodes[2]);
+    verifyDistributedLockServiceMXBean(this.managerVM, 3);
 
-    checkAggregate(managingNode, 3);
-    DistributedMember member = getMember(managedNodes[2]);
-    checkNavigation(managingNode, member);
+    DistributedMember member = this.managementTestRule.getDistributedMember(this.memberVMs[2]);
+    verifyFetchOperations(this.managerVM, member);
 
-    createLockService(managingNode);
-    checkAggregate(managingNode, 4);
+    createLockService(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 4);
 
-
-    for (VM vm : getManagedNodeList()) {
-      closeLockService(vm);
+    for (VM memberVM : this.memberVMs) {
+      closeLockService(memberVM);
     }
-    ensureProxyCleanup(managingNode);
-    checkAggregate(managingNode, 1);
-    closeLockService(managingNode);
-    checkAggregate(managingNode, 0);
+    verifyProxyCleanupInManager(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 1);
 
+    closeLockService(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 0);
   }
 
-  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;
-
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
-
-              public boolean done() {
-                ObjectName objectName = service.getRegionMBeanName(member, LOCK_SERVICE_NAME);
-                bean = service.getMBeanProxy(objectName, LockServiceMXBean.class);
-                boolean done = (bean == null);
-                return done;
-              }
-
-            }, MAX_WAIT, 500, true);
-
-          } catch (Exception e) {
-            throw new AssertionError("could not remove proxies in required time", e);
-
-          }
-          assertNull(bean);
-
-        }
+  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();
-
-            assertNotNull(grantor);
+      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());
+    });
+  }
 
-            LogWriterUtils.getLogWriter().info("In identifyLockGrantor - grantor is " + grantor);
+  private void createLockService(final VM anyVM) {
+    anyVM.invoke("createLockService", () -> {
+      assertThat(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME)).isNull();
 
+      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);
-
-        assertNotNull(bean);
-
-        assertTrue(bean.isDistributed());
-
-        assertFalse(bean.isLockGrantor());
+        Map<String, String> lockThreadMap = lockServiceMXBean.listThreadsHoldingLock();
+        assertThat(lockThreadMap).hasSize(1);
       }
-    };
-    vm.invoke(createLockService);
+    });
+  }
+
+  private void verifyFetchOperations(final VM memberVM, final DistributedMember member) {
+    memberVM.invoke("verifyFetchOperations", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+
+      DistributedSystemMXBean distributedSystemMXBean = awaitDistributedSystemMXBean();
+      ObjectName distributedLockServiceMXBeanName =
+          MBeanJMXAdapter.getDistributedLockServiceName(LOCK_SERVICE_NAME);
+      assertThat(distributedSystemMXBean.fetchDistributedLockServiceObjectName(LOCK_SERVICE_NAME))
+          .isEqualTo(distributedLockServiceMXBeanName);
+
+      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() {
-
-        DistributedLockService service = DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME);
-
-        DistributedLockService.destroy(LOCK_SERVICE_NAME);
-
-        ManagementService mgmtService = getManagementService();
-
-        LockServiceMXBean bean = null;
-        try {
+  private void verifyDistributedLockServiceMXBean(final VM managerVM, final int memberCount) {
+    managerVM.invoke("verifyDistributedLockServiceMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+
+      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);
-
-        service.lock(LOCK_OBJECT, 1000, -1);
-
+  private DistributedLockServiceMXBean awaitDistributedLockServiceMXBean(
+      final String lockServiceName, final int memberCount) {
+    ManagementService service = this.managementTestRule.getManagementService();
 
-        ManagementService mgmtService = getManagementService();
+    await().until(() -> {
+      assertThat(service.getDistributedLockServiceMXBean(lockServiceName)).isNotNull();
+      assertThat(service.getDistributedLockServiceMXBean(lockServiceName).getMemberCount())
+          .isEqualTo(memberCount);
+    });
 
-        LockServiceMXBean bean = null;
-        try {
-
-          bean = mgmtService.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
-
-        } catch (ManagementException mgs) {
-
-        }
-        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.getDistributedLockServiceMXBean(lockServiceName);
   }
 
   /**
-   * Verify lock data from remote Managing node
-   * 
-   * @param vm
+   * Await and return a LockServiceMXBean proxy for a specific member and 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());
-            }
-
-          }
-        };
-    vm.invoke(verifyLockDataRemote);
-  }
+  private LockServiceMXBean awaitLockServiceMXBeanProxy(final DistributedMember member,
+      final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName lockServiceMXBeanName = service.getLockServiceMBeanName(member, lockServiceName);
 
-  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.getMBeanProxy(lockServiceMXBeanName, LockServiceMXBean.class))
+            .isNotNull());
 
-      }
-    };
-    vm.invoke(checkNavigation);
+    return service.getMBeanProxy(lockServiceMXBeanName, LockServiceMXBean.class);
   }
 
   /**
-   * Verify Aggregate MBean
-   * 
-   * @param vm
+   * Await creation 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;
+  private LockServiceMXBean awaitLockServiceMXBean(final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
+    await().until(() -> assertThat(service.getLocalLockServiceMBean(lockServiceName)).isNotNull());
 
-              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;
-        }
+    return service.getLocalLockServiceMBean(lockServiceName);
+  }
 
-        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);
+  /**
+   * Await destruction of local LockServiceMXBean for specified lockServiceName.
+   */
+  private void awaitLockServiceMXBeanIsNull(final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-        }
-        assertNotNull(bean);
-        assertEquals(bean.getName(), LOCK_SERVICE_NAME);
+    await().until(() -> assertThat(service.getLocalLockServiceMBean(lockServiceName)).isNull());
+  }
 
-      }
-    };
-    vm.invoke(checkAggregate);
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(MAX_WAIT_MILLIS, MILLISECONDS);
   }
 }
+


[33/50] [abbrv] geode git commit: GEODE-1027: add unit test for previously committed fix

Posted by kl...@apache.org.
GEODE-1027: add unit test for previously committed fix


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

Branch: refs/heads/feature/GEODE-1930
Commit: 1f49cbcc8cbaad5c0c2ccb8063a67bd6bb88a9b9
Parents: 8eb09bd
Author: Kirk Lund <kl...@apache.org>
Authored: Wed Dec 7 15:33:51 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 14:38:27 2016 -0800

----------------------------------------------------------------------
 .../internal/statistics/SampleCollector.java    |   4 +-
 .../internal/statistics/StatisticsMonitor.java  |  28 ++---
 .../geode/internal/statistics/ValueMonitor.java |  20 ++--
 .../internal/beans/stats/MBeanStatsMonitor.java |  54 +++++----
 .../internal/statistics/FakeValueMonitor.java   |  37 ++++++
 .../beans/stats/MBeanStatsMonitorTest.java      | 117 +++++++++++++++++++
 6 files changed, 212 insertions(+), 48 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/1f49cbcc/geode-core/src/main/java/org/apache/geode/internal/statistics/SampleCollector.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/statistics/SampleCollector.java b/geode-core/src/main/java/org/apache/geode/internal/statistics/SampleCollector.java
index 9f1b343..2abbecd 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/statistics/SampleCollector.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/statistics/SampleCollector.java
@@ -115,7 +115,7 @@ public class SampleCollector {
    * 
    * @throws IllegalStateException if no SampleCollector has been created and initialized yet
    */
-  public static StatMonitorHandler getStatMonitorHandler() {
+  static StatMonitorHandler getStatMonitorHandler() {
     // sync SampleCollector.class and then instance.sampleHandlers
     synchronized (SampleCollector.class) {
       if (instance == null) {
@@ -321,7 +321,7 @@ public class SampleCollector {
   }
 
   /** For testing only */
-  public StatArchiveHandler getStatArchiveHandler() {
+  StatArchiveHandler getStatArchiveHandler() {
     synchronized (this.sampleHandlers) {
       return this.statArchiveHandler;
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/1f49cbcc/geode-core/src/main/java/org/apache/geode/internal/statistics/StatisticsMonitor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/statistics/StatisticsMonitor.java b/geode-core/src/main/java/org/apache/geode/internal/statistics/StatisticsMonitor.java
index 16f71e2..a00a7a3 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/statistics/StatisticsMonitor.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/statistics/StatisticsMonitor.java
@@ -29,14 +29,13 @@ public abstract class StatisticsMonitor {
 
   private final Object mutex = new Object();
 
-  private final ConcurrentHashSet<StatisticsListener> listeners =
-      new ConcurrentHashSet<StatisticsListener>();
+  private final ConcurrentHashSet<StatisticsListener> listeners = new ConcurrentHashSet<>();
 
-  private final ConcurrentHashSet<StatisticId> statisticIds = new ConcurrentHashSet<StatisticId>();
+  private final ConcurrentHashSet<StatisticId> statisticIds = new ConcurrentHashSet<>();
 
   public StatisticsMonitor() {}
 
-  public StatisticsMonitor addStatistic(StatisticId statId) {
+  public StatisticsMonitor addStatistic(final StatisticId statId) {
     if (statId == null) {
       throw new NullPointerException("StatisticId is null");
     }
@@ -46,7 +45,7 @@ public abstract class StatisticsMonitor {
     return this;
   }
 
-  public StatisticsMonitor removeStatistic(StatisticId statId) {
+  public StatisticsMonitor removeStatistic(final StatisticId statId) {
     if (statId == null) {
       throw new NullPointerException("StatisticId is null");
     }
@@ -56,7 +55,7 @@ public abstract class StatisticsMonitor {
     return this;
   }
 
-  public final void addListener(StatisticsListener listener) {
+  public void addListener(final StatisticsListener listener) {
     if (listener == null) {
       throw new NullPointerException("StatisticsListener is null");
     }
@@ -68,7 +67,7 @@ public abstract class StatisticsMonitor {
     }
   }
 
-  public final void removeListener(StatisticsListener listener) {
+  public void removeListener(final StatisticsListener listener) {
     if (listener == null) {
       throw new NullPointerException("StatisticsListener is null");
     }
@@ -93,24 +92,25 @@ public abstract class StatisticsMonitor {
    * @param millisTimeStamp the real time in millis of the sample
    * @param resourceInstances resources with one or more updated values
    */
-  protected void monitor(long millisTimeStamp, List<ResourceInstance> resourceInstances) {
+  protected void monitor(final long millisTimeStamp,
+      final List<ResourceInstance> resourceInstances) {
     monitorStatisticIds(millisTimeStamp, resourceInstances);
   }
 
-  private final void monitorStatisticIds(long millisTimeStamp,
-      List<ResourceInstance> resourceInstances) {
+  private void monitorStatisticIds(final long millisTimeStamp,
+      final List<ResourceInstance> resourceInstances) {
     if (!this.statisticIds.isEmpty()) {
       // TODO:
     }
   }
 
-  protected final void notifyListeners(StatisticsNotification notification) {
+  protected void notifyListeners(final StatisticsNotification notification) {
     for (StatisticsListener listener : this.listeners) {
       listener.handleNotification(notification);
     }
   }
 
-  protected final Object mutex() {
+  protected Object mutex() {
     return this.mutex;
   }
 
@@ -137,7 +137,9 @@ public abstract class StatisticsMonitor {
     return sb.toString();
   }
 
-  /** Override to append to toString() */
+  /**
+   * Override to append to toString()
+   */
   protected StringBuilder appendToString() {
     return null;
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/1f49cbcc/geode-core/src/main/java/org/apache/geode/internal/statistics/ValueMonitor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/statistics/ValueMonitor.java b/geode-core/src/main/java/org/apache/geode/internal/statistics/ValueMonitor.java
index 1dc6fd0..e46723c 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/statistics/ValueMonitor.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/statistics/ValueMonitor.java
@@ -43,31 +43,31 @@ import org.apache.geode.internal.CopyOnWriteHashSet;
  * @since GemFire 7.0
  * @see org.apache.geode.Statistics
  */
-public final class ValueMonitor extends StatisticsMonitor {
+public class ValueMonitor extends StatisticsMonitor {
 
   public enum Type {
     CHANGE, MATCH, DIFFER
   }
 
-  private final CopyOnWriteHashSet<Statistics> statistics = new CopyOnWriteHashSet<Statistics>();
+  private final CopyOnWriteHashSet<Statistics> statistics = new CopyOnWriteHashSet<>();
 
   public ValueMonitor() {
     super();
   }
 
   @Override
-  public ValueMonitor addStatistic(StatisticId statId) {
+  public ValueMonitor addStatistic(final StatisticId statId) {
     super.addStatistic(statId);
     return this;
   }
 
   @Override
-  public ValueMonitor removeStatistic(StatisticId statId) {
+  public ValueMonitor removeStatistic(final StatisticId statId) {
     super.removeStatistic(statId);
     return this;
   }
 
-  public ValueMonitor addStatistics(Statistics statistics) {
+  public ValueMonitor addStatistics(final Statistics statistics) {
     if (statistics == null) {
       throw new NullPointerException("Statistics is null");
     }
@@ -75,7 +75,7 @@ public final class ValueMonitor extends StatisticsMonitor {
     return this;
   }
 
-  public ValueMonitor removeStatistics(Statistics statistics) {
+  public ValueMonitor removeStatistics(final Statistics statistics) {
     if (statistics == null) {
       throw new NullPointerException("Statistics is null");
     }
@@ -83,14 +83,16 @@ public final class ValueMonitor extends StatisticsMonitor {
     return this;
   }
 
-  protected void monitor(long millisTimeStamp, List<ResourceInstance> resourceInstances) {
+  protected void monitor(final long millisTimeStamp,
+      final List<ResourceInstance> resourceInstances) {
     super.monitor(millisTimeStamp, resourceInstances);
     monitorStatistics(millisTimeStamp, resourceInstances);
   }
 
-  protected void monitorStatistics(long millisTimeStamp, List<ResourceInstance> resourceInstances) {
+  protected void monitorStatistics(final long millisTimeStamp,
+      final List<ResourceInstance> resourceInstances) {
     if (!this.statistics.isEmpty()) {
-      Map<StatisticId, Number> stats = new HashMap<StatisticId, Number>();
+      Map<StatisticId, Number> stats = new HashMap<>();
       for (ResourceInstance resource : resourceInstances) {
         if (this.statistics.contains(resource.getStatistics())) {
           ResourceType resourceType = resource.getResourceType();

http://git-wip-us.apache.org/repos/asf/geode/blob/1f49cbcc/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitor.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitor.java
index 390fb89..c1744f9 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitor.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitor.java
@@ -17,11 +17,12 @@ package org.apache.geode.management.internal.beans.stats;
 import java.util.HashMap;
 import java.util.Map;
 
+import org.apache.logging.log4j.Logger;
+
 import org.apache.geode.StatisticDescriptor;
 import org.apache.geode.Statistics;
 import org.apache.geode.StatisticsType;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.i18n.LogWriterI18n;
+import org.apache.geode.internal.logging.LogService;
 import org.apache.geode.internal.statistics.StatisticId;
 import org.apache.geode.internal.statistics.StatisticNotFoundException;
 import org.apache.geode.internal.statistics.StatisticsListener;
@@ -30,11 +31,11 @@ import org.apache.geode.internal.statistics.ValueMonitor;
 
 /**
  * Class to get mappings of stats name to their values
- * 
- * 
  */
 public class MBeanStatsMonitor implements StatisticsListener {
 
+  private static final Logger logger = LogService.getLogger();
+
   protected ValueMonitor monitor;
 
   /**
@@ -44,17 +45,17 @@ public class MBeanStatsMonitor implements StatisticsListener {
 
   protected String monitorName;
 
-  private LogWriterI18n logger;
+  public MBeanStatsMonitor(final String name) {
+    this(name, new ValueMonitor());
+  }
 
-  public MBeanStatsMonitor(String name) {
+  MBeanStatsMonitor(final String name, final ValueMonitor monitor) {
     this.monitorName = name;
-    this.monitor = new ValueMonitor();
+    this.monitor = monitor;
     this.statsMap = new DefaultHashMap();
-    this.logger = InternalDistributedSystem.getLoggerI18n();
-
   }
 
-  public void addStatisticsToMonitor(Statistics stats) {
+  public void addStatisticsToMonitor(final Statistics stats) {
     monitor.addListener(this);// if already listener is added this will be a no-op
     // Initialize the stats with the current values.
     StatisticsType type = stats.getType();
@@ -65,7 +66,7 @@ public class MBeanStatsMonitor implements StatisticsListener {
     monitor.addStatistics(stats);
   }
 
-  public void removeStatisticsFromMonitor(Statistics stats) {
+  public void removeStatisticsFromMonitor(final Statistics stats) {
     statsMap.clear();
   }
 
@@ -73,13 +74,13 @@ public class MBeanStatsMonitor implements StatisticsListener {
     monitor.removeListener(this);
   }
 
-  public Number getStatistic(String statName) {
-    return statsMap.get(statName) != null ? statsMap.get(statName) : 0;
+  public Number getStatistic(final String statName) {
+    Number value = statsMap.get(statName);
+    return value != null ? value : 0;
   }
 
   @Override
-  public void handleNotification(StatisticsNotification notification) {
-
+  public void handleNotification(final StatisticsNotification notification) {
     for (StatisticId statId : notification) {
       StatisticDescriptor descriptor = statId.getStatisticDescriptor();
       String name = descriptor.getName();
@@ -91,33 +92,38 @@ public class MBeanStatsMonitor implements StatisticsListener {
       }
       log(name, value);
       statsMap.put(name, value);
-
     }
   }
 
-  protected void log(String name, Number value) {
-
-    if (logger != null && logger.finestEnabled()) {
-      logger.finest("Monitor = " + monitorName + " descriptor = " + name + " And Value = " + value);
+  protected void log(final String name, final Number value) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Monitor = {} descriptor = {} And value = {}", monitorName, name, value);
     }
   }
 
-  public static class DefaultHashMap {
-    private Map<String, Number> internalMap = new HashMap<String, Number>();
+  public static class DefaultHashMap { // TODO: delete this class
+    private Map<String, Number> internalMap = new HashMap<>();
 
     public DefaultHashMap() {}
 
-    public Number get(String key) {
+    public Number get(final String key) {
       return internalMap.get(key) != null ? internalMap.get(key) : 0;
     }
 
-    public void put(String key, Number value) {
+    public void put(final String key, final Number value) {
       internalMap.put(key, value);
     }
 
     public void clear() {
       internalMap.clear();
     }
+
+    /**
+     * For testing only
+     */
+    Map<String, Number> getInternalMap() {
+      return this.internalMap;
+    }
   }
 
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/1f49cbcc/geode-core/src/test/java/org/apache/geode/internal/statistics/FakeValueMonitor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/statistics/FakeValueMonitor.java b/geode-core/src/test/java/org/apache/geode/internal/statistics/FakeValueMonitor.java
new file mode 100644
index 0000000..0b3a27d
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/statistics/FakeValueMonitor.java
@@ -0,0 +1,37 @@
+/*
+ * 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.statistics;
+
+import static org.mockito.Mockito.mock;
+
+/**
+ * Fake ValueMonitor which uses mocked StatMonitorHandler as a collaborator.
+ */
+public class FakeValueMonitor extends ValueMonitor {
+
+  private StatMonitorHandler statMonitorHandler;
+
+  public FakeValueMonitor() {
+    this(mock(StatMonitorHandler.class));
+  }
+
+  public FakeValueMonitor(StatMonitorHandler statMonitorHandler) {
+    this.statMonitorHandler = statMonitorHandler;
+  }
+
+  StatMonitorHandler getStatMonitorHandler() {
+    return this.statMonitorHandler;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/1f49cbcc/geode-core/src/test/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitorTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitorTest.java
new file mode 100644
index 0000000..18d7f81
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitorTest.java
@@ -0,0 +1,117 @@
+/*
+ * 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.internal.beans.stats;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TestName;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+
+import org.apache.geode.StatisticDescriptor;
+import org.apache.geode.Statistics;
+import org.apache.geode.StatisticsType;
+import org.apache.geode.i18n.LogWriterI18n;
+import org.apache.geode.internal.statistics.FakeValueMonitor;
+import org.apache.geode.internal.statistics.ValueMonitor;
+import org.apache.geode.management.internal.beans.stats.MBeanStatsMonitor.DefaultHashMap;
+import org.apache.geode.test.junit.categories.UnitTest;
+
+@Category(UnitTest.class)
+public class MBeanStatsMonitorTest {
+
+  private ValueMonitor statsMonitor;
+
+  private StatisticDescriptor[] descriptors;
+
+  private Map<String, Number> expectedStatsMap;
+
+  @Spy
+  private DefaultHashMap statsMap;
+  @Mock
+  private LogWriterI18n logWriter;
+  @Mock
+  private Statistics stats;
+  @Mock
+  private StatisticsType statsType;
+
+  @InjectMocks
+  private MBeanStatsMonitor mbeanStatsMonitor;
+
+  @Rule
+  public TestName testName = new TestName();
+
+  @Before
+  public void setUp() throws Exception {
+    this.statsMonitor = spy(new FakeValueMonitor());
+    this.mbeanStatsMonitor =
+        new MBeanStatsMonitor(this.testName.getMethodName(), this.statsMonitor);
+    MockitoAnnotations.initMocks(this);
+
+    this.expectedStatsMap = new HashMap<>();
+    this.descriptors = new StatisticDescriptor[3];
+    for (int i = 0; i < this.descriptors.length; i++) {
+      String key = "stat-" + String.valueOf(i + 1);
+      Number value = i + 1;
+
+      this.expectedStatsMap.put(key, value);
+
+      this.descriptors[i] = mock(StatisticDescriptor.class);
+      when(this.descriptors[i].getName()).thenReturn(key);
+      when(this.stats.get(this.descriptors[i])).thenReturn(value);
+    }
+
+    when(this.statsType.getStatistics()).thenReturn(this.descriptors);
+    when(this.stats.getType()).thenReturn(this.statsType);
+  }
+
+  @Test
+  public void addStatisticsToMonitorShouldAddToInternalMap() throws Exception {
+    this.mbeanStatsMonitor.addStatisticsToMonitor(this.stats);
+
+    assertThat(statsMap.getInternalMap()).containsAllEntriesOf(this.expectedStatsMap);
+  }
+
+  @Test
+  public void addStatisticsToMonitorShouldAddListener() throws Exception {
+    this.mbeanStatsMonitor.addStatisticsToMonitor(this.stats);
+
+    verify(this.statsMonitor, times(1)).addListener(this.mbeanStatsMonitor);
+  }
+
+  @Test
+  public void addStatisticsToMonitorShouldAddStatistics() throws Exception {
+    this.mbeanStatsMonitor.addStatisticsToMonitor(this.stats);
+
+    verify(this.statsMonitor, times(1)).addStatistics(this.stats);
+  }
+
+  @Test
+  public void addNullStatisticsToMonitorShouldThrowNPE() throws Exception {
+    assertThatThrownBy(() -> this.mbeanStatsMonitor.addStatisticsToMonitor(null))
+        .isExactlyInstanceOf(NullPointerException.class);
+  }
+
+}


[25/50] [abbrv] geode git commit: Update website release references to remove incubator

Posted by kl...@apache.org.
Update website release references to remove incubator

The release location has changed due to TLP. After the next release,
we should also update the archives location on the release page.


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

Branch: refs/heads/feature/GEODE-1930
Commit: ac3a8224170c48358dba706d4704058eaf53608f
Parents: 0918488
Author: Anthony Baker <ab...@apache.org>
Authored: Fri Dec 9 12:47:56 2016 -0800
Committer: Anthony Baker <ab...@apache.org>
Committed: Fri Dec 9 12:49:34 2016 -0800

----------------------------------------------------------------------
 geode-site/website/content/releases/index.html | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/ac3a8224/geode-site/website/content/releases/index.html
----------------------------------------------------------------------
diff --git a/geode-site/website/content/releases/index.html b/geode-site/website/content/releases/index.html
index de0335d..8947839 100644
--- a/geode-site/website/content/releases/index.html
+++ b/geode-site/website/content/releases/index.html
@@ -39,10 +39,10 @@ under the License. -->
         <!-- BINARY -->
         <ul>
             <span class="icon-cloud-download"> <strong>Binaries </strong>
-              [ <a href="http://apache.org/dyn/closer.cgi/incubator/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.zip">ZIP</a>, <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.zip.sha256">SHA-256</a>,
-              <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.zip.asc">PGP</a> ] -
-              [<a href="http://apache.org/dyn/closer.cgi/incubator/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.tar.gz">TAR.GZ</a>, <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.tar.gz.sha256">SHA-256</a>,
-              <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.tar.gz.asc">PGP</a> ]
+              [ <a href="http://apache.org/dyn/closer.cgi/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.zip">ZIP</a>, <a href="https://dist.apache.org/repos/dist/release/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.zip.sha256">SHA-256</a>,
+              <a href="https://dist.apache.org/repos/dist/release/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.zip.asc">PGP</a> ] -
+              [<a href="http://apache.org/dyn/closer.cgi/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.tar.gz">TAR.GZ</a>, <a href="https://dist.apache.org/repos/dist/release/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.tar.gz.sha256">SHA-256</a>,
+              <a href="https://dist.apache.org/repos/dist/release/geode/1.0.0-incubating/apache-geode-1.0.0-incubating.tar.gz.asc">PGP</a> ]
               </span>
 
               <blockquote>Binary downloads are provided for the convenience of our users and are not official Apache Geode releases. </blockquote>
@@ -51,11 +51,11 @@ under the License. -->
         <!-- SOURCE -->
         <ul>
             <span class="icon-cloud-download"> <strong>Source</strong>
-               [ <a href="http://apache.org/dyn/closer.cgi/incubator/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.zip">ZIP</a>, <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.zip.sha256">SHA-256</a>,
-               <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.zip.asc">PGP</a>
+               [ <a href="http://apache.org/dyn/closer.cgi/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.zip">ZIP</a>, <a href="https://dist.apache.org/repos/dist/release/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.zip.sha256">SHA-256</a>,
+               <a href="https://dist.apache.org/repos/dist/release/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.zip.asc">PGP</a>
                 ] -
-               [<a href="http://apache.org/dyn/closer.cgi/incubator/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.tar.gz">TAR.GZ</a>, <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.tar.gz.sha256">SHA-256</a>,
-               <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.tar.gz.asc">PGP</a>
+               [<a href="http://apache.org/dyn/closer.cgi/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.tar.gz">TAR.GZ</a>, <a href="https://dist.apache.org/repos/dist/release/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.tar.gz.sha256">SHA-256</a>,
+               <a href="https://dist.apache.org/repos/dist/release/geode/1.0.0-incubating/apache-geode-src-1.0.0-incubating.tar.gz.asc">PGP</a>
                ]
              </span>
             </li>
@@ -98,10 +98,10 @@ under the License. -->
 					Project releases are approved by vote of the Apache Geode Project Management Committee (PMC). Support for a release is provided by project volunteers on the project <a href="http://geode.apache.org/community/#mailing-lists">mailing lists</a>. Bugs found in a release may be discussed on the list and reported through the <a href="https://issues.apache.org/jira/browse/GEODE">issue tracker</a>. The user mailing list and issue tracker are the only support options hosted by the Apache Geode project.
 				</p>
 				<p>
-					<strong>Note</strong>: When downloading from a mirror, please be sure to verify that checksums and signatures are correct. To do so, use the checksum and signature files from the main Apache site at <a href="https://dist.apache.org/repos/dist/release/incubator/geode/">https://dist.apache.org/repos/dist/release/incubator/geode/</a>. Find here the KEYS file, which contains all OpenPGP keys we use to sign releases here: <a href="https://git-wip-us.apache.org/repos/asf?p=geode.git;a=blob;f=KEYS;h=9d13f70a9ce8f8d6a7c3feb1e194ccec123b5868;hb=c26334542fa9e90daff5f58467d6e174b3e0f3e2">KEYS</a>
+					<strong>Note</strong>: When downloading from a mirror, please be sure to verify that checksums and signatures are correct. To do so, use the checksum and signature files from the main Apache site at <a href="https://dist.apache.org/repos/dist/release/geode/">https://dist.apache.org/repos/dist/release/geode/</a>. Find here the KEYS file, which contains all OpenPGP keys we use to sign releases here: <a href="https://git-wip-us.apache.org/repos/asf?p=geode.git;a=blob;f=KEYS;h=9d13f70a9ce8f8d6a7c3feb1e194ccec123b5868;hb=c26334542fa9e90daff5f58467d6e174b3e0f3e2">KEYS</a>
 				</p>
 				<p>
-					The PGP signatures can be verified using PGP or GPG. First download the <a href="https://git-wip-us.apache.org/repos/asf?p=geode.git;a=blob;f=KEYS;h=9d13f70a9ce8f8d6a7c3feb1e194ccec123b5868;hb=c26334542fa9e90daff5f58467d6e174b3e0f3e2">KEYS</a> as well as the <a href="https://dist.apache.org/repos/dist/release/incubator/geode/1.0.0-incubating.M1/">asc signature</a> file for the particular distribution. Then verify the signatures using:
+					The PGP signatures can be verified using PGP or GPG. First download the <a href="https://git-wip-us.apache.org/repos/asf?p=geode.git;a=blob;f=KEYS;h=9d13f70a9ce8f8d6a7c3feb1e194ccec123b5868;hb=c26334542fa9e90daff5f58467d6e174b3e0f3e2">KEYS</a> as well as the <em>asc signature</em> file for the particular distribution. Then verify the signatures using:
 				</p>
 				<p>
        				% pgpk -a KEYS


[39/50] [abbrv] geode git commit: GEODE-1974: add FlakyTest category to flaky test

Posted by kl...@apache.org.
GEODE-1974: add FlakyTest category to flaky test


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

Branch: refs/heads/feature/GEODE-1930
Commit: 079542b8189f26a330a6331f79e1cd7edb590067
Parents: da00dbd
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Dec 12 18:05:06 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 18:05:06 2016 -0800

----------------------------------------------------------------------
 .../org/apache/geode/security/SecurityClusterConfigDUnitTest.java   | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/079542b8/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
index 9ce8262..ca209a7 100644
--- a/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
@@ -144,6 +144,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
 
   }
 
+  @Category(FlakyTest.class) // GEODE-1974
   @Test
   public void serverConnectingToSecuredLocatorMustUseClusterConfig() {
     Properties props = new Properties();


[13/50] [abbrv] geode git commit: GEODE-1835 : logging a warning message by the configure pdx command only when there are members in the distributed system.

Posted by kl...@apache.org.
GEODE-1835 : logging a warning message by the configure pdx command only
when there are members in the distributed system.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 28efd90290b519d9fe531c826ee4c6e606bcd8e4
Parents: 9031351
Author: Amey Barve <ab...@apache.org>
Authored: Mon Dec 5 11:56:25 2016 +0530
Committer: Kirk Lund <kl...@apache.org>
Committed: Thu Dec 8 08:46:37 2016 -0800

----------------------------------------------------------------------
 .../apache/geode/management/internal/cli/commands/PDXCommands.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/28efd902/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
index 9f7afc1..c5e9a4e 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
@@ -86,7 +86,7 @@ public class PDXCommands extends AbstractCommandsSupport {
           && (patterns != null && patterns.length > 0)) {
         return ResultBuilder.createUserErrorResult(CliStrings.CONFIGURE_PDX__ERROR__MESSAGE);
       }
-      if (CliUtil.getAllNormalMembers(CliUtil.getCacheIfExists()).isEmpty()) {
+      if (!CliUtil.getAllNormalMembers(CliUtil.getCacheIfExists()).isEmpty()) {
         ird.addLine(CliStrings.CONFIGURE_PDX__NORMAL__MEMBERS__WARNING);
       }
       // Set persistent and the disk-store


[03/50] [abbrv] geode git commit: GEODE-1831: Function no longer gets executed twice on gateway receivers with groups

Posted by kl...@apache.org.
GEODE-1831: Function no longer gets executed twice on gateway receivers with groups


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

Branch: refs/heads/feature/GEODE-1930
Commit: ef96dba9a02d3f0ffab030e9e30c27caea3b4a89
Parents: 033d14f
Author: Barry Oglesby <bo...@pivotal.io>
Authored: Tue Dec 6 12:51:48 2016 -0800
Committer: Barry Oglesby <bo...@pivotal.io>
Committed: Wed Dec 7 09:17:19 2016 -0800

----------------------------------------------------------------------
 .../geode/internal/cache/CacheServerImpl.java   |   8 +-
 .../internal/LocatorLoadBalancingDUnitTest.java |   4 +-
 .../cache/client/internal/LocatorTestBase.java  |  26 +++-
 ...ayReceiverAutoConnectionSourceDUnitTest.java | 126 +++++++++++++++++++
 4 files changed, 153 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/ef96dba9/geode-core/src/main/java/org/apache/geode/internal/cache/CacheServerImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/CacheServerImpl.java b/geode-core/src/main/java/org/apache/geode/internal/cache/CacheServerImpl.java
index 8463e82..a3c4a93 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/CacheServerImpl.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/CacheServerImpl.java
@@ -690,9 +690,11 @@ public class CacheServerImpl extends AbstractCacheServer implements Distribution
    */
   public String[] getCombinedGroups() {
     ArrayList<String> groupList = new ArrayList<String>();
-    for (String g : MemberAttributes.parseGroups(null, getSystem().getConfig().getGroups())) {
-      if (!groupList.contains(g)) {
-        groupList.add(g);
+    if (!this.isGatewayReceiver) {
+      for (String g : MemberAttributes.parseGroups(null, getSystem().getConfig().getGroups())) {
+        if (!groupList.contains(g)) {
+          groupList.add(g);
+        }
       }
     }
     for (String g : getGroups()) {

http://git-wip-us.apache.org/repos/asf/geode/blob/ef96dba9/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorLoadBalancingDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorLoadBalancingDUnitTest.java b/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorLoadBalancingDUnitTest.java
index fffc09b..bd8143e 100644
--- a/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorLoadBalancingDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorLoadBalancingDUnitTest.java
@@ -404,9 +404,9 @@ public class LocatorLoadBalancingDUnitTest extends LocatorTestBase {
     final ServerLoad load1 = new ServerLoad(.3f, .01f, .44f, 4564f);
     final ServerLoad load2 = new ServerLoad(23.2f, 1.1f, 22.3f, .3f);
     int serverPort1 = vm1.invoke("Start BridgeServer", () -> startBridgeServer(null, locators,
-        new String[] {REGION_NAME}, new MyLoadProbe(load1)));
+        new String[] {REGION_NAME}, new MyLoadProbe(load1), false));
     int serverPort2 = vm2.invoke("Start BridgeServer", () -> startBridgeServer(null, locators,
-        new String[] {REGION_NAME}, new MyLoadProbe(load2)));
+        new String[] {REGION_NAME}, new MyLoadProbe(load2), false));
 
     HashMap expected = new HashMap();
     ServerLocation l1 = new ServerLocation(NetworkUtils.getServerHostName(host), serverPort1);

http://git-wip-us.apache.org/repos/asf/geode/blob/ef96dba9/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorTestBase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorTestBase.java b/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorTestBase.java
index d6c7b29..c3b349a 100644
--- a/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorTestBase.java
+++ b/geode-core/src/test/java/org/apache/geode/cache/client/internal/LocatorTestBase.java
@@ -14,6 +14,7 @@
  */
 package org.apache.geode.cache.client.internal;
 
+import org.apache.geode.internal.lang.StringUtils;
 import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 
 import org.apache.geode.cache.*;
@@ -161,14 +162,21 @@ public abstract class LocatorTestBase extends JUnit4DistributedTestCase {
 
   protected int startBridgeServerInVM(VM vm, final String[] groups, final String locators,
       final String[] regions) {
-    return startBridgeServerInVM(vm, groups, locators, regions, CacheServer.DEFAULT_LOAD_PROBE);
+    return startBridgeServerInVM(vm, groups, locators, regions, CacheServer.DEFAULT_LOAD_PROBE,
+        false);
+  }
+
+  protected int startBridgeServerInVM(VM vm, String[] groups, String locators,
+      boolean useGroupsProperty) {
+    return startBridgeServerInVM(vm, groups, locators, new String[] {REGION_NAME},
+        CacheServer.DEFAULT_LOAD_PROBE, useGroupsProperty);
   }
 
   protected int startBridgeServerInVM(VM vm, final String[] groups, final String locators,
-      final String[] regions, final ServerLoadProbe probe) {
+      final String[] regions, final ServerLoadProbe probe, final boolean useGroupsProperty) {
     SerializableCallable connect = new SerializableCallable("Start bridge server") {
       public Object call() throws IOException {
-        return startBridgeServer(groups, locators, regions, probe);
+        return startBridgeServer(groups, locators, regions, probe, useGroupsProperty);
       }
     };
     Integer port = (Integer) vm.invoke(connect);
@@ -181,14 +189,18 @@ public abstract class LocatorTestBase extends JUnit4DistributedTestCase {
 
   protected int startBridgeServer(final String[] groups, final String locators,
       final String[] regions) throws IOException {
-    return startBridgeServer(groups, locators, regions, CacheServer.DEFAULT_LOAD_PROBE);
+    return startBridgeServer(groups, locators, regions, CacheServer.DEFAULT_LOAD_PROBE, false);
   }
 
   protected int startBridgeServer(final String[] groups, final String locators,
-      final String[] regions, final ServerLoadProbe probe) throws IOException {
+      final String[] regions, final ServerLoadProbe probe, final boolean useGroupsProperty)
+      throws IOException {
     Properties props = new Properties();
     props.setProperty(MCAST_PORT, "0");
     props.setProperty(LOCATORS, locators);
+    if (useGroupsProperty) {
+      props.setProperty(GROUPS, StringUtils.concat(groups, ","));
+    }
     DistributedSystem ds = getSystem(props);
     Cache cache = CacheFactory.create(ds);
     AttributesFactory factory = new AttributesFactory();
@@ -201,7 +213,9 @@ public abstract class LocatorTestBase extends JUnit4DistributedTestCase {
     }
     CacheServer server = cache.addCacheServer();
     server.setPort(0);
-    server.setGroups(groups);
+    if (!useGroupsProperty) {
+      server.setGroups(groups);
+    }
     server.setLoadProbe(probe);
     server.start();
 

http://git-wip-us.apache.org/repos/asf/geode/blob/ef96dba9/geode-wan/src/test/java/org/apache/geode/cache/wan/GatewayReceiverAutoConnectionSourceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/cache/wan/GatewayReceiverAutoConnectionSourceDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/cache/wan/GatewayReceiverAutoConnectionSourceDUnitTest.java
new file mode 100644
index 0000000..fb0881c
--- /dev/null
+++ b/geode-wan/src/test/java/org/apache/geode/cache/wan/GatewayReceiverAutoConnectionSourceDUnitTest.java
@@ -0,0 +1,126 @@
+/*
+ * 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.cache.wan;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.client.PoolManager;
+import org.apache.geode.cache.client.internal.AutoConnectionSourceImpl;
+import org.apache.geode.cache.client.internal.LocatorTestBase;
+import org.apache.geode.cache.client.internal.PoolImpl;
+import org.apache.geode.distributed.internal.ServerLocation;
+import org.apache.geode.internal.AvailablePort;
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.NetworkUtils;
+import org.apache.geode.test.dunit.SerializableRunnable;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+@Category({DistributedTest.class})
+public class GatewayReceiverAutoConnectionSourceDUnitTest extends LocatorTestBase {
+
+  public GatewayReceiverAutoConnectionSourceDUnitTest() {
+    super();
+  }
+
+  @Test
+  public void testBridgeServerAndGatewayReceiverClientAndServerWithoutGroup() throws Exception {
+    runBridgeServerAndGatewayReceiverTest(null, null, true);
+  }
+
+  @Test
+  public void testBridgeServerAndGatewayReceiverClientAndServerWithGroup() throws Exception {
+    String groupName = "group1";
+    runBridgeServerAndGatewayReceiverTest(new String[] {groupName}, groupName, true);
+  }
+
+  @Test
+  public void testBridgeServerAndGatewayReceiverClientWithoutGroupServerWithGroup()
+      throws Exception {
+    String groupName = "group1";
+    runBridgeServerAndGatewayReceiverTest(new String[] {groupName}, null, true);
+  }
+
+  @Test
+  public void testBridgeServerAndGatewayReceiverClientWithGroupServerWithoutGroup()
+      throws Exception {
+    String groupName = "group1";
+    runBridgeServerAndGatewayReceiverTest(null, groupName, false);
+  }
+
+  private void runBridgeServerAndGatewayReceiverTest(String[] serverGroups, String clientGroup,
+      boolean oneServerExpected) throws Exception {
+    final Host host = Host.getHost(0);
+    VM vm0 = host.getVM(0);
+    VM vm1 = host.getVM(1);
+    VM vm2 = host.getVM(2);
+
+    int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    startLocatorInVM(vm0, locatorPort, "");
+
+    String locators = NetworkUtils.getServerHostName(vm0.getHost()) + "[" + locatorPort + "]";
+
+    int serverPort = startBridgeServerInVM(vm1, serverGroups, locators, true);
+
+    addGatewayReceiverToVM(vm1);
+
+    startBridgeClientInVM(vm2, clientGroup, NetworkUtils.getServerHostName(vm0.getHost()),
+        locatorPort);
+
+    // Verify getAllServers returns a valid number of servers
+    verifyGetAllServers(vm2, REGION_NAME, serverPort, oneServerExpected);
+  }
+
+  private void addGatewayReceiverToVM(VM vm) {
+    vm.invoke(new SerializableRunnable("add GatewayReceiver") {
+      public void run() {
+        Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
+        GatewayReceiverFactory fact = cache.createGatewayReceiverFactory();
+        GatewayReceiver receiver = fact.create();
+        assertTrue(receiver.isRunning());
+      }
+    });
+  }
+
+  private void verifyGetAllServers(VM vm, final String regionName, final int serverPort,
+      final boolean oneServerExpected) {
+    vm.invoke(new SerializableRunnable("verify getAllServers") {
+      public void run() {
+        Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
+        Region region = cache.getRegion(regionName);
+        PoolImpl pool = (PoolImpl) PoolManager.find(region);
+        AutoConnectionSourceImpl connectionSource =
+            (AutoConnectionSourceImpl) pool.getConnectionSource();
+        List<ServerLocation> allServers = connectionSource.getAllServers();
+        if (oneServerExpected) {
+          // One server is expected. Assert one was returned, and its port matches the input
+          // serverPort.
+          assertEquals(1, allServers.size());
+          ServerLocation serverLocation = allServers.get(0);
+          assertEquals(serverPort, serverLocation.getPort());
+        } else {
+          // No servers are expected. Assert none were returned.
+          assertNull(allServers);
+        }
+      }
+    });
+  }
+}


[46/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 289d6d7..97fdab1 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
@@ -14,6 +14,7 @@
  */
 package org.apache.geode.management;
 
+import static com.jayway.awaitility.Awaitility.*;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static org.junit.Assert.*;
 
@@ -21,8 +22,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;
@@ -36,31 +40,27 @@ 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
   }
 
@@ -139,28 +139,20 @@ 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 {
@@ -209,8 +201,6 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Tests the fragmentation statistic for off-heap memory.
-   * 
-   * @throws Exception
    */
   @Test
   public void testFragmentationStat() throws Exception {
@@ -300,9 +290,7 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
   }
 
   /**
-   * 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 {
@@ -476,12 +464,13 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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) {
+  private void doFreeOffHeapMemoryOnVm(final VM vm, final int numAllocations,
+      final int numDestroys) {
     vm.invoke(new SerializableRunnable() {
       @Override
       public void run() {
@@ -492,11 +481,11 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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);
@@ -520,34 +509,29 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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) {
+      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) {
@@ -558,28 +542,23 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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,
+  private void assertCompactionTimeStatOnVm(final VM vm, final long compactionTime,
       final ASSERT_OP op) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertCompactionTimeStat(compactionTime, 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) {
+  private void assertCompactionTimeStat(final long compactionTime, final ASSERT_OP op) {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -606,27 +585,23 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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) {
+  private void assertFragmentationStat(final int fragmentation, final ASSERT_OP op) {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -651,7 +626,7 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
   /**
    * 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");
@@ -664,16 +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());
   }
 
   /**
@@ -696,20 +666,14 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
   /**
    * 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() {
+  private void assertOffHeapRegionAttributes() {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -726,33 +690,28 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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) {
+  private void assertOffHeapMetrics(final long freeMemory, final long allocatedMemory,
+      final long objects, final int fragmentation) {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -769,57 +728,49 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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,
+  private 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));
-      }
-    });
+    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) {
@@ -832,27 +783,22 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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) {
+  private void doDestroy(final Object key, final String regionName) {
     Region region = getCache().getRegion(regionName);
     assertNotNull(region);
 
@@ -861,59 +807,54 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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) {
+  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() {
+  private void addOffHeapNotificationListener() {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -929,116 +870,90 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * 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,
+  private void waitForNotificationListenerOnVm(final 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);
-      }
-    });
+    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();
-      }
-    });
+  private void clearNotificationListenerOnVm(final VM vm) {
+    vm.invoke(() -> notificationListener.clear());
   }
-}
 
+  /**
+   * Collects MBean Notifications.
+   */
+  private static class OffHeapNotificationListener implements NotificationListener {
 
-/**
- * Collects MBean Notifications.
- */
-class OffHeapNotificationListener implements NotificationListener {
-  List<Notification> notificationList = Collections.synchronizedList(new ArrayList<Notification>());
+    List<Notification> notificationList =
+        Collections.synchronizedList(new ArrayList<Notification>());
 
-  @Override
-  public void handleNotification(Notification notification, Object handback) {
-    this.notificationList.add(notification);
-  }
+    @Override
+    public void handleNotification(final Notification notification, final Object handback) {
+      this.notificationList.add(notification);
+    }
 
-  public void clear() {
-    this.notificationList.clear();
-  }
+    public void clear() {
+      this.notificationList.clear();
+    }
 
-  public int getNotificationSize() {
-    return this.notificationList.size();
+    public int getNotificationSize() {
+      return this.notificationList.size();
+    }
   }
 }


[27/50] [abbrv] geode git commit: Merge branch 'feature/GEODE-2201' into develop

Posted by kl...@apache.org.
Merge branch 'feature/GEODE-2201' into develop


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

Branch: refs/heads/feature/GEODE-1930
Commit: df8730d9de9eb0a730cf1c61cf845748418747cb
Parents: ef86239 d427613
Author: Jens Deppe <jd...@pivotal.io>
Authored: Sun Dec 11 20:17:41 2016 -0800
Committer: Jens Deppe <jd...@pivotal.io>
Committed: Sun Dec 11 20:17:41 2016 -0800

----------------------------------------------------------------------
 .../tests/rules/ScreenshotOnFailureRule.java    |  2 +-
 .../tools/pulse/tests/rules/WebDriverRule.java  |  4 +-
 .../tools/pulse/tests/ui/PulseTestUtils.java    | 54 +++++++++++---------
 3 files changed, 33 insertions(+), 27 deletions(-)
----------------------------------------------------------------------



[08/50] [abbrv] geode git commit: GEODE-2092 Update docs with security examples location

Posted by kl...@apache.org.
GEODE-2092 Update docs with security examples location


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

Branch: refs/heads/feature/GEODE-1930
Commit: 22ec6a789a1cbf64e1d7677078558e17efb0c668
Parents: 860d7ef
Author: Karen Miller <km...@pivotal.io>
Authored: Wed Dec 7 12:55:48 2016 -0800
Committer: Karen Miller <km...@pivotal.io>
Committed: Wed Dec 7 14:16:40 2016 -0800

----------------------------------------------------------------------
 geode-docs/managing/security/authentication_examples.html.md.erb | 2 +-
 geode-docs/managing/security/authorization_example.html.md.erb   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/22ec6a78/geode-docs/managing/security/authentication_examples.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/managing/security/authentication_examples.html.md.erb b/geode-docs/managing/security/authentication_examples.html.md.erb
index b7634c8..ce21bac 100644
--- a/geode-docs/managing/security/authentication_examples.html.md.erb
+++ b/geode-docs/managing/security/authentication_examples.html.md.erb
@@ -23,7 +23,7 @@ This example demonstrates the basics of an implementation of the
 `SecurityManager.authenticate` method.
 The remainder of the example may be found within the Apache Geode
 source code within the
-`geode-core/src/main/java/org/apache/geode/security/templates` directory.
+`geode-core/src/main/java/org/apache/geode/examples/security` directory.
 
 Of course, the security implementation of every installation is unique,
 so this example cannot be used in a production environment.

http://git-wip-us.apache.org/repos/asf/geode/blob/22ec6a78/geode-docs/managing/security/authorization_example.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/managing/security/authorization_example.html.md.erb b/geode-docs/managing/security/authorization_example.html.md.erb
index 2e725a1..36182c7 100644
--- a/geode-docs/managing/security/authorization_example.html.md.erb
+++ b/geode-docs/managing/security/authorization_example.html.md.erb
@@ -23,7 +23,7 @@ This example demonstrates the basics of an implementation of the
 `SecurityManager.authorize` method.
 The remainder of the example may be found within the Apache Geode
 source code within the
-`geode-core/src/main/java/org/apache/geode/security/templates` directory.
+`geode-core/src/main/java/org/apache/geode/examples/security` directory.
 
 Of course, the security implementation of every installation is unique,
 so this example cannot be used in a production environment,


[29/50] [abbrv] geode git commit: GEODE-2098 Document that gfsh history is in .geode dir

Posted by kl...@apache.org.
GEODE-2098 Document that gfsh history is in .geode dir


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

Branch: refs/heads/feature/GEODE-1930
Commit: 03c79a68b0eaf3926053f5cb34c0f2c96829bb05
Parents: 0f8ef97
Author: Karen Miller <km...@pivotal.io>
Authored: Fri Dec 9 15:48:25 2016 -0800
Committer: Karen Miller <km...@pivotal.io>
Committed: Mon Dec 12 08:18:18 2016 -0800

----------------------------------------------------------------------
 geode-docs/tools_modules/gfsh/command-pages/history.html.md.erb | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/03c79a68/geode-docs/tools_modules/gfsh/command-pages/history.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/tools_modules/gfsh/command-pages/history.html.md.erb b/geode-docs/tools_modules/gfsh/command-pages/history.html.md.erb
index 04e4736..aa625c2 100644
--- a/geode-docs/tools_modules/gfsh/command-pages/history.html.md.erb
+++ b/geode-docs/tools_modules/gfsh/command-pages/history.html.md.erb
@@ -23,7 +23,9 @@ Show or save the command history.
 
 This history can be saved to a file which can also be used as a script later.
 
-A history of commands that have been executed successfully is also logged in `.gfsh.history` file in the home directory of the user running gfsh.
+A history of commands that have been executed successfully is also logged in
+the `.geode/.gfsh.history` file within the home directory of
+the user running gfsh.
 
 **Availability:** Online or offline.
 


[44/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 fcdc3a4..3dc92b6 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
@@ -12,22 +12,44 @@
  * or implied. 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;
 
@@ -41,1325 +63,1156 @@ 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";
+  @Manager
+  private VM managerVM;
 
-  static final String REGION_PATH = "/MANAGEMENT_TEST_REGION";
+  @Member
+  private VM[] memberVMs;
 
-  static final String PARTITIONED_REGION_PATH = "/MANAGEMENT_PAR_REGION";
+  @Before
+  public void before() throws Exception {
+    this.managerVM = getHost(0).getVM(0);
 
-  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;
-
-  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);
-
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
-
-      createDistributedRegion(vm, REGION_NAME);
-      validateReplicateRegionAfterCreate(vm);
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
+    for (VM memberVM : this.memberVMs) {
+      createDistributedRegion_tmp(memberVM, REGION_NAME);
+      verifyReplicateRegionAfterCreate(memberVM);
     }
 
-    verifyRemoteDistributedRegion(managingNode, 3);
-
+    verifyRemoteDistributedRegion(this.managerVM, 3);
 
-    for (VM vm : getManagedNodeList()) {
-      closeRegion(vm, REGION_PATH);
-      validateReplicatedRegionAfterClose(vm);
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
+      verifyReplicatedRegionAfterClose(memberVM);
     }
 
-    ensureProxyCleanup(managingNode);
+    verifyProxyCleanup(this.managerVM);
+
+    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()];
+    createMembersAndThenManagers_tmp();
 
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
-    addMemberListener(managingNode);
-
-    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);
     }
 
+    verifyRemotePartitionRegion(this.managerVM);
 
-    validateRemotePartitionRegion(managingNode);
-
-    for (VM vm : getManagedNodeList()) {
-
-      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);
-
-    for (int j = 0; j < managedNodes.length; j++) {
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
-      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);
-
-    VM managingNode = getManagingNode();
-
-    VM[] managedNodes = new VM[getManagedNodeList().size()];
+    createManagersAndThenMembers_tmp();
 
-    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);
     }
 
+    verifyDistributedMBean(this.managerVM, 3);
+    createDistributedRegion_tmp(this.managerVM, REGION_NAME);
+    verifyDistributedMBean(this.managerVM, 4);
 
-    validateDistributedMBean(managingNode, 3);
-
-    createDistributedRegion(managingNode, REGION_NAME);
-    validateDistributedMBean(managingNode, 4);
-
-
-
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
-
-      closeRegion(vm, REGION_PATH);
-
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
     }
-    ensureProxyCleanup(managingNode);
-
-    validateDistributedMBean(managingNode, 1);
 
-    closeRegion(managingNode, REGION_PATH);
-    validateDistributedMBean(managingNode, 0);
+    verifyProxyCleanup(this.managerVM);
 
+    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>();
+    createManagersAndThenMembers_tmp();
 
-    for (VM vm : managedNodeList) {
-      memberIds.add(getMemberId(vm));
+    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);
 
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
+    }
+    closeRegion(this.managerVM, REGION_PATH);
   }
 
-
-
   @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);
-    }
+    createMembersAndThenManagers_tmp();
 
-    for (VM vm : managedNodeList) {
-      checkSubRegions(vm, LOCAL_SUB_REGION_PATH);
+    for (VM memberVM : this.memberVMs) {
+      createLocalRegion_tmp(memberVM, LOCAL_REGION_NAME);
+      createSubRegion_tmp(memberVM, LOCAL_REGION_NAME, LOCAL_SUB_REGION_NAME);
     }
 
-    for (VM vm : managedNodeList) {
-      closeRegion(vm, LOCAL_REGION_NAME);
-      checkNullRegions(vm, LOCAL_SUB_REGION_NAME);
+    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 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 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);
-          }
-
-        }
-      });
-
-    }
-
+    createMembersAndThenManagers_tmp();
+    createSpecialRegion(this.memberVMs[0]);
+    verifySpecialRegion(this.managerVM);
   }
 
   @Test
   public void testLruStats() throws Exception {
-    initManagement(false);
-    for (VM vm : managedNodeList) {
-      createDiskRegion(vm);
-
+    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);
+    });
   }
 
-  protected LRUStatistics getLRUStats(Region region) {
-    final LocalRegion l = (LocalRegion) region;
-    return l.getEvictionController().getLRUHelper().getStats();
+  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);
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void checkSubRegions(VM vm1, final String subRegionPath) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
-
-          RegionMXBean bean = managementService.getLocalRegionMBean(subRegionPath);
-          assertNotNull(bean);
-
-        }
-      });
-
-    }
+  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 checkNullRegions(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);
-          assertNull(bean);
+  private void verifyNavigationApis(final VM managerVM, final List<String> memberIds) {
+    managerVM.invoke("verifyNavigationApis", () -> {
+      ManagementService service = getManagementService_tmp();
+      assertThat(service.getDistributedSystemMXBean()).isNotNull();
 
-        }
-      });
+      awaitMemberCount(4);
 
-    }
-  }
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      assertThat(distributedSystemMXBean.listDistributedRegionObjectNames()).hasSize(2);
 
+      assertThat(distributedSystemMXBean.fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH))
+          .isNotNull();
+      assertThat(distributedSystemMXBean.fetchDistributedRegionObjectName(REGION_PATH)).isNotNull();
 
+      ObjectName actualName =
+          distributedSystemMXBean.fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH);
+      ObjectName expectedName =
+          MBeanJMXAdapter.getDistributedRegionMbeanName(PARTITIONED_REGION_PATH);
+      assertThat(actualName).isEqualTo(expectedName);
 
-  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();
+      actualName = distributedSystemMXBean.fetchDistributedRegionObjectName(REGION_PATH);
+      expectedName = MBeanJMXAdapter.getDistributedRegionMbeanName(REGION_PATH);
+      assertThat(actualName).isEqualTo(expectedName);
 
-        assertNotNull(service.getDistributedSystemMXBean());
+      for (String memberId : memberIds) {
+        ObjectName objectName = MBeanJMXAdapter.getMemberMBeanName(memberId);
+        awaitMemberMXBeanProxy(objectName);
 
-        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);
+        ObjectName[] objectNames = distributedSystemMXBean.fetchRegionObjectNames(objectName);
+        assertThat(objectNames).isNotNull();
+        assertThat(objectNames).hasSize(2);
 
-          actualName = bean.fetchDistributedRegionObjectName(REGION_PATH);
-          expectedName = MBeanJMXAdapter.getDistributedRegionMbeanName(REGION_PATH);
-          assertEquals(expectedName, actualName);
+        List<ObjectName> listOfNames = Arrays.asList(objectNames);
 
-        } catch (Exception e) {
-          fail("fetchDistributedRegionObjectName () Unsuccessful " + e);
-        }
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, PARTITIONED_REGION_PATH);
+        assertThat(listOfNames).contains(expectedName);
 
-        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);
-          }
-        }
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, REGION_PATH);
+        assertThat(listOfNames).contains(expectedName);
+      }
 
-        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 ");
-          }
-        }
+      for (String memberId : memberIds) {
+        ObjectName objectName = MBeanJMXAdapter.getMemberMBeanName(memberId);
+        awaitMemberMXBeanProxy(objectName);
 
-      }
-    };
-    vm.invoke(checkNavigationAPIS);
-  }
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, PARTITIONED_REGION_PATH);
+        awaitRegionMXBeanProxy(expectedName);
 
+        actualName =
+            distributedSystemMXBean.fetchRegionObjectName(memberId, PARTITIONED_REGION_PATH);
+        assertThat(actualName).isEqualTo(expectedName);
 
-  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);
-        }
+        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());
-
-    RegionMXBean bean = service.getLocalRegionMBean(FIXED_PR_PATH);
-    RegionAttributes regAttrs = fixedPrRegion.getAttributes();
-
-    LogWriterUtils.getLogWriter().info("FixedPartitionAttribute From GemFire :"
-        + regAttrs.getPartitionAttributes().getFixedPartitionAttributes());
+    partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
 
-    RegionAttributesData data = bean.listRegionAttributes();
+    AttributesFactory attributesFactory = new AttributesFactory();
+    attributesFactory.setPartitionAttributes(partitionAttributesFactory.create());
 
-    PartitionAttributesData parData = bean.listPartitionAttributes();
+    fixedPartitionedRegion = getCache_tmp().createRegion(FIXED_PR_NAME, attributesFactory.create());
+    assertThat(fixedPartitionedRegion).isNotNull();
 
-    assertPartitionData(regAttrs, parData);
+    RegionMXBean regionMXBean = service.getLocalRegionMBean(FIXED_PR_PATH);
+    RegionAttributes regionAttributes = fixedPartitionedRegion.getAttributes();
 
-    FixedPartitionAttributesData[] fixedPrData = bean.listFixedPartitionAttributes();
+    PartitionAttributesData partitionAttributesData = regionMXBean.listPartitionAttributes();
+    verifyPartitionData(regionAttributes, partitionAttributesData);
 
-    assertNotNull(fixedPrData);
+    FixedPartitionAttributesData[] fixedPartitionAttributesData =
+        regionMXBean.listFixedPartitionAttributes();
+    assertThat(fixedPartitionAttributesData).isNotNull();
+    assertThat(fixedPartitionAttributesData).hasSize(3);
 
-    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);
-
+    });
   }
 
   /**
    * Add a Notification listener to DistributedSystemMBean which should gather 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;
-
-        DistrNotif regionCreate = new DistrNotif();
-
-        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);
+  private void addSystemNotificationListener(final VM managerVM) {
+    managerVM.invoke("addSystemNotificationListener", () -> {
+      awaitDistributedSystemMXBean();
+
+      List<Notification> notifications = new ArrayList<>();
+      SYSTEM_NOTIFICATIONS_REF.set(notifications);
+
+      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);
-  }
-
-  /**
-   * 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);
-        }
-
-        assertNotNull(bean);
-        assertEquals(REGION_PATH, bean.getFullPath());
 
+      assertThat(regionCreatedCount).isEqualTo(1); // just the manager
+      assertThat(regionDestroyedCount).isEqualTo(expectedMembers + 1); // all 3 members + manager
+    });
+  }
 
+  // <[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]]>
+
+  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);
+    });
   }
 
+  private void verifyRemoteDistributedRegion(final VM managerVM, final int expectedMembers)
+      throws Exception {
+    managerVM.invoke("verifyRemoteDistributedRegion", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+      assertThat(otherMemberSet).hasSize(expectedMembers);
 
-  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;
-
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
-
-              public boolean done() {
-                DistributedRegionMXBean bean = service.getDistributedRegionMXBean(REGION_PATH);
-                boolean done = (bean == null);
-                return done;
-              }
+      for (DistributedMember member : otherMemberSet) {
+        RegionMXBean regionMXBean = awaitRegionMXBeanProxy(member, REGION_PATH);
 
-            }, MAX_WAIT, 500, true);
+        RegionAttributesData regionAttributesData = regionMXBean.listRegionAttributes();
+        assertThat(regionAttributesData).isNotNull();
 
-          } catch (Exception e) {
-            fail("could not remove Aggregate Bean in required time");
+        MembershipAttributesData membershipAttributesData = regionMXBean.listMembershipAttributes();
+        assertThat(membershipAttributesData).isNotNull();
 
-          }
-          return;
-        }
-
-        try {
-          bean = MBeanUtil.getDistributedRegionMbean(REGION_PATH, expectedMembers);
-          sysMBean = service.getDistributedSystemMXBean();
-        } catch (Exception e) {
-          InternalDistributedSystem.getLoggerI18n()
-              .fine("Undesired Result , DistributedRegionMXBean Should not be null" + e);
-        }
+        EvictionAttributesData evictionAttributesData = regionMXBean.listEvictionAttributes();
+        assertThat(evictionAttributesData).isNotNull();
+      }
 
-        assertNotNull(bean);
-        assertEquals(REGION_PATH, bean.getFullPath());
-        assertEquals(expectedMembers, bean.getMemberCount());
-        assertEquals(expectedMembers, bean.getMembers().length);
+      DistributedRegionMXBean distributedRegionMXBean =
+          awaitDistributedRegionMXBean(REGION_PATH, expectedMembers);
 
-        // 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);
+      DistributedRegionMXBean distributedRegionMXBean =
+          awaitDistributedRegionMXBean(REGION_PATH, expectedMembers);
+
+      assertThat(distributedRegionMXBean.getFullPath()).isEqualTo(REGION_PATH);
+      assertThat(distributedRegionMXBean.getMemberCount()).isEqualTo(expectedMembers);
+      assertThat(distributedRegionMXBean.getMembers()).hasSize(expectedMembers);
+
+      // 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> ");
+    });
   }
 
-  /**
-   * 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);
+  private void verifyRemotePartitionRegion(final VM managerVM) throws Exception {
+    managerVM.invoke("verifyRemotePartitionRegion", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
 
+      for (DistributedMember member : otherMemberSet) {
+        RegionMXBean regionMXBean = awaitRegionMXBeanProxy(member, PARTITIONED_REGION_PATH);
+        PartitionAttributesData partitionAttributesData = regionMXBean.listPartitionAttributes();
+        assertThat(partitionAttributesData).isNotNull();
       }
 
-    };
-    vm.invoke(verifyRegion);
+      ManagementService service = getManagementService_tmp();
+      DistributedRegionMXBean distributedRegionMXBean =
+          service.getDistributedRegionMXBean(PARTITIONED_REGION_PATH);
+      assertThat(distributedRegionMXBean.getMembers()).hasSize(3);
+    });
   }
 
+  private void verifyReplicateRegionAfterCreate(final VM memberVM) {
+    memberVM.invoke("verifyReplicateRegionAfterCreate", () -> {
+      Cache cache = getCache_tmp();
 
+      String memberId =
+          MBeanJMXAdapter.getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());
+      ObjectName objectName = ObjectName.getInstance("GemFire:type=Member,member=" + memberId);
 
-  /**
-   * Creates a Distributed Region
-   * 
-   * @param vm
-   */
-  protected void validateReplicateRegionAfterCreate(final VM vm) {
-    SerializableRunnable checkDistributedRegion =
-        new SerializableRunnable("Check Distributed region") {
-          public void run() {
-
-            GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            SystemManagementService service = (SystemManagementService) getManagementService();
-
-            MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-            RegionNotif test = new RegionNotif();
-
-            String memberId = MBeanJMXAdapter
-                .getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());
-
-            ObjectName memberMBeanName;
-            try {
-              memberMBeanName = ObjectName.getInstance("GemFire:type=Member,member=" + memberId);
-              mbeanServer.addNotificationListener(memberMBeanName, test, null, null);
-            } catch (MalformedObjectNameException e) {
-
-              Assert.fail("FAILED WITH EXCEPION", e);
-            } catch (NullPointerException e) {
-              Assert.fail("FAILED WITH EXCEPION", e);
-
-            } catch (InstanceNotFoundException e) {
-              Assert.fail("FAILED WITH EXCEPION", e);
+      // List<Notification> notifications = new ArrayList<>();
+      // MEMBER_NOTIFICATIONS_REF.set(notifications);
+      //
+      // MemberNotificationListener listener = new MemberNotificationListener(notifications);
+      // ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener,
+      // null, null);
 
-            }
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(REGION_PATH);
+      assertThat(regionMXBean).isNotNull();
 
-            assertNotNull(service.getLocalRegionMBean(REGION_PATH));
+      Region region = cache.getRegion(REGION_PATH);
+      RegionAttributes regionAttributes = region.getAttributes();
 
-            RegionMXBean bean = service.getLocalRegionMBean(REGION_PATH);
-            Region region = cache.getRegion(REGION_PATH);
+      RegionAttributesData regionAttributesData = regionMXBean.listRegionAttributes();
+      verifyRegionAttributes(regionAttributes, regionAttributesData);
 
-            RegionAttributes regAttrs = region.getAttributes();
+      MembershipAttributesData membershipData = regionMXBean.listMembershipAttributes();
+      assertThat(membershipData).isNotNull();
 
-            RegionAttributesData data = bean.listRegionAttributes();
-
-            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);
+      EvictionAttributesData evictionData = regionMXBean.listEvictionAttributes();
+      assertThat(evictionData).isNotNull();
+    });
   }
 
-  /**
-   * 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);
+  private void verifyPartitionRegionAfterCreate(final VM memberVM) {
+    memberVM.invoke("verifyPartitionRegionAfterCreate", () -> {
+      Region region = getCache_tmp().getRegion(PARTITIONED_REGION_PATH);
 
-      }
-    };
-    vm.invoke(createParRegion);
-  }
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
 
-  /**
-   * 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);
+      verifyPartitionData(region.getAttributes(), regionMXBean.listPartitionAttributes());
+    });
   }
 
-  /**
-   * 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 verifyReplicatedRegionAfterClose(final VM memberVM) {
+    memberVM.invoke("verifyReplicatedRegionAfterClose", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(REGION_PATH);
+      assertThat(regionMXBean).isNull();
+
+      ObjectName objectName = service.getRegionMBeanName(
+          getCache_tmp().getDistributedSystem().getDistributedMember(), REGION_PATH);
+      assertThat(service.getLocalManager().getManagementResourceRepo()
+          .getEntryFromLocalMonitoringRegion(objectName)).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);
+  private void verifyPartitionRegionAfterClose(final VM memberVM) {
+    memberVM.invoke("verifyPartitionRegionAfterClose", () -> {
+      ManagementService service = getManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
+      assertThat(regionMXBean).isNull();
+    });
   }
 
   /**
-   * 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]);
       }
-
     }
 
+    assertThat(regionAttributesData.getRegionTimeToLive())
+        .isEqualTo(regionAttributes.getRegionTimeToLive().getTimeout());
 
+    assertThat(regionAttributesData.getRegionIdleTimeout())
+        .isEqualTo(regionAttributes.getRegionIdleTimeout().getTimeout());
 
-    int regionTimeToLive = regAttrs.getRegionTimeToLive().getTimeout();
-
-    assertEquals(regionTimeToLive, data.getRegionTimeToLive());
-
-    int regionIdleTimeout = regAttrs.getRegionIdleTimeout().getTimeout();
-
-    assertEquals(regionIdleTimeout, data.getRegionIdleTimeout());
+    assertThat(regionAttributesData.getEntryTimeToLive())
+        .isEqualTo(regionAttributes.getEntryTimeToLive().getTimeout());
 
-    int entryTimeToLive = regAttrs.getEntryTimeToLive().getTimeout();
+    assertThat(regionAttributesData.getEntryIdleTimeout())
+        .isEqualTo(regionAttributes.getEntryIdleTimeout().getTimeout());
 
-    assertEquals(entryTimeToLive, data.getEntryTimeToLive());
-
-    int entryIdleTimeout = regAttrs.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);
+    String alias = "awaiting MemberMXBean proxy for " + member;
+
+    await(alias)
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
+  }
+
+  private MemberMXBean awaitMemberMXBeanProxy(final ObjectName objectName) {
+    SystemManagementService service = getSystemManagementService_tmp();
+    await()
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
+    return service.getMBeanProxy(objectName, MemberMXBean.cla

<TRUNCATED>

[21/50] [abbrv] geode git commit: GEODE-1984: Addressed review comments, Removed copy pasted repeating code and moved it into a separate method.

Posted by kl...@apache.org.
GEODE-1984: Addressed review comments,
Removed copy pasted repeating code and moved it into a separate method.


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

Branch: refs/heads/feature/GEODE-1930
Commit: f522f6ca6a3fd362e5d6657ef451743a68a4c0dc
Parents: 0eb952a
Author: adongre <ad...@apache.org>
Authored: Thu Dec 8 12:53:05 2016 +0530
Committer: adongre <ad...@apache.org>
Committed: Fri Dec 9 05:08:36 2016 +0530

----------------------------------------------------------------------
 .../apache/geode/cache/wan/GatewaySender.java   |  16 +-
 .../functions/GatewaySenderDestroyFunction.java |   2 +-
 .../codeAnalysis/sanctionedSerializables.txt    |   2 +-
 .../wan/wancommand/WANCommandTestBase.java      |   4 +-
 ...mandCreateDestroyGatewaySenderDUnitTest.java | 265 +++++--------------
 5 files changed, 79 insertions(+), 210 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/f522f6ca/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java b/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java
index f9f8f91..1dc1fb1 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java
@@ -402,17 +402,15 @@ public interface GatewaySender {
 
 
   /**
-   * Destroys the GatewaySender. Before destroying the sender, caller needs to to ensure that the
-   * sender is stopped so that all the resources (threads, connection pool etc.) will be released
-   * properly. Stopping the sender is not handled in the destroy. Destroy is carried out in
-   * following steps: 1. Take the lifeCycleLock. 2. If the sender is attached to any application
-   * region, throw an exception. 3. Close the GatewaySenderAdvisor. 4. Remove the sender from the
-   * cache. 5. Destroy the region underlying the GatewaySender.
+   * Destroys the GatewaySender.
    * <p>
-   * In case of ParallelGatewaySender, the destroy operation does distributed destroy of the QPR. In
-   * case of SerialGatewaySender, the queue region is destroyed locally.
+   * In case of ParallelGatewaySender, the destroy operation does distributed destroy of the Queue
+   * Region. In case of SerialGatewaySender, the Queue Region is destroyed locally.
+   * 
+   * @since Geode 1.1
+   *
    */
-  public void destroy();
+  void destroy();
 
 
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/f522f6ca/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java
index ba393fe..2873633 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java
@@ -28,7 +28,7 @@ import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.logging.log4j.Logger;
 
 public class GatewaySenderDestroyFunction extends FunctionAdapter implements InternalEntity {
-  private static final long serialVersionUID = 1459761440357690134L;
+  private static final long serialVersionUID = 1L;
 
   private static final Logger logger = LogService.getLogger();
   private static final String ID = GatewaySenderDestroyFunction.class.getName();

http://git-wip-us.apache.org/repos/asf/geode/blob/f522f6ca/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt b/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
index 5ce46bf..1aac8c2 100644
--- a/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
+++ b/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
@@ -569,7 +569,7 @@ org/apache/geode/management/internal/cli/functions/GarbageCollectionFunction,tru
 org/apache/geode/management/internal/cli/functions/GatewayReceiverCreateFunction,true,8746830191680509335
 org/apache/geode/management/internal/cli/functions/GatewayReceiverFunctionArgs,true,-5158224572470173267,bindAddress:java/lang/String,endPort:java/lang/Integer,gatewayTransportFilters:java/lang/String[],manualStart:java/lang/Boolean,maximumTimeBetweenPings:java/lang/Integer,socketBufferSize:java/lang/Integer,startPort:java/lang/Integer
 org/apache/geode/management/internal/cli/functions/GatewaySenderCreateFunction,true,8746830191680509335
-org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction,true,1459761440357690134
+org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction,true,1
 org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunctionArgs,true,3848480256348119530,id:java/lang/String
 org/apache/geode/management/internal/cli/functions/GatewaySenderFunctionArgs,true,-5158224572470173267,alertThreshold:java/lang/Integer,batchSize:java/lang/Integer,batchTimeInterval:java/lang/Integer,diskStoreName:java/lang/String,diskSynchronous:java/lang/Boolean,dispatcherThreads:java/lang/Integer,enableBatchConflation:java/lang/Boolean,enablePersistence:java/lang/Boolean,gatewayEventFilters:java/lang/String[],gatewayTransportFilters:java/lang/String[],id:java/lang/String,manualStart:java/lang/Boolean,maxQueueMemory:java/lang/Integer,orderPolicy:java/lang/String,parallel:java/lang/Boolean,remoteDSId:java/lang/Integer,socketBufferSize:java/lang/Integer,socketReadTimeout:java/lang/Integer
 org/apache/geode/management/internal/cli/functions/GetMemberConfigInformationFunction,true,1

http://git-wip-us.apache.org/repos/asf/geode/blob/f522f6ca/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java
index f364ba3..5578f76 100644
--- a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java
+++ b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java
@@ -452,9 +452,6 @@ public abstract class WANCommandTestBase extends CliCommandTestBase {
     }
   }
 
-  // Added for gateway destroy command
-  // Copied from WANTestBase.java
-
   public static void verifySenderDestroyed(String senderId, boolean isParallel) {
     Set<GatewaySender> senders = cache.getGatewaySenders();
     AbstractGatewaySender sender = null;
@@ -473,6 +470,7 @@ public abstract class WANCommandTestBase extends CliCommandTestBase {
       queueRegionNameSuffix = "_SERIAL_GATEWAY_SENDER_QUEUE";
     }
 
+
     Set<LocalRegion> allRegions = ((GemFireCacheImpl) cache).getAllRegions();
     for (LocalRegion region : allRegions) {
       if (region.getName().indexOf(senderId + queueRegionNameSuffix) != -1) {

http://git-wip-us.apache.org/repos/asf/geode/blob/f522f6ca/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java
index d095764..8d1f5d8 100644
--- a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java
+++ b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java
@@ -23,11 +23,13 @@ import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.result.TabularResultData;
 import org.apache.geode.test.dunit.IgnoredException;
+import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.Properties;
 
@@ -95,32 +97,11 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
     vm4.invoke(() -> verifySenderState("ln", true, false));
     vm5.invoke(() -> verifySenderState("ln", true, false));
 
-    // Test Destroy Command.
-    command =
-        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
-    cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info(
-          "testCreateDestroyGatewaySenderWithDefault stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender destroy failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
+    doDestroyAndVerifyGatewaySender("ln", null, null, "testCreateDestroyGatewaySenderWithDefault",
+        Arrays.asList(vm3, vm4, vm5), 5, false);
+  }
 
-    } else {
-      fail("testCreateDestroyGatewaySenderWithDefault failed as did not get CommandResult");
-    }
 
-    vm3.invoke(() -> verifySenderDestroyed("ln", false));
-    vm4.invoke(() -> verifySenderDestroyed("ln", false));
-    vm5.invoke(() -> verifySenderDestroyed("ln", false));
-  }
 
   /**
    * + * GatewaySender with given attribute values +
@@ -186,29 +167,8 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
     vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
         1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
 
-    // Test Destroy Command.
-    command =
-        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
-    cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateDestroyGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender destroy failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateDestroyGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderDestroyed("ln", false));
-    vm4.invoke(() -> verifySenderDestroyed("ln", false));
-    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+    doDestroyAndVerifyGatewaySender("ln", null, null, "testCreateDestroyGatewaySender",
+        Arrays.asList(vm3, vm4, vm5), 5, false);
   }
 
   /**
@@ -336,31 +296,9 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
     vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
         1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, eventFilters, null));
 
-    // Test Destroy Command.
-    command =
-        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
-    cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateDestroyGatewaySenderWithGatewayEventFilters stringResult : "
-          + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender destroy failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail(
-          "testCreateDestroyGatewaySenderWithGatewayEventFilters failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderDestroyed("ln", false));
-    vm4.invoke(() -> verifySenderDestroyed("ln", false));
-    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+    doDestroyAndVerifyGatewaySender("ln", null, null,
+        "testCreateDestroyGatewaySenderWithGatewayEventFilters", Arrays.asList(vm3, vm4, vm5), 5,
+        false);
 
   }
 
@@ -435,33 +373,9 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
     vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
         1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, transportFilters));
 
-    // Test Destroy Command.
-    command =
-        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
-    cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter()
-          .info("testCreateDestroyGatewaySenderWithGatewayTransportFilters stringResult : "
-              + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender destroy failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-
-    } else {
-      fail(
-          "testCreateDestroyGatewaySenderWithGatewayTransportFilters failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderDestroyed("ln", false));
-    vm4.invoke(() -> verifySenderDestroyed("ln", false));
-    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+    doDestroyAndVerifyGatewaySender("ln", null, null,
+        "testCreateDestroyGatewaySenderWithGatewayTransportFilters", Arrays.asList(vm3, vm4, vm5),
+        5, false);
   }
 
   /**
@@ -526,29 +440,8 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
     vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
         1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
 
-    // Test Destroy Command.
-    command = CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__MEMBER + "=" + vm3Member.getId();
-    cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter()
-          .info("testCreateDestroyGatewaySender_OnMember stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(1, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender destroy failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-
-    } else {
-      fail("testCreateDestroyGatewaySender_OnMember failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderDestroyed("ln", false));
+    doDestroyAndVerifyGatewaySender("ln", null, vm3Member,
+        "testCreateDestroyGatewaySender_OnMember", Arrays.asList(vm3), 1, false);
   }
 
   /**
@@ -610,31 +503,8 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
     vm4.invoke(() -> verifySenderState("ln", true, false));
     vm5.invoke(() -> verifySenderState("ln", true, false));
 
-    // Test Destroy Command
-    command = CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.DESTROY_GATEWAYSENDER__GROUP + "=SenderGroup1";
-
-    cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter()
-          .info("testCreateDestroyGatewaySender_Group stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(3, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender destroy failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateDestroyGatewaySender_Group failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderDestroyed("ln", false));
-    vm4.invoke(() -> verifySenderDestroyed("ln", false));
-    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+    doDestroyAndVerifyGatewaySender("ln", "SenderGroup1", null,
+        "testCreateDestroyGatewaySender_Group", Arrays.asList(vm3, vm4, vm5), 3, false);
 
   }
 
@@ -697,31 +567,8 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
     vm3.invoke(() -> verifySenderState("ln", true, false));
     vm4.invoke(() -> verifySenderState("ln", true, false));
 
-
-    // Test Destroy Command
-    command = CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.DESTROY_GATEWAYSENDER__GROUP + "=SenderGroup1";
-
-    cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info(
-          "testCreateDestroyGatewaySender_Group_Scenario2 stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(2, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender destroy failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateDestroyGatewaySender_Group_Scenario2 failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderDestroyed("ln", false));
-    vm4.invoke(() -> verifySenderDestroyed("ln", false));
+    doDestroyAndVerifyGatewaySender("ln", "SenderGroup1", null,
+        "testCreateDestroyGatewaySender_Group_Scenario2", Arrays.asList(vm3, vm4), 2, false);
 
   }
 
@@ -791,30 +638,8 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
         () -> verifySenderAttributes("ln", 2, true, true, 1000, socketReadTimeout, true, 1000, 5000,
             true, false, 1000, 100, GatewaySender.DEFAULT_DISPATCHER_THREADS, null, null, null));
 
-    // Test Destroy Command
-    command =
-        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
-    cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter()
-          .info("testCreateDestroyParallelGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender destroy failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-
-    } else {
-      fail("testCreateDestroyParallelGatewaySender failed as did not get CommandResult");
-    }
-    vm3.invoke(() -> verifySenderDestroyed("ln", true));
-    vm4.invoke(() -> verifySenderDestroyed("ln", true));
-    vm5.invoke(() -> verifySenderDestroyed("ln", true));
+    doDestroyAndVerifyGatewaySender("ln", null, null, "testCreateDestroyParallelGatewaySender",
+        Arrays.asList(vm3, vm4), 5, true);
   }
 
   /**
@@ -918,4 +743,52 @@ public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTes
       fail("testCreateDestroyParallelGatewaySender failed as did not get CommandResult");
     }
   }
+
+  /**
+   * doDestroyAndVerifyGatewaySender helper command.
+   *
+   * @param id if of the Gateway Sender
+   * @param group Group for the GatewaySender
+   * @param member Distributed Member for memeber id.
+   * @param testName testName for the logging
+   * @param vms list of vms where to verify the destroyed gateway sender
+   * @param size command result.
+   * @param isParallel true if parallel , false otherwise.
+   */
+
+  private void doDestroyAndVerifyGatewaySender(final String id, final String group,
+      final DistributedMember member, final String testName, final List<VM> vms, final int size,
+      final boolean isParallel) {
+    String command =
+        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=" + id;
+
+    if (group != null) {
+      command += " --" + CliStrings.DESTROY_GATEWAYSENDER__GROUP + "=" + group;
+    }
+
+    if (member != null) {
+      command += " --" + CliStrings.CREATE_GATEWAYSENDER__MEMBER + "=" + member.getId();
+    }
+
+    final CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info(testName + " stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(size, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+
+    } else {
+      fail(testName + " failed as did not get CommandResult");
+    }
+    for (VM vm : vms) {
+      vm.invoke(() -> verifySenderDestroyed(id, isParallel));
+    }
+  }
 }


[02/50] [abbrv] geode git commit: GEODE-1862: Invoke getAllDurableCqsFromServer on the primary queue server

Posted by kl...@apache.org.
GEODE-1862: Invoke getAllDurableCqsFromServer on the primary queue server

Invoking this method on a server that does not have the queue will
return the wrong results.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 05c2388f5add287aa07a43ca08a85776f8b9f43b
Parents: 9dd4205
Author: Barry Oglesby <bo...@pivotal.io>
Authored: Thu Sep 1 17:40:03 2016 -0700
Committer: Dan Smith <up...@apache.org>
Committed: Tue Dec 6 16:53:20 2016 -0800

----------------------------------------------------------------------
 .../cache/client/internal/ConnectionStats.java  |   4 +
 .../cache/client/internal/GetDurableCQsOp.java  |   2 +-
 .../sockets/DurableClientSimpleDUnitTest.java   | 248 ++++++++++++-------
 3 files changed, 159 insertions(+), 95 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/05c2388f/geode-core/src/main/java/org/apache/geode/cache/client/internal/ConnectionStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/cache/client/internal/ConnectionStats.java b/geode-core/src/main/java/org/apache/geode/cache/client/internal/ConnectionStats.java
index c2229c1..d91719d 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/client/internal/ConnectionStats.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/client/internal/ConnectionStats.java
@@ -3344,6 +3344,10 @@ public class ConnectionStats implements MessageStats {
     return this.stats.getLong(executeFunctionDurationId);
   }
 
+  public int getGetDurableCqs() {
+    return this.stats.getInt(getDurableCQsId);
+  }
+
   /**
    * Records that the specified GetClientPRMetadata operation is starting
    * <p>

http://git-wip-us.apache.org/repos/asf/geode/blob/05c2388f/geode-cq/src/main/java/org/apache/geode/cache/client/internal/GetDurableCQsOp.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/main/java/org/apache/geode/cache/client/internal/GetDurableCQsOp.java b/geode-cq/src/main/java/org/apache/geode/cache/client/internal/GetDurableCQsOp.java
index b520c5d..814931c 100755
--- a/geode-cq/src/main/java/org/apache/geode/cache/client/internal/GetDurableCQsOp.java
+++ b/geode-cq/src/main/java/org/apache/geode/cache/client/internal/GetDurableCQsOp.java
@@ -43,7 +43,7 @@ public class GetDurableCQsOp {
    */
   public static List<String> execute(ExecutablePool pool) {
     AbstractOp op = new GetDurableCQsOpImpl();
-    return (List<String>) pool.execute(op);
+    return (List<String>) pool.executeOnPrimary(op);
   }
 
   private GetDurableCQsOp() {

http://git-wip-us.apache.org/repos/asf/geode/blob/05c2388f/geode-cq/src/test/java/org/apache/geode/internal/cache/tier/sockets/DurableClientSimpleDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/org/apache/geode/internal/cache/tier/sockets/DurableClientSimpleDUnitTest.java b/geode-cq/src/test/java/org/apache/geode/internal/cache/tier/sockets/DurableClientSimpleDUnitTest.java
index 68c397d..0ea7050 100644
--- a/geode-cq/src/test/java/org/apache/geode/internal/cache/tier/sockets/DurableClientSimpleDUnitTest.java
+++ b/geode-cq/src/test/java/org/apache/geode/internal/cache/tier/sockets/DurableClientSimpleDUnitTest.java
@@ -16,12 +16,15 @@ package org.apache.geode.internal.cache.tier.sockets;
 
 import static org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil.TYPE_CREATE;
 import static org.apache.geode.test.dunit.Assert.fail;
+import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
 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.util.Iterator;
+import java.util.List;
+import java.util.Map;
 import java.util.concurrent.TimeUnit;
 
 import org.apache.geode.cache.CacheException;
@@ -31,6 +34,7 @@ import org.apache.geode.cache.Region;
 import org.apache.geode.cache.client.Pool;
 import org.apache.geode.cache.client.PoolManager;
 import org.apache.geode.cache.client.ServerRefusedConnectionException;
+import org.apache.geode.cache.client.internal.ConnectionStats;
 import org.apache.geode.cache.client.internal.PoolImpl;
 import org.apache.geode.cache.query.CqAttributes;
 import org.apache.geode.cache.query.CqAttributesFactory;
@@ -42,6 +46,7 @@ import org.apache.geode.cache.query.QueryService;
 import org.apache.geode.cache.query.RegionNotFoundException;
 import org.apache.geode.cache30.CacheSerializableRunnable;
 import org.apache.geode.distributed.internal.DistributionConfig;
+import org.apache.geode.distributed.internal.ServerLocation;
 import org.apache.geode.internal.cache.ClientServerObserver;
 import org.apache.geode.internal.cache.ClientServerObserverAdapter;
 import org.apache.geode.internal.cache.ClientServerObserverHolder;
@@ -83,8 +88,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     // normally
     final String durableClientId = getName() + "_client";
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));
+        getClientPool(getServerHostName(durableClientVM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));
 
     // Send clientReady message
     this.durableClientVM.invoke(new CacheSerializableRunnable("Send clientReady") {
@@ -109,8 +114,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
     // Start normal publisher client
     this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(publisherClientVM.getHost()), serverPort,
-            false),
+        getClientPool(getServerHostName(publisherClientVM.getHost()), serverPort, false),
         regionName));
 
     // Publish some entries
@@ -147,8 +151,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     final String regionName1 = regionName + "1";
     final String regionName2 = regionName + "2";
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClients(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), serverPort, true),
-        regionName1, regionName2, getClientDistributedSystemProperties(durableClientId)));
+        getClientPool(getServerHostName(durableClientVM.getHost()), serverPort, true), regionName1,
+        regionName2, getClientDistributedSystemProperties(durableClientId)));
 
     // Send clientReady message
     this.durableClientVM.invoke(new CacheSerializableRunnable("Send clientReady") {
@@ -219,8 +223,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     // stops normally
     final String durableClientId = getName() + "_client";
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));
+        getClientPool(getServerHostName(durableClientVM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));
 
     // Send clientReady message
     this.durableClientVM.invoke(new CacheSerializableRunnable("Send clientReady") {
@@ -249,8 +253,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
       public void run2() throws CacheException {
         getSystem(getClientDistributedSystemProperties(durableClientId));
         PoolFactoryImpl pf = (PoolFactoryImpl) PoolManager.createFactory();
-        pf.init(getClientPool(NetworkUtils.getServerHostName(publisherClientVM.getHost()),
-            serverPort, true));
+        pf.init(getClientPool(getServerHostName(publisherClientVM.getHost()), serverPort, true));
         try {
           pf.create("uncreatablePool");
           fail("Should not have been able to create the pool");
@@ -281,8 +284,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
     // Start normal publisher client
     this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(publisherClientVM.getHost()), serverPort,
-            false),
+        getClientPool(getServerHostName(publisherClientVM.getHost()), serverPort, false),
         regionName));
 
     // Publish some entries
@@ -316,8 +318,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     // stops normally
     final String durableClientId = getName() + "_client";
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId)));
+        getClientPool(getServerHostName(durableClientVM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId)));
 
     // Send clientReady message
     this.durableClientVM.invoke(new CacheSerializableRunnable("Send clientReady") {
@@ -332,8 +334,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     VM durableClient2VM = this.publisherClientVM;
     final String durableClientId2 = getName() + "_client2";
     durableClient2VM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClient2VM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId2)));
+        getClientPool(getServerHostName(durableClient2VM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId2)));
 
     // Send clientReady message
     durableClient2VM.invoke(new CacheSerializableRunnable("Send clientReady") {
@@ -404,8 +406,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     final int durableClientTimeout = 60; // keep the client alive for 60 seconds
     // final boolean durableClientKeepAlive = true; // keep the client alive when it stops normally
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), server1Port,
-            server2Port, true),
+        getClientPool(getServerHostName(durableClientVM.getHost()), server1Port, server2Port, true),
         regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
         Boolean.TRUE));
 
@@ -447,10 +448,9 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     });
 
     // Start normal publisher client
-    this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(publisherClientVM.getHost()), server1Port,
-            server2Port, false),
-        regionName));
+    this.publisherClientVM.invoke(() -> CacheServerTestUtil
+        .createCacheClient(getClientPool(getServerHostName(publisherClientVM.getHost()),
+            server1Port, server2Port, false), regionName));
 
     // Publish some entries
     final int numberOfEntries = 10;
@@ -496,8 +496,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
     // Re-start the durable client
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), server1Port,
-            server2Port, true),
+        getClientPool(getServerHostName(durableClientVM.getHost()), server1Port, server2Port, true),
         regionName, getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));
 
     // Send clientReady message
@@ -565,9 +564,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     final int durableClientTimeout = 60; // keep the client alive for 60 seconds
     // final boolean durableClientKeepAlive = true; // keep the client alive when it stops normally
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
-        Boolean.TRUE));
+        getClientPool(getServerHostName(durableClientVM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId, durableClientTimeout), Boolean.TRUE));
 
     // Send clientReady message
     this.durableClientVM.invoke(new CacheSerializableRunnable("Send clientReady") {
@@ -595,8 +593,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     VM durableClient2VM = this.server2VM;
     final String durableClientId2 = getName() + "_client2";
     durableClient2VM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClient2VM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId2, durableClientTimeout),
+        getClientPool(getServerHostName(durableClient2VM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId2, durableClientTimeout),
         Boolean.TRUE));
 
     // Send clientReady message
@@ -648,8 +646,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
     // Start normal publisher client
     this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(publisherClientVM.getHost()), serverPort,
-            false),
+        getClientPool(getServerHostName(publisherClientVM.getHost()), serverPort, false),
         regionName));
 
     // Publish some entries
@@ -726,8 +723,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
     // Re-start durable client 1
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));
+        getClientPool(getServerHostName(durableClientVM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));
 
     // Send clientReady message
     this.durableClientVM.invoke(new CacheSerializableRunnable("Send clientReady") {
@@ -739,8 +736,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
     // Re-start durable client 2
     durableClient2VM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClient2VM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId2), Boolean.TRUE));
+        getClientPool(getServerHostName(durableClient2VM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId2), Boolean.TRUE));
 
     // Send clientReady message
     durableClient2VM.invoke(new CacheSerializableRunnable("Send clientReady") {
@@ -798,8 +795,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     final int durableClientTimeout = 60; // keep the client alive for 60 seconds
     // final boolean durableClientKeepAlive = true; // keep the client alive when it stops normally
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), server1Port,
-            server2Port, true),
+        getClientPool(getServerHostName(durableClientVM.getHost()), server1Port, server2Port, true),
         regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
         Boolean.TRUE));
 
@@ -863,10 +859,9 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
         new Integer(server2Port)));
 
     // Start normal publisher client
-    this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(publisherClientVM.getHost()), server1Port,
-            server2Port, false),
-        regionName));
+    this.publisherClientVM.invoke(() -> CacheServerTestUtil
+        .createCacheClient(getClientPool(getServerHostName(publisherClientVM.getHost()),
+            server1Port, server2Port, false), regionName));
 
     // Publish some entries
     final int numberOfEntries = 10;
@@ -894,8 +889,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     // Re-start the durable client that is kept alive on the server when it stops
     // normally
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), server1Port,
-            server2Port, true),
+        getClientPool(getServerHostName(durableClientVM.getHost()), server1Port, server2Port, true),
         regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
         Boolean.TRUE));
 
@@ -978,8 +972,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     final String durableClientId = getName() + "_client";
     // make the client use ClientCacheFactory so it will have a default pool
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createClientCache(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), serverPort, true),
-        regionName, getClientDistributedSystemProperties(durableClientId)));
+        getClientPool(getServerHostName(durableClientVM.getHost()), serverPort, true), regionName,
+        getClientDistributedSystemProperties(durableClientId)));
 
     // verify that readyForEvents has not yet been called on the client's default pool
     this.durableClientVM.invoke(new CacheSerializableRunnable("check readyForEvents not called") {
@@ -1069,39 +1063,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
           CacheServerTestUtil.getCache().readyForEvents();
         }
       });
-
-      // Durable client registers durable cq on server
-      this.durableClientVM.invoke(new CacheSerializableRunnable("Register Cq") {
-        @Override
-        public void run2() throws CacheException {
-          // Get the region
-          Region region = CacheServerTestUtil.getCache().getRegion(regionName);
-          assertNotNull(region);
-
-          // Create CQ Attributes.
-          CqAttributesFactory cqAf = new CqAttributesFactory();
-
-          // Initialize and set CqListener.
-          CqListener[] cqListeners = {new CacheServerTestUtil.ControlCqListener()};
-          cqAf.initCqListeners(cqListeners);
-          CqAttributes cqa = cqAf.create();
-
-          // Create cq's
-          // Get the query service for the Pool
-          QueryService queryService = CacheServerTestUtil.getPool().getQueryService();
-
-          try {
-            CqQuery query = queryService.newCq(cqName, "Select * from /" + regionName, cqa, true);
-            query.execute();
-          } catch (CqExistsException e) {
-            fail("Failed due to ", e);
-          } catch (CqException e) {
-            fail("Failed due to ", e);
-          } catch (RegionNotFoundException e) {
-            fail("Could not find specified region:" + regionName + ":", e);
-          }
-        }
-      });
+      registerDurableCq(cqName);
 
       // Verify durable client on server1
       this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
@@ -1120,8 +1082,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
       // Start normal publisher client
       this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-          getClientPool(NetworkUtils.getServerHostName(publisherClientVM.getHost()), serverPort,
-              false),
+          getClientPool(getServerHostName(publisherClientVM.getHost()), serverPort, false),
           regionName));
 
       // Publish some entries
@@ -1262,6 +1223,41 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     }
   }
 
+  protected void registerDurableCq(final String cqName) {
+    // Durable client registers durable cq on server
+    this.durableClientVM.invoke(new CacheSerializableRunnable("Register Cq") {
+      @Override
+      public void run2() throws CacheException {
+        // Get the region
+        Region region = CacheServerTestUtil.getCache().getRegion(regionName);
+        assertNotNull(region);
+
+        // Create CQ Attributes.
+        CqAttributesFactory cqAf = new CqAttributesFactory();
+
+        // Initialize and set CqListener.
+        CqListener[] cqListeners = {new CacheServerTestUtil.ControlCqListener()};
+        cqAf.initCqListeners(cqListeners);
+        CqAttributes cqa = cqAf.create();
+
+        // Create cq's
+        // Get the query service for the Pool
+        QueryService queryService = CacheServerTestUtil.getPool().getQueryService();
+
+        try {
+          CqQuery query = queryService.newCq(cqName, "Select * from /" + regionName, cqa, true);
+          query.execute();
+        } catch (CqExistsException e) {
+          fail("Failed due to ", e);
+        } catch (CqException e) {
+          fail("Failed due to ", e);
+        } catch (RegionNotFoundException e) {
+          fail("Could not find specified region:" + regionName + ":", e);
+        }
+      }
+    });
+  }
+
   private void setPeriodicACKObserver(VM vm) {
     CacheSerializableRunnable cacheSerializableRunnable =
         new CacheSerializableRunnable("Set ClientServerObserver") {
@@ -1359,8 +1355,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
     // Start normal publisher client
     this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(publisherClientVM.getHost()), serverPort,
-            false),
+        getClientPool(getServerHostName(publisherClientVM.getHost()), serverPort, false),
         regionName));
 
     // Publish some entries
@@ -3282,8 +3277,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     // final boolean durableClientKeepAlive = true; // keep the client alive when it stops normally
     final String durableClientId = getName() + "_client";
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), server1Port,
-            server2Port, true),
+        getClientPool(getServerHostName(durableClientVM.getHost()), server1Port, server2Port, true),
         regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
         Boolean.TRUE));
 
@@ -3355,8 +3349,7 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     // Start up the client again. This time initialize it so that it is not kept
     // alive on the servers when it stops normally.
     this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(durableClientVM.getHost()), server1Port,
-            server2Port, true),
+        getClientPool(getServerHostName(durableClientVM.getHost()), server1Port, server2Port, true),
         regionName, getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));
 
     // Send clientReady message
@@ -3424,10 +3417,9 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
         .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, new Boolean(true)));
 
     // Start normal publisher client
-    this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
-        getClientPool(NetworkUtils.getServerHostName(this.publisherClientVM.getHost()), server1Port,
-            server2Port, false),
-        this.regionName));
+    this.publisherClientVM.invoke(() -> CacheServerTestUtil
+        .createCacheClient(getClientPool(getServerHostName(this.publisherClientVM.getHost()),
+            server1Port, server2Port, false), this.regionName));
 
     // Create an entry
     publishEntries(1);
@@ -3436,8 +3428,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     final String durableClientId = getName() + "_client";
     final int durableClientTimeout = 60; // keep the client alive for 60 seconds
     restartDurableClient(new Object[] {
-        getClientPool(NetworkUtils.getServerHostName(this.durableClientVM.getHost()), server1Port,
-            server2Port, true),
+        getClientPool(getServerHostName(this.durableClientVM.getHost()), server1Port, server2Port,
+            true),
         regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
         true});
 
@@ -3469,8 +3461,8 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
 
     // Restart durable client
     restartDurableClient(new Object[] {
-        getClientPool(NetworkUtils.getServerHostName(this.durableClientVM.getHost()), server1Port,
-            server2Port, true),
+        getClientPool(getServerHostName(this.durableClientVM.getHost()), server1Port, server2Port,
+            true),
         regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
         true});
 
@@ -3499,6 +3491,74 @@ public class DurableClientSimpleDUnitTest extends DurableClientTestCase {
     return registered;
   }
 
+  @Test
+  public void testGetAllDurableCqsFromServer() {
+    // Start server 1
+    final int server1Port = ((Integer) this.server1VM.invoke(CacheServerTestUtil.class,
+        "createCacheServer", new Object[] {regionName, new Boolean(true)})).intValue();
+
+    // Start server 2
+    final int server2Port = ((Integer) this.server2VM.invoke(CacheServerTestUtil.class,
+        "createCacheServer", new Object[] {regionName, new Boolean(true)})).intValue();
+
+    // Start a durable client
+    final String durableClientId = getName() + "_client";
+    this.durableClientVM.invoke(CacheServerTestUtil.class, "createCacheClient",
+        new Object[] {
+            getClientPool(getServerHostName(durableClientVM.getHost()), server1Port, server2Port,
+                true, 0),
+            regionName, getClientDistributedSystemProperties(durableClientId, 60), Boolean.TRUE});
+
+    // Send clientReady message
+    this.durableClientVM.invoke(new CacheSerializableRunnable("Send clientReady") {
+      public void run2() throws CacheException {
+        CacheServerTestUtil.getCache().readyForEvents();
+      }
+    });
+
+    // Register durable CQ
+    String cqName = getName() + "_cq";
+    registerDurableCq(cqName);
+
+    // Execute getAllDurableCqsFromServer on the client
+    List<String> durableCqNames =
+        (List<String>) this.durableClientVM.invoke(() -> getAllDurableCqsFromServer());
+
+    this.durableClientVM.invoke(() -> verifyDurableCqs(durableCqNames, cqName));
+
+    // Stop the durable client
+    this.durableClientVM.invoke(() -> CacheServerTestUtil.closeCache());
+
+    // Stop the servers
+    this.server1VM.invoke(() -> CacheServerTestUtil.closeCache());
+    this.server2VM.invoke(() -> CacheServerTestUtil.closeCache());
+  }
+
+  public static List<String> getAllDurableCqsFromServer() throws CqException {
+    QueryService queryService = CacheServerTestUtil.getPool().getQueryService();
+    return queryService.getAllDurableCqsFromServer();
+  }
+
+  public static void verifyDurableCqs(final List<String> durableCqNames,
+      final String registeredCqName) {
+    // Verify the number of durable CQ names is one, and it matches the registered name
+    assertEquals(1, durableCqNames.size());
+    String returnedCqName = durableCqNames.get(0);
+    assertEquals(registeredCqName, returnedCqName);
+
+    // Get client's primary server
+    PoolImpl pool = CacheServerTestUtil.getPool();
+    ServerLocation primaryServerLocation = pool.getPrimary();
+
+    // Verify the primary server was used and no other server was used
+    Map<ServerLocation, ConnectionStats> statistics = pool.getEndpointManager().getAllStats();
+    for (Map.Entry<ServerLocation, ConnectionStats> entry : statistics.entrySet()) {
+      int expectedGetDurableCqInvocations = entry.getKey().equals(primaryServerLocation) ? 1 : 0;
+      assertEquals(expectedGetDurableCqInvocations, entry.getValue().getGetDurableCqs());
+    }
+  }
+
+
   private void waitForEventsRemovedByQueueRemovalMessage(VM secondaryServerVM,
       final String durableClientId, final int numEvents) {
     secondaryServerVM.invoke(() -> DurableClientSimpleDUnitTest


[14/50] [abbrv] geode git commit: GEODE-1835 : unit test to verify a warning message by the configure pdx command only when there are members in the distributed system.

Posted by kl...@apache.org.
GEODE-1835 : unit test to verify a warning message by the configure pdx
command only when there are members in the distributed system.

This closes #304


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

Branch: refs/heads/feature/GEODE-1930
Commit: ef7418140b903e73bc3a38d3a86c01349924bd09
Parents: 28efd90
Author: Amey Barve <ab...@apache.org>
Authored: Mon Dec 5 18:24:18 2016 +0530
Committer: Kirk Lund <kl...@apache.org>
Committed: Thu Dec 8 08:46:38 2016 -0800

----------------------------------------------------------------------
 .../ClusterConfigurationDUnitTest.java             | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/ef741814/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
index 3f7b073..2677900 100644
--- a/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
+++ b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
@@ -614,6 +614,15 @@ public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
     });
   }
 
+  @Test
+  public void testConfigurePDXForWarning() throws Exception {
+    setup();
+    CommandResult commandResult = configurePDX("com.foo.*", "true", "true", null, "true");
+    String result = (String) commandResult.getResultData().getGfJsonObject()
+        .getJSONObject("content").getJSONArray("message").get(0);
+    assertEquals(CliStrings.CONFIGURE_PDX__NORMAL__MEMBERS__WARNING, result);
+  }
+
   private Object[] setup() throws IOException {
     final int[] ports = getRandomAvailableTCPPorts(3);
     final int locator1Port = ports[0];
@@ -800,13 +809,14 @@ public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
     executeAndVerifyCommand(csb.getCommandString());
   }
 
-  private void executeAndVerifyCommand(String commandString) {
+  private CommandResult executeAndVerifyCommand(String commandString) {
     CommandResult cmdResult = executeCommand(commandString);
     org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Command : " + commandString);
     org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
         .info("Command Result : " + commandResultToString(cmdResult));
     assertEquals(Status.OK, cmdResult.getStatus());
     assertFalse(cmdResult.failedToPersist());
+    return cmdResult;
   }
 
   private void createIndex(String indexName, String expression, String regionName, String group) {
@@ -939,7 +949,7 @@ public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
     }
   }
 
-  private void configurePDX(String autoSerializerClasses, String ignoreUnreadFields,
+  private CommandResult configurePDX(String autoSerializerClasses, String ignoreUnreadFields,
       String persistent, String portableAutoSerializerClasses, String readSerialized) {
     CommandStringBuilder csb = new CommandStringBuilder(CliStrings.CONFIGURE_PDX);
     csb.addOptionWithValueCheck(CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES,
@@ -950,7 +960,8 @@ public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
     csb.addOptionWithValueCheck(CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES,
         portableAutoSerializerClasses);
     csb.addOptionWithValueCheck(CliStrings.CONFIGURE_PDX__READ__SERIALIZED, readSerialized);
-    executeAndVerifyCommand(csb.getCommandString());
+
+    return executeAndVerifyCommand(csb.getCommandString());
   }
 
   private void createAndDeployJar(String jarName, String group) throws IOException {


[18/50] [abbrv] geode git commit: Merge branch 'bugfix/GEODE-1984' into develop

Posted by kl...@apache.org.
Merge branch 'bugfix/GEODE-1984' into develop


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

Branch: refs/heads/feature/GEODE-1930
Commit: 213d8bc1c3ad85365d7860e3a5d8ea334691cdd4
Parents: 1d951e3 f522f6c
Author: adongre <ad...@apache.org>
Authored: Fri Dec 9 05:08:36 2016 +0530
Committer: adongre <ad...@apache.org>
Committed: Fri Dec 9 05:08:36 2016 +0530

----------------------------------------------------------------------
 .../internal/AsyncEventQueueImpl.java           |   2 +-
 .../apache/geode/cache/wan/GatewaySender.java   |  13 +
 .../cache/wan/AbstractGatewaySender.java        |   1 +
 .../internal/cli/commands/WanCommands.java      |  59 +-
 .../functions/GatewaySenderDestroyFunction.java |  90 +++
 .../GatewaySenderDestroyFunctionArgs.java       |  33 +
 .../internal/cli/i18n/CliStrings.java           |  18 +
 .../controllers/ShellCommandsController.java    |   2 +
 .../web/controllers/WanCommandsController.java  |  24 +
 .../codeAnalysis/sanctionedSerializables.txt    |   2 +
 .../cli/commands/golden-help-offline.properties |  21 +
 .../cli/commands/golden-help-online.properties  |   6 +
 .../geode/internal/cache/wan/WANTestBase.java   |   2 +-
 .../wan/wancommand/WANCommandTestBase.java      |  33 +
 ...mandCreateDestroyGatewaySenderDUnitTest.java | 794 +++++++++++++++++++
 .../WanCommandCreateGatewaySenderDUnitTest.java | 663 ----------------
 16 files changed, 1092 insertions(+), 671 deletions(-)
----------------------------------------------------------------------



[43/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 d2e797e..63cf88f 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
@@ -14,98 +14,70 @@
  */
 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 {
+@SuppressWarnings("serial")
+public class DistributedSystemStatsDUnitTest {
 
-  private static final long serialVersionUID = 1L;
+  @Manager
+  private VM manager;
 
-  public DistributedSystemStatsDUnitTest() {
-    super();
-  }
+  @Member
+  private VM[] members;
+
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
   @Test
   public void testDistributedSystemStats() throws Exception {
-    initManagement(true);
-
-    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);
-      }
-    });
-  }
-
-  @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);
-          }
-        }
-
+    this.manager.invoke("verifyMBeans", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      assertNotNull(cache);
+
+      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)));
+
+        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/geode/blob/914cbfdc/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 f4ca239..dcfd2bf 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
@@ -24,7 +24,6 @@ import org.junit.experimental.categories.Category;
 
 import org.apache.geode.test.junit.categories.UnitTest;
 
-
 @Category(UnitTest.class)
 public class QueryDataFunctionApplyLimitClauseTest {
 

http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 9416616..a7940a4 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
@@ -14,11 +14,22 @@
  */
 package org.apache.geode.management.internal.pulse;
 
+import static java.util.concurrent.TimeUnit.MINUTES;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.Assert.*;
 
+import java.io.IOException;
+import java.io.Serializable;
 import java.util.Properties;
 
+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;
 
@@ -29,273 +40,141 @@ import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionAttributes;
 import org.apache.geode.cache.Scope;
+import org.apache.geode.cache.client.ClientCache;
+import org.apache.geode.cache.client.ClientRegionFactory;
+import org.apache.geode.cache.client.ClientRegionShortcut;
 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.CacheServerMXBean;
-import org.apache.geode.management.MBeanUtil;
-import org.apache.geode.management.ManagementTestBase;
-import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.ManagementTestRule;
+import org.apache.geode.management.Manager;
+import org.apache.geode.management.internal.SystemManagementService;
 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 client IDs
  */
 @Category(DistributedTest.class)
-public class TestClientIdsDUnitTest 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 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();
+@SuppressWarnings({"serial", "unused"})
+public class TestClientIdsDUnitTest implements Serializable {
+
+  private static final String KEY1 = "KEY1";
+  private static final String KEY2 = "KEY2";
+  private static final String VALUE1 = "client-KEY1";
+  private static final String VALUE2 = "client-KEY2";
+  private static final String REGION_NAME =
+      TestClientIdsDUnitTest.class.getSimpleName() + "_Region";
+
+  @Manager
+  private VM managerVM;
+
+  private VM serverVM;
+  private VM client1VM;
+  private VM client2VM;
+
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().start(false).build();
+
+  @Before
+  public void before() throws Exception {
+    serverVM = Host.getHost(0).getVM(1);
+    client1VM = Host.getHost(0).getVM(2);
+    client2VM = Host.getHost(0).getVM(3);
   }
 
   @Test
   public void testClientIds() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
-    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);
-    verifyClientIds(managingNode, serverMember, port);
-    helper.stopManagingNode(managingNode);
-  }
+    this.managementTestRule.createManagers();
 
-  @SuppressWarnings("serial")
-  private Object createServerCache(VM vm) {
-    return vm.invoke(new SerializableCallable("Create Server Cache") {
-      public Object call() {
-        try {
-          return createServerCache();
-        } catch (Exception e) {
-          fail("Error while createServerCache " + e);
-        }
-        return null;
-      }
-    });
-  }
+    int port = this.serverVM.invoke(() -> createServerCache());
+
+    this.client1VM
+        .invoke(() -> createClientCache(getServerHostName(this.serverVM.getHost()), port));
+    this.client2VM
+        .invoke(() -> createClientCache(getServerHostName(this.serverVM.getHost()), port));
 
-  @SuppressWarnings("serial")
-  private void createClientCache(VM vm, final String host, final Integer port1) {
-    vm.invoke(new SerializableCallable("Create Client Cache") {
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    DistributedMember client1Member = this.managementTestRule.getDistributedMember(this.client1VM);
+    DistributedMember client2Member = this.managementTestRule.getDistributedMember(this.client2VM);
 
-      public Object call() {
+    // this.managerVM.invoke(() -> verifyClientIds(serverMember, port));
+    this.managerVM.invoke(() -> {
+      CacheServerMXBean cacheServerMXBean = awaitCacheServerMXBean(serverMember, port);
+      await().until(() -> {
         try {
-          createClientCache(host, port1);
+          assertThat(cacheServerMXBean.getClientIds()).hasSize(2);
         } catch (Exception e) {
-          fail("Error while createClientCache " + e);
+          throw new Error(e);
         }
-        return null;
-      }
+      });
+      assertThat(cacheServerMXBean.getClientIds()).hasSize(2); // TODO
     });
   }
 
-  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);
-    return cache;
-  }
+  private int createServerCache() throws IOException {
+    Cache cache = this.managementTestRule.getCache();
 
-  private Integer createServerCache(DataPolicy dataPolicy) throws Exception {
-    Cache cache = helper.createCache(false);
     AttributesFactory factory = new AttributesFactory();
     factory.setScope(Scope.DISTRIBUTED_ACK);
-    factory.setDataPolicy(dataPolicy);
+    factory.setDataPolicy(DataPolicy.REPLICATE);
+
     RegionAttributes attrs = factory.create();
     cache.createRegion(REGION_NAME, attrs);
-    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-    CacheServer server1 = cache.addCacheServer();
-    server1.setPort(port);
-    server1.setNotifyBySubscription(true);
-    server1.start();
-    return new Integer(server1.getPort());
-  }
 
-  public Integer createServerCache() throws Exception {
-    return createServerCache(DataPolicy.REPLICATE);
+    CacheServer cacheServer = cache.addCacheServer();
+    cacheServer.setPort(0);
+    cacheServer.setNotifyBySubscription(true);
+    cacheServer.start();
+    return cacheServer.getPort();
   }
 
-  public Cache createClientCache(String host, Integer port1) throws Exception {
+  private void createClientCache(final String host, final int serverPort) {
+    ClientCache cache = this.managementTestRule.getClientCache();
 
-    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())
+    PoolImpl pool = (PoolImpl) PoolManager.createFactory().addServer(host, serverPort)
         .setSubscriptionEnabled(false).setThreadLocalConnections(true).setMinConnections(1)
         .setReadTimeout(20000).setPingInterval(10000).setRetryAttempts(1)
-        .setSubscriptionEnabled(true).setStatisticInterval(1000)
-        .create("CacheServerManagementDUnitTest");
-
-    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;
+        .setSubscriptionEnabled(true).setStatisticInterval(1000).create(getClass().getSimpleName());
 
+    ClientRegionFactory factory =
+        cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
+    factory.setPoolName(pool.getName());
+    factory.create(REGION_NAME);
   }
 
-  /**
-   * get member id
-   */
-  @SuppressWarnings("serial")
-  protected static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
+  private void verifyClientIds(final DistributedMember serverMember, final int serverPort)
+      throws Exception {
+    CacheServerMXBean cacheServerMXBean = awaitCacheServerMXBean(serverMember, serverPort);
+    await().until(() -> {
+      try {
+        assertThat(cacheServerMXBean.getClientIds()).hasSize(2);
+      } catch (Exception e) {
+        throw new Error(e);
+      }
+    });
+    assertThat(cacheServerMXBean.getClientIds()).hasSize(2); // TODO
   }
 
-  /**
-   * Verify the Cache Server details
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void verifyClientIds(final VM vm, final DistributedMember serverMember,
-      final int serverPort) {
-    SerializableRunnable verifyCacheServerRemote =
-        new SerializableRunnable("Verify Cache Server Remote") {
-          public void run() {
-            try {
-              final WaitCriterion waitCriteria = new WaitCriterion() {
-                @Override
-                public boolean done() {
-                  CacheServerMXBean bean = null;
-                  try {
-                    bean = MBeanUtil.getCacheServerMbeanProxy(serverMember, serverPort);
-                    if (bean != null) {
-                      if (bean.getClientIds().length > 0) {
-                        return true;
-                      }
-                    }
-                  } catch (Exception e) {
-                    LogWriterUtils.getLogWriter().info("exception occured " + e.getMessage()
-                        + CliUtil.stackTraceAsString((Throwable) e));
-                  }
-                  return false;
-                }
+  private CacheServerMXBean awaitCacheServerMXBean(final DistributedMember serverMember,
+      final int port) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getCacheServerMBeanName(port, serverMember);
 
-                @Override
-                public String description() {
-                  return "wait for getNumOfClients bean to complete and get results";
-                }
-              };
-              Wait.waitForCriterion(waitCriteria, 2 * 60 * 1000, 3000, true);
+    await().until(
+        () -> assertThat(service.getMBeanProxy(objectName, CacheServerMXBean.class)).isNotNull());
 
-              // Now it is sure that bean would be available
-              CacheServerMXBean bean = MBeanUtil.getCacheServerMbeanProxy(serverMember, serverPort);
-              LogWriterUtils.getLogWriter().info("verifyClientIds = " + bean.getClientIds().length);
-              assertEquals(true, bean.getClientIds().length > 0 ? true : false);
-            } catch (Exception e) {
-              fail("Error while verifying cache server from remote member " + e);
-            }
-          }
-        };
-    vm.invoke(verifyCacheServerRemote);
+    return service.getMBeanProxy(objectName, CacheServerMXBean.class);
   }
 
-  /**
-   * Verify the Cache Server details
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void put(final VM vm) {
-    SerializableRunnable put = new SerializableRunnable("put") {
-      public void run() {
-        try {
-          Cache cache = GemFireCacheImpl.getInstance();
-          Region<Object, Object> 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);
-          try {
-            Thread.sleep(10000);
-          } catch (Exception e) {
-            // sleep
-          }
-          r1.clear();
-        } catch (Exception ex) {
-          Assert.fail("failed while put", ex);
-        }
-      }
-
-    };
-    vm.invoke(put);
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
   }
-
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 7d96517..52c7b9c 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
@@ -15,6 +15,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;
@@ -32,268 +35,173 @@ 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);
+
+    int port = createServerCache(server);
+    getMember(server);
 
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
+    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);
-  }
 
-  @SuppressWarnings("serial")
-  private Object createServerCache(VM vm) {
-    return vm.invoke(new SerializableCallable("Create Server Cache in TestSubscriptionsDUnitTest") {
+    verifyNumSubscriptions(managingNode);
 
-      public Object call() {
-        try {
-          return createServerCache();
-        } catch (Exception e) {
-          fail("Error while createServerCache in TestSubscriptionsDUnitTest" + e);
-        }
-        return null;
-      }
-    });
+    stopManagingNode(managingNode);
   }
 
-  @SuppressWarnings("serial")
-  private void createClientCache(VM vm, final String host, final Integer port1) {
-    vm.invoke(new SerializableCallable("Create Client Cache in TestSubscriptionsDUnitTest") {
+  private int createServerCache(VM vm) {
+    return vm.invoke("Create Server Cache in TestSubscriptionsDUnitTest", () -> {
+      return createServerCache();
+    });
+  }
 
-      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");
+
+    PoolImpl p =
+        (PoolImpl) PoolManager.createFactory().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();
+
+      waitForCriterion(new WaitCriterion() {
+        @Override
+        public boolean done() {
+          ManagementService service = ManagementService.getExistingManagementService(cache);
+          DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+          return distributedSystemMXBean != null
+              & distributedSystemMXBean.getNumSubscriptions() > 1;
+        }
 
-  /**
-   * 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());
-            }
-
-          }
-        };
-    vm.invoke(verifyCacheServerRemote);
-  }
+        @Override
+        public String description() {
+          return "TestSubscriptionsDUnitTest wait for getDistributedSystemMXBean to complete and get results";
+        }
+      }, 2 * 60 * 1000, 3000, true);
 
-  /**
-   * 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);
-            }
-          }
-
-        };
-    vm.invoke(put);
+      DistributedSystemMXBean distributedSystemMXBean =
+          ManagementService.getExistingManagementService(cache).getDistributedSystemMXBean();
+      assertNotNull(distributedSystemMXBean);
+      assertEquals(2, distributedSystemMXBean.getNumSubscriptions());
+    });
   }
 
-  @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 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);
+    });
   }
 
+  private void put(final VM vm) {
+    vm.invoke("put", () -> {
+      Cache cache = GemFireCacheImpl.getInstance();
+      Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+      assertNotNull(region);
+
+      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/geode/blob/914cbfdc/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 460b562..057454d 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
@@ -316,6 +316,58 @@ 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}.
    *
@@ -353,10 +405,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/geode/blob/914cbfdc/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 a09f5ff..af7e217 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
@@ -22,13 +22,13 @@ import java.util.Map;
  * 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>, however, they are
- * intended to be referenced through static import:
+ * 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/geode/blob/914cbfdc/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 04d2951..9a42caa 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
@@ -24,6 +24,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;
@@ -91,7 +92,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/geode/blob/914cbfdc/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 f25810e..7d4e6d5 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
@@ -17,6 +17,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/geode/blob/914cbfdc/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 037d73c..a511995 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
@@ -245,6 +245,11 @@ public abstract class JUnit4CacheTestCase extends JUnit4DistributedTestCase
     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/geode/blob/914cbfdc/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 ebbb2fd..a7640f2 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
@@ -111,7 +111,7 @@ public abstract class JUnit4DistributedTestCase implements DistributedTestFixtur
   }
 
   @Rule
-  public SerializableTestName testName = new SerializableTestName();
+  public SerializableTestName testNameForDistributedTestCase = new SerializableTestName();
 
   @BeforeClass
   public static final void initializeDistributedTestCase() {
@@ -122,7 +122,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/geode/blob/914cbfdc/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 ddf37c5..9107d4d 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
@@ -43,14 +43,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/geode/blob/914cbfdc/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 221b52a..1f2134a 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
@@ -46,7 +46,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();
@@ -58,7 +58,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/geode/blob/914cbfdc/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..8e89bdb
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java
@@ -0,0 +1,66 @@
+/*
+ * 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/geode/blob/914cbfdc/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..7a86613
--- /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/geode/blob/914cbfdc/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..cdc8dda
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java
@@ -0,0 +1,75 @@
+/*
+ * 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/geode/blob/914cbfdc/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..31fba3d
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
@@ -0,0 +1,200 @@
+/*
+ * 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/geode/blob/914cbfdc/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..8c85775
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
@@ -0,0 +1,50 @@
+/*
+ * 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/geode/blob/914cbfdc/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..6b1f8f1
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.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.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/geode/blob/914cbfdc/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 6398e45..866a0d5 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
@@ -18,7 +18,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 will invoke a
@@ -28,18 +29,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/geode/blob/914cbfdc/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..1048f2e
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java
@@ -0,0 +1,59 @@
+/*
+ * 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/geode/blob/914cbfdc/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..7dded64
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.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.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/geode/blob/914cbfdc/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 5a80a64..11f572b 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
@@ -14,41 +14,51 @@
  */
 package org.apache.geode.test.dunit.standalone;
 
-import batterytest.greplogs.ExpectedStrings;
-import batterytest.greplogs.LogConsumer;
-import org.apache.geode.distributed.Locator;
-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.logging.LogService;
-import org.apache.geode.test.dunit.DUnitEnv;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.VM;
-import hydra.MethExecutorResult;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.core.appender.FileAppender;
-import org.apache.logging.log4j.core.config.LoggerConfig;
-import org.apache.logging.log4j.core.layout.PatternLayout;
-import org.junit.Assert;
+import static org.apache.geode.distributed.ConfigurationProperties.*;
 
-import java.io.*;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
 import java.lang.reflect.Method;
 import java.net.InetAddress;
 import java.net.URISyntaxException;
 import java.nio.channels.FileChannel;
 import java.nio.charset.Charset;
-import java.rmi.*;
+import java.rmi.AccessException;
+import java.rmi.AlreadyBoundException;
+import java.rmi.NotBoundException;
+import java.rmi.Remote;
+import java.rmi.RemoteException;
 import java.rmi.registry.LocateRegistry;
 import java.rmi.registry.Registry;
 import java.rmi.server.UnicastRemoteObject;
 import java.util.List;
 import java.util.Properties;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
+import batterytest.greplogs.ExpectedStrings;
+import batterytest.greplogs.LogConsumer;
+import hydra.MethExecutorResult;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.FileAppender;
+import org.apache.logging.log4j.core.config.LoggerConfig;
+import org.apache.logging.log4j.core.layout.PatternLayout;
+import org.junit.Assert;
+
+import org.apache.geode.distributed.Locator;
+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.logging.LogService;
+import org.apache.geode.test.dunit.DUnitEnv;
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.SerializableCallable;
+import org.apache.geode.test.dunit.VM;
 
 /**
  * A class to build a fake test configuration and launch some DUnit VMS.
@@ -73,6 +83,9 @@ public class DUnitLauncher {
   private static final int LOCATOR_VM_NUM = -2;
 
   static final long STARTUP_TIMEOUT = 120 * 1000;
+  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;
 
@@ -191,7 +204,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);
@@ -206,7 +219,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/geode/blob/914cbfdc/geode-junit/build.gradle
----------------------------------------------------------------------
diff --git a/geode-junit/build.gradle b/geode-junit/build.gradle
index f7e5e46..e47095f 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'
   testCompile 'com.google.guava:guava:' + project.'guava.version'
   testCompile 'org.assertj:assertj-core:' + project.'assertj-core.version'

http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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..c7c326a
--- /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/geode/blob/914cbfdc/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 c76ed19..be561df 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
@@ -14,11 +14,33 @@
  */
 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();
+        }
+      }
+    };
+  }
 }


[07/50] [abbrv] geode git commit: GEODE-2004: [doc update] Create/update/delete query through rest api should require DATA:READ instead of DATA:WRITE

Posted by kl...@apache.org.
GEODE-2004: [doc update] Create/update/delete query through rest api should require DATA:READ instead of DATA:WRITE


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

Branch: refs/heads/feature/GEODE-1930
Commit: 860d7efabc72b3d67406315f5f6baaadc3ff9fd4
Parents: f58a11d
Author: Dave Barnes <db...@pivotal.io>
Authored: Wed Dec 7 12:29:14 2016 -0800
Committer: Dave Barnes <db...@pivotal.io>
Committed: Wed Dec 7 12:29:14 2016 -0800

----------------------------------------------------------------------
 .../managing/security/implementing_authorization.html.md.erb     | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/860d7efa/geode-docs/managing/security/implementing_authorization.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/managing/security/implementing_authorization.html.md.erb b/geode-docs/managing/security/implementing_authorization.html.md.erb
index cd7f829..a01feda 100644
--- a/geode-docs/managing/security/implementing_authorization.html.md.erb
+++ b/geode-docs/managing/security/implementing_authorization.html.md.erb
@@ -141,7 +141,7 @@ This table classifies the permissions assigned for `gfsh` operations.
 | export offline-disk-store              | CLUSTER:READ                     |
 | export stack-traces                    | CLUSTER:READ                     |
 | gc                                     | CLUSTER:MANAGE                   |
-| get --key=key1 --region=region1        | DATA:READ:RegionName:Key         |
+| get &#8209;key=key1 &#8209;region=region1        | DATA:READ:RegionName:Key         |
 | import data                            | DATA:WRITE:RegionName            |
 | import cluster-configuration           | DATA:MANAGE                      |
 | list async-event-queues                | CLUSTER:READ                     |
@@ -160,7 +160,7 @@ This table classifies the permissions assigned for `gfsh` operations.
 | pause gateway-sender                   | DATA:MANAGE                      |
 | pdx rename                             | DATA:MANAGE                      |
 | put --key=key1 --region=region1        | DATA:WRITE:RegionName:Key        |
-| query                                  | DATA:READ:RegionName             |
+| query                                  | DATA:READ                        |
 | rebalance                              | DATA:MANAGE                      |
 | remove                                 | DATA:WRITE:RegionName or DATA:WRITE:RegionName:Key |
 | resume gateway-sender                  | DATA:MANAGE                      |


[34/50] [abbrv] geode git commit: GEODE-1334: add FlakyTest category to flaky test

Posted by kl...@apache.org.
GEODE-1334: add FlakyTest category to flaky test


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

Branch: refs/heads/feature/GEODE-1930
Commit: 92ef7329ed7247d6283b2ab3c373522269b76bbf
Parents: 1f49cbc
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Dec 12 17:30:51 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 17:30:51 2016 -0800

----------------------------------------------------------------------
 .../internal/configuration/ClusterConfigurationDUnitTest.java       | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/92ef7329/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
index 2677900..0d48f5b 100644
--- a/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
+++ b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
@@ -267,6 +267,7 @@ public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
    * 
    * @since GemFire 8.1
    */
+  @Category(FlakyTest.class) // GEODE-1334
   @Test
   public void testCreateExtensions() throws Exception {
     Object[] result = setup();


[42/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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..9251e83
--- /dev/null
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java
@@ -0,0 +1,25 @@
+/*
+ * 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/geode/blob/914cbfdc/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 634ea2f..478fe67 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
@@ -143,13 +143,13 @@ 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);
   }
@@ -178,14 +178,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,
+  private void verifyAllMBeanIndexMetrics(String regionName, int numRegionIndexes,
       int numTotalIndexes) {
     LuceneServiceMXBean mbean = getMBean();
     verifyMBeanIndexMetrics(mbean, regionName, numRegionIndexes, numTotalIndexes);
@@ -210,18 +210,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/geode/blob/914cbfdc/gradle/dependency-versions.properties
----------------------------------------------------------------------
diff --git a/gradle/dependency-versions.properties b/gradle/dependency-versions.properties
index 828b088..05d7124 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


[05/50] [abbrv] geode git commit: GEODE-2185: Index not used with parameterized query

Posted by kl...@apache.org.
GEODE-2185: Index not used with parameterized query


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

Branch: refs/heads/feature/GEODE-1930
Commit: 7fb0e68b130317ac3cce0fa1ca8f39fb0006720f
Parents: c2b1c8b
Author: Jason Huynh <hu...@gmail.com>
Authored: Tue Dec 6 10:21:01 2016 -0800
Committer: Jason Huynh <hu...@gmail.com>
Committed: Wed Dec 7 09:52:15 2016 -0800

----------------------------------------------------------------------
 .../query/internal/CompiledBindArgument.java    | 18 ++++--
 .../internal/IndexTrackingQueryObserver.java    | 33 ++++++-----
 .../geode/cache/query/data/Instrument.java      | 60 ++++++++++++++++++++
 .../geode/cache/query/data/TradingLine.java     | 41 +++++++++++++
 .../MapRangeIndexMaintenanceJUnitTest.java      | 49 ++++++++++++++++
 5 files changed, 182 insertions(+), 19 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/7fb0e68b/geode-core/src/main/java/org/apache/geode/cache/query/internal/CompiledBindArgument.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/cache/query/internal/CompiledBindArgument.java b/geode-core/src/main/java/org/apache/geode/cache/query/internal/CompiledBindArgument.java
index cb9218b..106d389 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/query/internal/CompiledBindArgument.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/query/internal/CompiledBindArgument.java
@@ -46,13 +46,19 @@ public class CompiledBindArgument extends AbstractCompiledValue {
   public void generateCanonicalizedExpression(StringBuffer clauseBuffer, ExecutionContext context)
       throws AmbiguousNameException, TypeMismatchException, NameResolutionException {
 
-    Object bindArg;
-    if (context.isBindArgsSet()
-        && (bindArg = context.getBindArgument(this.index)) instanceof Region) {
-      clauseBuffer.insert(0, ((Region) bindArg).getFullPath());
-    } else {
-      clauseBuffer.insert(0, "$" + this.index);
+    // When compiling a new query, a context is created where there are no bind arguments at this
+    // point
+    if (context.isBindArgsSet()) {
+      Object bindArgumentValue = context.getBindArgument(this.index);
+      if (bindArgumentValue instanceof Region) {
+        clauseBuffer.insert(0, ((Region) bindArgumentValue).getFullPath());
+      } else if (bindArgumentValue instanceof String) {
+        clauseBuffer.insert(0, '\'').insert(0, bindArgumentValue).insert(0, '\'');
+      } else {
+        super.generateCanonicalizedExpression(clauseBuffer, context);
+      }
     }
+
   }
 
   public Object evaluate(ExecutionContext context) {

http://git-wip-us.apache.org/repos/asf/geode/blob/7fb0e68b/geode-core/src/main/java/org/apache/geode/cache/query/internal/IndexTrackingQueryObserver.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/cache/query/internal/IndexTrackingQueryObserver.java b/geode-core/src/main/java/org/apache/geode/cache/query/internal/IndexTrackingQueryObserver.java
index a643b59..da223d5 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/query/internal/IndexTrackingQueryObserver.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/query/internal/IndexTrackingQueryObserver.java
@@ -40,6 +40,7 @@ import org.apache.geode.internal.cache.PartitionedRegionQueryEvaluator.TestHook;
 public class IndexTrackingQueryObserver extends QueryObserverAdapter {
 
   private static final ThreadLocal indexInfo = new ThreadLocal();
+  private static final ThreadLocal lastKeyUsed = new ThreadLocal();
   private static final ThreadLocal lastIndexUsed = new ThreadLocal();
   private volatile TestHook th;
 
@@ -50,15 +51,7 @@ public class IndexTrackingQueryObserver extends QueryObserverAdapter {
       this.indexInfo.set(indexMap);
     }
     IndexInfo iInfo;
-    String indexName;
-    // Dont create new IndexInfo if one is already there in map for aggregation
-    // of results later for whole partition region on this node.
-    if ((index instanceof MapRangeIndex || index instanceof CompactMapRangeIndex)
-        && key instanceof Object[]) {
-      indexName = index.getName() + "-" + ((Object[]) key)[1];
-    } else {
-      indexName = index.getName();
-    }
+    String indexName = getIndexName(index, key);
     if (indexMap.containsKey(indexName)) {
       iInfo = indexMap.get(indexName);
     } else {
@@ -67,6 +60,7 @@ public class IndexTrackingQueryObserver extends QueryObserverAdapter {
     iInfo.addRegionId(index.getRegion().getFullPath());
     indexMap.put(indexName, iInfo);
     this.lastIndexUsed.set(index);
+    this.lastKeyUsed.set(key);
     if (th != null) {
       th.hook(1);
     }
@@ -108,19 +102,32 @@ public class IndexTrackingQueryObserver extends QueryObserverAdapter {
     // append the size of the lookup results (and bucket id if its an Index on bucket)
     // to IndexInfo results Map.
     Map indexMap = (Map) this.indexInfo.get();
-    if (lastIndexUsed.get() != null) {
-      IndexInfo indexInfo = (IndexInfo) indexMap.get(((Index) this.lastIndexUsed.get()).getName());
+    Index index = (Index) lastIndexUsed.get();
+    if (index != null) {
+      IndexInfo indexInfo = (IndexInfo) indexMap.get(getIndexName(index, this.lastKeyUsed.get()));
       if (indexInfo != null) {
-        indexInfo.getResults().put(((Index) this.lastIndexUsed.get()).getRegion().getFullPath(),
-            new Integer(results.size()));
+        indexInfo.getResults().put(index.getRegion().getFullPath(), new Integer(results.size()));
       }
     }
     this.lastIndexUsed.set(null);
+    this.lastKeyUsed.set(null);
     if (th != null) {
       th.hook(3);
     }
   }
 
+  private String getIndexName(Index index, Object key) {
+    String indexName;
+    if ((index instanceof MapRangeIndex || index instanceof CompactMapRangeIndex)
+        && key instanceof Object[]) {
+      indexName = index.getName() + "-" + ((Object[]) key)[1];
+    } else {
+      indexName = index.getName();
+    }
+    return indexName;
+  }
+
+
   /**
    * This should be called only when one query execution on one gemfire node is done. NOT for each
    * buckets.

http://git-wip-us.apache.org/repos/asf/geode/blob/7fb0e68b/geode-core/src/test/java/org/apache/geode/cache/query/data/Instrument.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache/query/data/Instrument.java b/geode-core/src/test/java/org/apache/geode/cache/query/data/Instrument.java
new file mode 100644
index 0000000..131efa6
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/cache/query/data/Instrument.java
@@ -0,0 +1,60 @@
+/*
+ * 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.cache.query.data;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Instrument implements Serializable {
+
+  private String id;
+
+  private List<TradingLine> tradingLines;
+
+  public Instrument(String id) {
+    this.id = id;
+    this.tradingLines = new ArrayList<>();
+  }
+
+  public String getId() {
+    return this.id;
+  }
+
+  public void addTradingLine(TradingLine tl) {
+    this.tradingLines.add(tl);
+  }
+
+  // This method is needed for the query
+  public List<TradingLine> getTradingLines() {
+    return this.tradingLines;
+  }
+
+  public String toString() {
+    return new StringBuilder().append(getClass().getSimpleName()).append("[").append("id=")
+        .append(this.id).append("; tradingLines=").append(this.tradingLines).append("]").toString();
+  }
+
+  public static Instrument getInstrument(String id) {
+    Instrument inst = new Instrument(id);
+    for (int i = 0; i < 5; i++) {
+      TradingLine tl = new TradingLine();
+      tl.addAlternateReference("SOME_KEY", "SOME_VALUE");
+      tl.addAlternateReference("SOME_OTHER_KEY", "SOME_OTHER_VALUE");
+      inst.addTradingLine(tl);
+    }
+    return inst;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/7fb0e68b/geode-core/src/test/java/org/apache/geode/cache/query/data/TradingLine.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache/query/data/TradingLine.java b/geode-core/src/test/java/org/apache/geode/cache/query/data/TradingLine.java
new file mode 100644
index 0000000..55a5f43
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/cache/query/data/TradingLine.java
@@ -0,0 +1,41 @@
+/*
+ * 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.cache.query.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class TradingLine {
+
+  private Map<String, String> alternateReferences;
+
+  public TradingLine() {
+    this.alternateReferences = new HashMap<String, String>();
+  }
+
+  public void addAlternateReference(String key, String value) {
+    this.alternateReferences.put(key, value);
+  }
+
+  // This method is needed for the query
+  public Map<String, String> getAlternateReferences() {
+    return this.alternateReferences;
+  }
+
+  public String toString() {
+    return new StringBuilder().append(getClass().getSimpleName()).append("[")
+        .append("; alternateReferences=").append(this.alternateReferences).append("]").toString();
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/7fb0e68b/geode-core/src/test/java/org/apache/geode/cache/query/internal/index/MapRangeIndexMaintenanceJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache/query/internal/index/MapRangeIndexMaintenanceJUnitTest.java b/geode-core/src/test/java/org/apache/geode/cache/query/internal/index/MapRangeIndexMaintenanceJUnitTest.java
index 5159f89..988defb 100644
--- a/geode-core/src/test/java/org/apache/geode/cache/query/internal/index/MapRangeIndexMaintenanceJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/cache/query/internal/index/MapRangeIndexMaintenanceJUnitTest.java
@@ -21,8 +21,13 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
+import java.util.Collection;
 import java.util.HashMap;
 
+import org.apache.geode.cache.query.Query;
+import org.apache.geode.cache.query.data.Instrument;
+import org.apache.geode.cache.query.internal.IndexTrackingQueryObserver;
+import org.apache.geode.cache.query.internal.QueryObserverHolder;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -65,6 +70,50 @@ public class MapRangeIndexMaintenanceJUnitTest {
   }
 
   @Test
+  public void testMapIndexIsUsedWithBindKeyParameter() throws Exception {
+    // Create Region
+    region =
+        CacheUtils.getCache().createRegionFactory(RegionShortcut.REPLICATE).create("instrument");
+
+    // Initialize observer
+    MyQueryObserverAdapter observer = new MyQueryObserverAdapter();
+    QueryObserverHolder.setInstance(observer);
+
+    // Create map index
+    qs = CacheUtils.getQueryService();
+    qs.createIndex(INDEX_NAME, "tl.alternateReferences['SOME_KEY', 'SOME_OTHER_KEY']",
+        "/instrument i, i.tradingLines tl");
+
+    // Add instruments
+    int numInstruments = 20;
+    for (int i = 0; i < numInstruments; i++) {
+      String key = String.valueOf(i);
+      Object value = Instrument.getInstrument(key);
+      region.put(key, value);
+    }
+
+    // Execute query
+    Query query = qs.newQuery(
+        "<trace> select distinct i from /instrument i, i.tradingLines t where t.alternateReferences[$1]='SOME_VALUE'");
+    SelectResults results = (SelectResults) query.execute(new Object[] {"SOME_KEY"});
+
+    // Verify index was used
+    assertTrue(observer.indexUsed);
+
+    // Verify the results size
+    assertEquals(numInstruments, results.size());
+  }
+
+  private static class MyQueryObserverAdapter extends IndexTrackingQueryObserver {
+    public boolean indexUsed = false;
+
+    public void afterIndexLookup(Collection results) {
+      super.afterIndexLookup(results);
+      indexUsed = true;
+    }
+  }
+
+  @Test
   public void testNullMapKeysInIndexOnLocalRegionForCompactMap() throws Exception {
 
     // Create Partition Region


[36/50] [abbrv] geode git commit: GEODE-209: disable broken test until race condition is fixed

Posted by kl...@apache.org.
GEODE-209: disable broken test until race condition is fixed


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

Branch: refs/heads/feature/GEODE-1930
Commit: c48a350e33f4f74cf551ccba119436113bfc8bb2
Parents: c10a788
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Dec 12 17:45:14 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 17:45:14 2016 -0800

----------------------------------------------------------------------
 .../golden/FailWithTimeoutOfWaitForOutputToMatchJUnitTest.java   | 4 ++++
 1 file changed, 4 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/c48a350e/geode-core/src/test/java/org/apache/geode/test/golden/FailWithTimeoutOfWaitForOutputToMatchJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/golden/FailWithTimeoutOfWaitForOutputToMatchJUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/golden/FailWithTimeoutOfWaitForOutputToMatchJUnitTest.java
index 67798f2..eff4234 100755
--- a/geode-core/src/test/java/org/apache/geode/test/golden/FailWithTimeoutOfWaitForOutputToMatchJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/golden/FailWithTimeoutOfWaitForOutputToMatchJUnitTest.java
@@ -16,9 +16,11 @@ package org.apache.geode.test.golden;
 
 import static org.junit.Assert.*;
 
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
+import org.apache.geode.test.junit.categories.FlakyTest;
 import org.apache.geode.test.process.ProcessWrapper;
 import org.apache.geode.test.junit.categories.IntegrationTest;
 
@@ -46,6 +48,8 @@ public class FailWithTimeoutOfWaitForOutputToMatchJUnitTest extends FailOutputTe
   /**
    * Process output has an extra line and should fail
    */
+  @Category(FlakyTest.class) // GEODE-209
+  @Ignore // cause of GEODE-209 is process.destroy() closes the stream
   @Test
   public void testFailWithTimeoutOfWaitForOutputToMatch() throws Exception {
     this.process =


[30/50] [abbrv] geode git commit: GEODE-2196: revert changes that broke Jenkins build

Posted by kl...@apache.org.
GEODE-2196: revert changes that broke Jenkins build


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

Branch: refs/heads/feature/GEODE-1930
Commit: 5d2f0f6b56f0fd22b5fd8cea7abc3bccb26117d8
Parents: 03c79a6
Author: Jinmei Liao <ji...@pivotal.io>
Authored: Mon Dec 12 08:43:05 2016 -0800
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Mon Dec 12 08:43:05 2016 -0800

----------------------------------------------------------------------
 .../internal/DistributionConfig.java            |   2 +-
 .../internal/DistributionConfigImpl.java        |   2 +-
 .../configuration/ClusterConfigDUnitTest.java   | 243 -------------------
 3 files changed, 2 insertions(+), 245 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/5d2f0f6b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java
index c2a395d..5eb070d 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java
@@ -384,7 +384,7 @@ public interface DistributionConfig extends Config, LogConfig {
    * Default will be the current working directory as determined by
    * <code>System.getProperty("user.dir")</code>.
    */
-  File DEFAULT_DEPLOY_WORKING_DIR = new File(System.getProperty("user.dir"));
+  File DEFAULT_DEPLOY_WORKING_DIR = new File(".");
 
   /**
    * Returns the value of the {@link ConfigurationProperties#USER_COMMAND_PACKAGES} property

http://git-wip-us.apache.org/repos/asf/geode/blob/5d2f0f6b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java
index fa6d13f..0c6603d 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java
@@ -124,7 +124,7 @@ public class DistributionConfigImpl extends AbstractDistributionConfig implement
    */
   private File logFile = DEFAULT_LOG_FILE;
 
-  protected File deployWorkingDir = new File(System.getProperty("user.dir"));
+  protected File deployWorkingDir = DEFAULT_DEPLOY_WORKING_DIR;
 
   /**
    * The level at which log messages are logged

http://git-wip-us.apache.org/repos/asf/geode/blob/5d2f0f6b/geode-core/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigDUnitTest.java
deleted file mode 100644
index 418999a..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigDUnitTest.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * 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.internal.configuration;
-
-import static org.apache.geode.distributed.ConfigurationProperties.CLUSTER_CONFIGURATION_DIR;
-import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION;
-import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
-import static org.apache.geode.distributed.ConfigurationProperties.LOAD_CLUSTER_CONFIGURATION_FROM_DIR;
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
-import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE_SIZE_LIMIT;
-import static org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import org.apache.geode.cache.Cache;
-import org.apache.geode.distributed.internal.InternalLocator;
-import org.apache.geode.distributed.internal.SharedConfiguration;
-import org.apache.geode.internal.ClassPathLoader;
-import org.apache.geode.internal.JarClassLoader;
-import org.apache.geode.management.internal.configuration.domain.Configuration;
-import org.apache.geode.management.internal.configuration.utils.ZipUtils;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
-import org.apache.geode.test.dunit.rules.Member;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Properties;
-
-@Category(DistributedTest.class)
-public class ClusterConfigDUnitTest extends JUnit4DistributedTestCase {
-  private static final String EXPORTED_CLUSTER_CONFIG_ZIP_FILENAME = "cluster_config.zip";
-  private static final String[] CONFIG_NAMES = new String[] {"cluster", "group1", "group2"};
-
-  private static final ExpectedConfig NO_GROUP =
-      new ExpectedConfig().maxLogFileSize("5000").regions("regionForCluster").jars("cluster.jar");
-
-  private static final ExpectedConfig GROUP1 = new ExpectedConfig().maxLogFileSize("6000")
-      .regions("regionForCluster", "regionForGroup1").jars("cluster.jar", "group1.jar");
-
-  private static final ExpectedConfig GROUP2 = new ExpectedConfig().maxLogFileSize("7000")
-      .regions("regionForCluster", "regionForGroup2").jars("cluster.jar", "group2.jar");
-
-  private static final ExpectedConfig GROUP1_AND_2 = new ExpectedConfig().maxLogFileSize("7000")
-      .regions("regionForCluster", "regionForGroup1", "regionForGroup2")
-      .jars("cluster.jar", "group1.jar", "group2.jar");
-
-
-  private String locatorString;
-
-  @Rule
-  public LocatorServerStartupRule lsRule = new LocatorServerStartupRule();
-
-  @Before
-  public void setupFirstLocatorWithClusterConfigFromDirectory() throws Exception {
-    File locatorDir = lsRule.getRootFolder().newFolder("locator-0");
-
-    // The unzip should yield a cluster config directory structure like:
-    // tempFolder/locator-0/cluster_config/cluster/cluster.xml
-    // tempFolder/locator-0/cluster_config/cluster/cluster.properties
-    // tempFolder/locator-0/cluster_config/cluster/cluster.jar
-    // tempFolder/locator-0/cluster_config/group1/ {group1.xml, group1.properties, group1.jar}
-    // tempFolder/locator-0/cluster_config/group2/ ...
-    ZipUtils.unzip(getClass().getResource(EXPORTED_CLUSTER_CONFIG_ZIP_FILENAME).getPath(),
-        locatorDir.getCanonicalPath());
-
-    Properties locatorProps = new Properties();
-    locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
-    locatorProps.setProperty(LOAD_CLUSTER_CONFIGURATION_FROM_DIR, "true");
-    locatorProps.setProperty(CLUSTER_CONFIGURATION_DIR, locatorDir.getCanonicalPath());
-
-    Member firstLocator = lsRule.startLocatorVM(0, locatorProps);
-    locatorString = "localhost[" + firstLocator.getPort() + "]";
-
-    verifyLocatorConfigExistsInFileSystem(firstLocator.getWorkingDir());
-    firstLocator.invoke(this::verifyLocatorConfigExistsInInternalRegion);
-  }
-
-  @Test
-  public void secondLocatorLoadsClusterConfigFromFirstLocator() throws IOException {
-    Properties secondLocatorProps = new Properties();
-    secondLocatorProps.setProperty(LOCATORS, locatorString);
-    secondLocatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
-    Member secondLocator = lsRule.startLocatorVM(1, secondLocatorProps);
-
-    verifyLocatorConfig(secondLocator);
-  }
-
-  @Test
-  public void serverWithZeroOrOneGroupsLoadCorrectConfigFromLocator() throws Exception {
-    Properties serverProps = new Properties();
-    serverProps.setProperty(LOCATORS, locatorString);
-    serverProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
-
-    Member serverWithNoGroup = lsRule.startServerVM(1, serverProps);
-    verifyServerConfig(NO_GROUP, serverWithNoGroup);
-
-    serverProps.setProperty(GROUPS, "group1");
-    Member serverForGroup1 = lsRule.startServerVM(2, serverProps);
-    verifyServerConfig(GROUP1, serverForGroup1);
-
-    serverProps.setProperty(GROUPS, "group2");
-    Member serverForGroup2 = lsRule.startServerVM(3, serverProps);
-    verifyServerConfig(GROUP2, serverForGroup2);
-  }
-
-  @Test
-  public void oneServerWithMultipleGroupsLoadsCorrectConfigFromLocator() throws Exception {
-    Properties serverProps = new Properties();
-    serverProps.setProperty(LOCATORS, locatorString);
-    serverProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
-    serverProps.setProperty(GROUPS, "group1,group2");
-    Member serverWithNoGroup = lsRule.startServerVM(1, serverProps);
-
-    serverWithNoGroup.invoke(() -> this.verifyServerConfig(GROUP1_AND_2, serverWithNoGroup));
-  }
-
-  private void verifyLocatorConfig(Member locator) {
-    verifyLocatorConfigExistsInFileSystem(locator.getWorkingDir());
-    locator.invoke(this::verifyLocatorConfigExistsInInternalRegion);
-  }
-
-  private void verifyServerConfig(ExpectedConfig expectedConfig, Member server)
-      throws ClassNotFoundException {
-    verifyServerJarFilesExistInFileSystem(server.getWorkingDir(), expectedConfig.jars);
-    server.invoke(() -> this.verifyServerConfigInMemory(expectedConfig));
-  }
-
-  private void verifyLocatorConfigExistsInFileSystem(File workingDir) {
-    File clusterConfigDir = new File(workingDir, "cluster_config");
-    assertThat(clusterConfigDir).exists();
-
-    for (String configName : CONFIG_NAMES) {
-      File configDir = new File(clusterConfigDir, configName);
-      assertThat(configDir).exists();
-
-      File jar = new File(configDir, configName + ".jar");
-      File properties = new File(configDir, configName + ".properties");
-      File xml = new File(configDir, configName + ".xml");
-      assertThat(configDir.listFiles()).contains(jar, properties, xml);
-    }
-  }
-
-  private void verifyLocatorConfigExistsInInternalRegion() throws Exception {
-    InternalLocator internalLocator = LocatorServerStartupRule.locatorStarter.locator;
-    SharedConfiguration sc = internalLocator.getSharedConfiguration();
-
-    for (String configName : CONFIG_NAMES) {
-      Configuration config = sc.getConfiguration(configName);
-      assertThat(config).isNotNull();
-    }
-  }
-
-  private void verifyServerConfigInMemory(ExpectedConfig expectedConfig)
-      throws ClassNotFoundException {
-    Cache cache = LocatorServerStartupRule.serverStarter.cache;
-    for (String region : expectedConfig.regions) {
-      assertThat(cache.getRegion(region)).isNotNull();
-    }
-    Properties props = cache.getDistributedSystem().getProperties();
-    assertThat(props.getProperty(LOG_FILE_SIZE_LIMIT)).isEqualTo(expectedConfig.maxLogFileSize);
-
-    for (String jar : expectedConfig.jars) {
-      JarClassLoader jarClassLoader = findJarClassLoader(jar);
-      assertThat(jarClassLoader).isNotNull();
-      assertThat(jarClassLoader.loadClass(nameOfClassContainedInJar(jar))).isNotNull();
-    }
-  }
-
-  private void verifyServerJarFilesExistInFileSystem(File workingDir, String[] jarNames) {
-    assertThat(workingDir.listFiles()).isNotEmpty();
-
-    for (String jarName : jarNames) {
-      assertThat(workingDir.listFiles()).filteredOn((File file) -> file.getName().contains(jarName))
-          .isNotEmpty();
-    }
-  }
-
-  private String nameOfClassContainedInJar(String jarName) {
-    switch (jarName) {
-      case "cluster.jar":
-        return "Cluster";
-      case "group1.jar":
-        return "Group1";
-      case "group2.jar":
-        return "Group2";
-      default:
-        throw new IllegalArgumentException(
-            EXPORTED_CLUSTER_CONFIG_ZIP_FILENAME + " does not contain a jar named " + jarName);
-    }
-  }
-
-  private JarClassLoader findJarClassLoader(final String jarName) {
-    Collection<ClassLoader> classLoaders = ClassPathLoader.getLatest().getClassLoaders();
-    for (ClassLoader classLoader : classLoaders) {
-      if (classLoader instanceof JarClassLoader
-          && ((JarClassLoader) classLoader).getJarName().equals(jarName)) {
-        return (JarClassLoader) classLoader;
-      }
-    }
-    return null;
-  }
-
-  private static class ExpectedConfig implements Serializable {
-    public String maxLogFileSize;
-    public String[] regions;
-    public String[] jars;
-
-    public ExpectedConfig maxLogFileSize(String maxLogFileSize) {
-      this.maxLogFileSize = maxLogFileSize;
-      return this;
-    }
-
-    public ExpectedConfig regions(String... regions) {
-      this.regions = regions;
-      return this;
-    }
-
-    public ExpectedConfig jars(String... jars) {
-      this.jars = jars;
-      return this;
-    }
-  }
-}


[09/50] [abbrv] geode git commit: GEODE-2004: [doc update] change to a permission for REST-initiated queries. Updated error messages.

Posted by kl...@apache.org.
GEODE-2004: [doc update] change to a permission for REST-initiated queries. Updated error messages.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 1d34eeb9f6217a4375590094166e5b81a820abae
Parents: 22ec6a7
Author: Dave Barnes <db...@pivotal.io>
Authored: Wed Dec 7 14:37:09 2016 -0800
Committer: Dave Barnes <db...@pivotal.io>
Committed: Wed Dec 7 14:37:09 2016 -0800

----------------------------------------------------------------------
 .../rest_apps/delete_named_query.html.md.erb    |  4 ++-
 .../get_execute_adhoc_query.html.md.erb         | 12 +++++++
 geode-docs/rest_apps/get_queries.html.md.erb    | 30 ++++++++++++++---
 .../rest_apps/post_create_query.html.md.erb     | 16 +++++++--
 .../rest_apps/post_execute_query.html.md.erb    | 18 +++++++++--
 .../rest_apps/put_update_query.html.md.erb      | 34 +++++++++++++++++---
 6 files changed, 100 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/1d34eeb9/geode-docs/rest_apps/delete_named_query.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/rest_apps/delete_named_query.html.md.erb b/geode-docs/rest_apps/delete_named_query.html.md.erb
index ae109d6..d26ea36 100644
--- a/geode-docs/rest_apps/delete_named_query.html.md.erb
+++ b/geode-docs/rest_apps/delete_named_query.html.md.erb
@@ -54,7 +54,9 @@ Response Payload: application/json
 
 | Status Code               | Description                                                                                   |
 |---------------------------|-----------------------------------------------------------------------------------------------|
-| 404 NOT FOUND             | Query with specified ID could not be found.                                                   |
+| 401 UNAUTHORIZED          | Invalid Username or Password                                                                  |
+| 403 FORBIDDEN             | Insufficient privileges for operation                                                         |
+| 404 NOT FOUND             | Query with specified ID could not be found                                                    |
 | 500 INTERNAL SERVER ERROR | Encountered error at server. Check the HTTP response body for a stack trace of the exception. |
 
 

http://git-wip-us.apache.org/repos/asf/geode/blob/1d34eeb9/geode-docs/rest_apps/get_execute_adhoc_query.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/rest_apps/get_execute_adhoc_query.html.md.erb b/geode-docs/rest_apps/get_execute_adhoc_query.html.md.erb
index 0a70c82..dc31407 100644
--- a/geode-docs/rest_apps/get_execute_adhoc_query.html.md.erb
+++ b/geode-docs/rest_apps/get_execute_adhoc_query.html.md.erb
@@ -103,10 +103,22 @@ Content-Type: application/json
 </tr>
 </thead>
 <tbody>
+<tr>
+<td>401 UNAUTHORIZED</td>
+<td>Invalid Username or Password</td>
+</tr>
+<tr>
+<td>403 FORBIDDEN</td>
+<td>Insufficient privileges for operation</td>
+</tr>
 <tr class="odd">
 <td>500 INTERNAL SERVER ERROR</td>
 <td>Error encountered at Geode server. Check the HTTP response body for a stack trace of the exception. Some possible exceptions include:
 <ul>
+<li>A function was applied to a parameter that is improper for that function!</li>
+<li>Bind parameter is not of the expected type!</li>
+<li>Name in the query cannot be resolved!</li>
+<li>The number of bound parameters does not match the number of placeholders!</li>
 <li>Query is not permitted on this type of region!</li>
 <li>Query execution time is exceeded max query execution time (gemfire.Cache.MAX_QUERY_EXECUTION_TIME) configured!</li>
 <li>Data referenced in from clause is not available for querying!</li>

http://git-wip-us.apache.org/repos/asf/geode/blob/1d34eeb9/geode-docs/rest_apps/get_queries.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/rest_apps/get_queries.html.md.erb b/geode-docs/rest_apps/get_queries.html.md.erb
index 71e0219..ba86e55 100644
--- a/geode-docs/rest_apps/get_queries.html.md.erb
+++ b/geode-docs/rest_apps/get_queries.html.md.erb
@@ -65,8 +65,30 @@ Location: http://localhost:8080/gemfire-api/v1/queries
 
 ## Error Codes
 
-| �                         | �                                                                                                                                |
-|---------------------------|----------------------------------------------------------------------------------------------------------------------------------|
-| 500 INTERNAL SERVER ERROR | Error encountered at Geode server. Check the HTTP response body for a stack trace of the exception. |
-
+<table>
+<colgroup>
+<col width="40%" />
+<col width="60%" />
+</colgroup>
+<thead>
+<tr class="header">
+<th>Status Code</th>
+<th>Description</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>401 UNAUTHORIZED</td>
+<td>Invalid Username or Password</td>
+</tr>
+<tr>
+<td>403 FORBIDDEN</td>
+<td>Insufficient privileges for operation</td>
+</tr>
+<tr class="even">
+<td>500 INTERNAL SERVER ERROR</td>
+<td>Error encountered at Geode server. Check the HTTP response body for a stack trace of the exception.</td>
+</tr>
+</tbody>
+</table>
 

http://git-wip-us.apache.org/repos/asf/geode/blob/1d34eeb9/geode-docs/rest_apps/post_create_query.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/rest_apps/post_create_query.html.md.erb b/geode-docs/rest_apps/post_create_query.html.md.erb
index 9062948..9fdba2a 100644
--- a/geode-docs/rest_apps/post_create_query.html.md.erb
+++ b/geode-docs/rest_apps/post_create_query.html.md.erb
@@ -89,9 +89,21 @@ Location: http://localhost:8080/gemfire-api/v1/queries/selectOrders
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
 <td>400 BAD REQUEST</td>
-<td>Returned if user does not specify a query ID or a malformed OQL statement.</td>
+<td>Query ID not specified or malformed OQL statement</td>
+</tr>
+<tr>
+<td>401 UNAUTHORIZED</td>
+<td>Invalid Username or Password</td>
+</tr>
+<tr>
+<td>403 FORBIDDEN</td>
+<td>Insufficient privileges for operation</td>
+</tr>
+<tr>
+<td>409 CONFLICT</td>
+<td>QueryId already assigned to another query</td>
 </tr>
 <tr class="even">
 <td>500 INTERNAL SERVER ERROR</td>

http://git-wip-us.apache.org/repos/asf/geode/blob/1d34eeb9/geode-docs/rest_apps/post_execute_query.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/rest_apps/post_execute_query.html.md.erb b/geode-docs/rest_apps/post_execute_query.html.md.erb
index 7d0853c..f0557ba 100644
--- a/geode-docs/rest_apps/post_execute_query.html.md.erb
+++ b/geode-docs/rest_apps/post_execute_query.html.md.erb
@@ -146,9 +146,21 @@ Content-Type: application/json
 </tr>
 </thead>
 <tbody>
-<tr class="odd">
+<tr>
+<tr>
+<td>400 BAD REQUEST</td>
+<td>JSON document in the request body (specifying query bind params) is invalid</td>
+</tr>
+<td>401 UNAUTHORIZED</td>
+<td>Invalid Username or Password</td>
+</tr>
+<tr>
+<td>403 FORBIDDEN</td>
+<td>Insufficient privileges for operation</td>
+</tr>
+<tr>
 <td>404 NOT FOUND</td>
-<td>Query with specified ID could not be found.</td>
+<td>Query with specified ID could not be found</td>
 </tr>
 <tr class="even">
 <td>500 INTERNAL SERVER ERROR</td>
@@ -160,7 +172,7 @@ Content-Type: application/json
 <li>Name in the query cannot be resolved!&quot;</li>
 <li>The number of bound parameters does not match the number of placeholders!</li>
 <li>Query is not permitted on this type of region!</li>
-<li>Query execution time is exceeded max query execution time (gemfire.Cache.MAX_QUERY_EXECUTION_TIME) configured!</li>
+<li>Query execution time has exceeded max query execution time (gemfire.Cache.MAX_QUERY_EXECUTION_TIME) configured!</li>
 <li>Data referenced in from clause is not available for querying!&quot;</li>
 <li>Query execution gets canceled due to low memory conditions and the resource manager critical heap percentage has been set!&quot;</li>
 <li>Error encountered while executing named query!&quot;</li>

http://git-wip-us.apache.org/repos/asf/geode/blob/1d34eeb9/geode-docs/rest_apps/put_update_query.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/rest_apps/put_update_query.html.md.erb b/geode-docs/rest_apps/put_update_query.html.md.erb
index 966154a..339f4d7 100644
--- a/geode-docs/rest_apps/put_update_query.html.md.erb
+++ b/geode-docs/rest_apps/put_update_query.html.md.erb
@@ -73,10 +73,36 @@ Response Payload:  null
 
 ## Error Codes
 
-| Status Code               | Description                                                                                                                      |
-|---------------------------|----------------------------------------------------------------------------------------------------------------------------------|
-| 404 NOT FOUND             | Returned if the specified queryId cannot be found.                                                                               |
-| 500 INTERNAL SERVER ERROR | Error encountered at Geode server. Check the HTTP response body for a stack trace of the exception. |
+<table>
+<colgroup>
+<col width="50%" />
+<col width="50%" />
+</colgroup>
+<thead>
+<tr class="header">
+<th>Status Code</th>
+<th>Description</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>401 UNAUTHORIZED</td>
+<td>Invalid Username or Password</td>
+</tr>
+<tr>
+<td>403 FORBIDDEN</td>
+<td>Insufficient privileges for operation</td>
+</tr>
+<tr>
+<td>404 NOT FOUND</td>
+<td>QueryID does not exist</td>
+</tr>
+<tr class="odd">
+<td>500 INTERNAL SERVER ERROR</td>
+<td>Error encountered at Geode server. Check the HTTP response body for a stack trace of the exception.</td>
+</tr>
+</tbody>
+</table>
 
 ## Implementation Notes
 


[23/50] [abbrv] geode git commit: [GEODE-2196] Add test for Cluster Config. Refactor LocatorServerStartupRule.

Posted by kl...@apache.org.
[GEODE-2196] Add test for Cluster Config. Refactor LocatorServerStartupRule.

* Add ClusterConfigDUnitTest
* Refactor LocatorServerStartupRule
* this closes #309


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

Branch: refs/heads/feature/GEODE-1930
Commit: adfd41f437d2a30255ae8368e355b497d6bb0164
Parents: 213d8bc
Author: Jared Stewart <js...@pivotal.io>
Authored: Thu Dec 8 15:03:54 2016 -0800
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Fri Dec 9 09:47:07 2016 -0800

----------------------------------------------------------------------
 .../internal/DistributionConfig.java            |   2 +-
 .../internal/DistributionConfigImpl.java        |   2 +-
 .../ConnectToLocatorSSLDUnitTest.java           |   6 +-
 .../configuration/ClusterConfigDUnitTest.java   | 243 +++++++++++++++++++
 .../ClusterConfigWithoutSecurityDUnitTest.java  |   8 +-
 .../security/PeerAuthenticatorDUnitTest.java    |  12 +-
 ...eerSecurityWithEmbeddedLocatorDUnitTest.java |  18 +-
 .../SecurityClusterConfigDUnitTest.java         |  13 +-
 .../SecurityWithoutClusterConfigDUnitTest.java  |   7 +-
 .../security/StartServerAuthorizationTest.java  |  33 ++-
 .../dunit/rules/LocatorServerStartupRule.java   | 108 +++++----
 .../test/dunit/rules/LocatorStarterRule.java    |  11 +-
 .../apache/geode/test/dunit/rules/Member.java   |  62 +++++
 .../test/dunit/rules/ServerStarterRule.java     |  32 ++-
 .../internal/configuration/cluster_config.zip   | Bin 0 -> 4666 bytes
 .../LuceneClusterConfigurationDUnitTest.java    |  48 ++--
 16 files changed, 474 insertions(+), 131 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java
index 5eb070d..c2a395d 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfig.java
@@ -384,7 +384,7 @@ public interface DistributionConfig extends Config, LogConfig {
    * Default will be the current working directory as determined by
    * <code>System.getProperty("user.dir")</code>.
    */
-  File DEFAULT_DEPLOY_WORKING_DIR = new File(".");
+  File DEFAULT_DEPLOY_WORKING_DIR = new File(System.getProperty("user.dir"));
 
   /**
    * Returns the value of the {@link ConfigurationProperties#USER_COMMAND_PACKAGES} property

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java
index 0c6603d..fa6d13f 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionConfigImpl.java
@@ -124,7 +124,7 @@ public class DistributionConfigImpl extends AbstractDistributionConfig implement
    */
   private File logFile = DEFAULT_LOG_FILE;
 
-  protected File deployWorkingDir = DEFAULT_DEPLOY_WORKING_DIR;
+  protected File deployWorkingDir = new File(System.getProperty("user.dir"));
 
   /**
    * The level at which log messages are logged

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java
index 751425a..142ce17 100644
--- a/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java
@@ -83,14 +83,14 @@ public class ConnectToLocatorSSLDUnitTest extends JUnit4DistributedTestCase {
   }
 
   public void setUpLocatorAndConnect(Properties securityProps) throws Exception {
-    lsRule.getLocatorVM(0, securityProps);
+    lsRule.startLocatorVM(0, securityProps);
 
     // saving the securityProps to a file
     OutputStream out = new FileOutputStream(securityPropsFile);
     securityProps.store(out, "");
 
-    GfshShellConnectionRule gfshConnector =
-        new GfshShellConnectionRule(lsRule.getPort(0), GfshShellConnectionRule.PortType.locator);
+    GfshShellConnectionRule gfshConnector = new GfshShellConnectionRule(
+        lsRule.getMember(0).getPort(), GfshShellConnectionRule.PortType.locator);
 
     // when we connect too soon, we would get "Failed to retrieve RMIServer stub:
     // javax.naming.CommunicationException [Root exception is java.rmi.NoSuchObjectException: no

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigDUnitTest.java
new file mode 100644
index 0000000..418999a
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigDUnitTest.java
@@ -0,0 +1,243 @@
+/*
+ * 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.internal.configuration;
+
+import static org.apache.geode.distributed.ConfigurationProperties.CLUSTER_CONFIGURATION_DIR;
+import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION;
+import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
+import static org.apache.geode.distributed.ConfigurationProperties.LOAD_CLUSTER_CONFIGURATION_FROM_DIR;
+import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE_SIZE_LIMIT;
+import static org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.distributed.internal.InternalLocator;
+import org.apache.geode.distributed.internal.SharedConfiguration;
+import org.apache.geode.internal.ClassPathLoader;
+import org.apache.geode.internal.JarClassLoader;
+import org.apache.geode.management.internal.configuration.domain.Configuration;
+import org.apache.geode.management.internal.configuration.utils.ZipUtils;
+import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
+import org.apache.geode.test.dunit.rules.Member;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Properties;
+
+@Category(DistributedTest.class)
+public class ClusterConfigDUnitTest extends JUnit4DistributedTestCase {
+  private static final String EXPORTED_CLUSTER_CONFIG_ZIP_FILENAME = "cluster_config.zip";
+  private static final String[] CONFIG_NAMES = new String[] {"cluster", "group1", "group2"};
+
+  private static final ExpectedConfig NO_GROUP =
+      new ExpectedConfig().maxLogFileSize("5000").regions("regionForCluster").jars("cluster.jar");
+
+  private static final ExpectedConfig GROUP1 = new ExpectedConfig().maxLogFileSize("6000")
+      .regions("regionForCluster", "regionForGroup1").jars("cluster.jar", "group1.jar");
+
+  private static final ExpectedConfig GROUP2 = new ExpectedConfig().maxLogFileSize("7000")
+      .regions("regionForCluster", "regionForGroup2").jars("cluster.jar", "group2.jar");
+
+  private static final ExpectedConfig GROUP1_AND_2 = new ExpectedConfig().maxLogFileSize("7000")
+      .regions("regionForCluster", "regionForGroup1", "regionForGroup2")
+      .jars("cluster.jar", "group1.jar", "group2.jar");
+
+
+  private String locatorString;
+
+  @Rule
+  public LocatorServerStartupRule lsRule = new LocatorServerStartupRule();
+
+  @Before
+  public void setupFirstLocatorWithClusterConfigFromDirectory() throws Exception {
+    File locatorDir = lsRule.getRootFolder().newFolder("locator-0");
+
+    // The unzip should yield a cluster config directory structure like:
+    // tempFolder/locator-0/cluster_config/cluster/cluster.xml
+    // tempFolder/locator-0/cluster_config/cluster/cluster.properties
+    // tempFolder/locator-0/cluster_config/cluster/cluster.jar
+    // tempFolder/locator-0/cluster_config/group1/ {group1.xml, group1.properties, group1.jar}
+    // tempFolder/locator-0/cluster_config/group2/ ...
+    ZipUtils.unzip(getClass().getResource(EXPORTED_CLUSTER_CONFIG_ZIP_FILENAME).getPath(),
+        locatorDir.getCanonicalPath());
+
+    Properties locatorProps = new Properties();
+    locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
+    locatorProps.setProperty(LOAD_CLUSTER_CONFIGURATION_FROM_DIR, "true");
+    locatorProps.setProperty(CLUSTER_CONFIGURATION_DIR, locatorDir.getCanonicalPath());
+
+    Member firstLocator = lsRule.startLocatorVM(0, locatorProps);
+    locatorString = "localhost[" + firstLocator.getPort() + "]";
+
+    verifyLocatorConfigExistsInFileSystem(firstLocator.getWorkingDir());
+    firstLocator.invoke(this::verifyLocatorConfigExistsInInternalRegion);
+  }
+
+  @Test
+  public void secondLocatorLoadsClusterConfigFromFirstLocator() throws IOException {
+    Properties secondLocatorProps = new Properties();
+    secondLocatorProps.setProperty(LOCATORS, locatorString);
+    secondLocatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
+    Member secondLocator = lsRule.startLocatorVM(1, secondLocatorProps);
+
+    verifyLocatorConfig(secondLocator);
+  }
+
+  @Test
+  public void serverWithZeroOrOneGroupsLoadCorrectConfigFromLocator() throws Exception {
+    Properties serverProps = new Properties();
+    serverProps.setProperty(LOCATORS, locatorString);
+    serverProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
+
+    Member serverWithNoGroup = lsRule.startServerVM(1, serverProps);
+    verifyServerConfig(NO_GROUP, serverWithNoGroup);
+
+    serverProps.setProperty(GROUPS, "group1");
+    Member serverForGroup1 = lsRule.startServerVM(2, serverProps);
+    verifyServerConfig(GROUP1, serverForGroup1);
+
+    serverProps.setProperty(GROUPS, "group2");
+    Member serverForGroup2 = lsRule.startServerVM(3, serverProps);
+    verifyServerConfig(GROUP2, serverForGroup2);
+  }
+
+  @Test
+  public void oneServerWithMultipleGroupsLoadsCorrectConfigFromLocator() throws Exception {
+    Properties serverProps = new Properties();
+    serverProps.setProperty(LOCATORS, locatorString);
+    serverProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
+    serverProps.setProperty(GROUPS, "group1,group2");
+    Member serverWithNoGroup = lsRule.startServerVM(1, serverProps);
+
+    serverWithNoGroup.invoke(() -> this.verifyServerConfig(GROUP1_AND_2, serverWithNoGroup));
+  }
+
+  private void verifyLocatorConfig(Member locator) {
+    verifyLocatorConfigExistsInFileSystem(locator.getWorkingDir());
+    locator.invoke(this::verifyLocatorConfigExistsInInternalRegion);
+  }
+
+  private void verifyServerConfig(ExpectedConfig expectedConfig, Member server)
+      throws ClassNotFoundException {
+    verifyServerJarFilesExistInFileSystem(server.getWorkingDir(), expectedConfig.jars);
+    server.invoke(() -> this.verifyServerConfigInMemory(expectedConfig));
+  }
+
+  private void verifyLocatorConfigExistsInFileSystem(File workingDir) {
+    File clusterConfigDir = new File(workingDir, "cluster_config");
+    assertThat(clusterConfigDir).exists();
+
+    for (String configName : CONFIG_NAMES) {
+      File configDir = new File(clusterConfigDir, configName);
+      assertThat(configDir).exists();
+
+      File jar = new File(configDir, configName + ".jar");
+      File properties = new File(configDir, configName + ".properties");
+      File xml = new File(configDir, configName + ".xml");
+      assertThat(configDir.listFiles()).contains(jar, properties, xml);
+    }
+  }
+
+  private void verifyLocatorConfigExistsInInternalRegion() throws Exception {
+    InternalLocator internalLocator = LocatorServerStartupRule.locatorStarter.locator;
+    SharedConfiguration sc = internalLocator.getSharedConfiguration();
+
+    for (String configName : CONFIG_NAMES) {
+      Configuration config = sc.getConfiguration(configName);
+      assertThat(config).isNotNull();
+    }
+  }
+
+  private void verifyServerConfigInMemory(ExpectedConfig expectedConfig)
+      throws ClassNotFoundException {
+    Cache cache = LocatorServerStartupRule.serverStarter.cache;
+    for (String region : expectedConfig.regions) {
+      assertThat(cache.getRegion(region)).isNotNull();
+    }
+    Properties props = cache.getDistributedSystem().getProperties();
+    assertThat(props.getProperty(LOG_FILE_SIZE_LIMIT)).isEqualTo(expectedConfig.maxLogFileSize);
+
+    for (String jar : expectedConfig.jars) {
+      JarClassLoader jarClassLoader = findJarClassLoader(jar);
+      assertThat(jarClassLoader).isNotNull();
+      assertThat(jarClassLoader.loadClass(nameOfClassContainedInJar(jar))).isNotNull();
+    }
+  }
+
+  private void verifyServerJarFilesExistInFileSystem(File workingDir, String[] jarNames) {
+    assertThat(workingDir.listFiles()).isNotEmpty();
+
+    for (String jarName : jarNames) {
+      assertThat(workingDir.listFiles()).filteredOn((File file) -> file.getName().contains(jarName))
+          .isNotEmpty();
+    }
+  }
+
+  private String nameOfClassContainedInJar(String jarName) {
+    switch (jarName) {
+      case "cluster.jar":
+        return "Cluster";
+      case "group1.jar":
+        return "Group1";
+      case "group2.jar":
+        return "Group2";
+      default:
+        throw new IllegalArgumentException(
+            EXPORTED_CLUSTER_CONFIG_ZIP_FILENAME + " does not contain a jar named " + jarName);
+    }
+  }
+
+  private JarClassLoader findJarClassLoader(final String jarName) {
+    Collection<ClassLoader> classLoaders = ClassPathLoader.getLatest().getClassLoaders();
+    for (ClassLoader classLoader : classLoaders) {
+      if (classLoader instanceof JarClassLoader
+          && ((JarClassLoader) classLoader).getJarName().equals(jarName)) {
+        return (JarClassLoader) classLoader;
+      }
+    }
+    return null;
+  }
+
+  private static class ExpectedConfig implements Serializable {
+    public String maxLogFileSize;
+    public String[] regions;
+    public String[] jars;
+
+    public ExpectedConfig maxLogFileSize(String maxLogFileSize) {
+      this.maxLogFileSize = maxLogFileSize;
+      return this;
+    }
+
+    public ExpectedConfig regions(String... regions) {
+      this.regions = regions;
+      return this;
+    }
+
+    public ExpectedConfig jars(String... jars) {
+      this.jars = jars;
+      return this;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/security/ClusterConfigWithoutSecurityDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/ClusterConfigWithoutSecurityDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/ClusterConfigWithoutSecurityDUnitTest.java
index 1ad6799..fe37f9e 100644
--- a/geode-core/src/test/java/org/apache/geode/security/ClusterConfigWithoutSecurityDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/ClusterConfigWithoutSecurityDUnitTest.java
@@ -21,6 +21,7 @@ import static org.junit.Assert.*;
 
 import java.util.Properties;
 
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.apache.geode.test.dunit.rules.ServerStarterRule;
 import org.junit.After;
 import org.junit.Before;
@@ -33,7 +34,6 @@ import org.apache.geode.distributed.DistributedSystem;
 import org.apache.geode.internal.i18n.LocalizedStrings;
 import org.apache.geode.test.dunit.IgnoredException;
 import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.SecurityTest;
 
@@ -50,7 +50,7 @@ public class ClusterConfigWithoutSecurityDUnitTest extends JUnit4DistributedTest
         .addIgnoredException(LocalizedStrings.GEMFIRE_CACHE_SECURITY_MISCONFIGURATION.toString());
     IgnoredException
         .addIgnoredException(LocalizedStrings.GEMFIRE_CACHE_SECURITY_MISCONFIGURATION_2.toString());
-    lsRule.getLocatorVM(0, new Properties());
+    lsRule.startLocatorVM(0, new Properties());
   }
 
   @After
@@ -71,7 +71,7 @@ public class ClusterConfigWithoutSecurityDUnitTest extends JUnit4DistributedTest
 
     // initial security properties should only contain initial set of values
     ServerStarterRule serverStarter = new ServerStarterRule(props);
-    serverStarter.startServer(lsRule.getPort(0));
+    serverStarter.startServer(lsRule.getMember(0).getPort());
     DistributedSystem ds = serverStarter.cache.getDistributedSystem();
 
     // after cache is created, the configuration won't chagne
@@ -93,7 +93,7 @@ public class ClusterConfigWithoutSecurityDUnitTest extends JUnit4DistributedTest
 
     ServerStarterRule serverStarter = new ServerStarterRule(props);
 
-    assertThatThrownBy(() -> serverStarter.startServer(lsRule.getPort(0)))
+    assertThatThrownBy(() -> serverStarter.startServer(lsRule.getMember(0).getPort()))
         .isInstanceOf(GemFireConfigException.class)
         .hasMessage(LocalizedStrings.GEMFIRE_CACHE_SECURITY_MISCONFIGURATION.toLocalizedString());
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/security/PeerAuthenticatorDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/PeerAuthenticatorDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/PeerAuthenticatorDUnitTest.java
index 90cc6f1..a7752ae 100644
--- a/geode-core/src/test/java/org/apache/geode/security/PeerAuthenticatorDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/PeerAuthenticatorDUnitTest.java
@@ -16,10 +16,13 @@
 package org.apache.geode.security;
 
 import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Host.getHost;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
 import java.util.Properties;
 
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
+import org.apache.geode.test.dunit.rules.Member;
 import org.apache.geode.test.dunit.rules.ServerStarterRule;
 import org.junit.Before;
 import org.junit.Rule;
@@ -29,7 +32,6 @@ import org.junit.experimental.categories.Category;
 import org.apache.geode.security.templates.DummyAuthenticator;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.SecurityTest;
 
@@ -42,23 +44,23 @@ public class PeerAuthenticatorDUnitTest extends JUnit4DistributedTestCase {
   public void before() throws Exception {
     Properties props = new Properties();
     props.setProperty(SECURITY_PEER_AUTHENTICATOR, DummyAuthenticator.class.getName());
-    lsRule.getLocatorVM(0, props);
+    lsRule.startLocatorVM(0, props);
   }
 
   @Test
   public void testPeerAuthenticator() throws Exception {
 
-    int locatorPort = lsRule.getPort(0);
+    int locatorPort = lsRule.getMember(0).getPort();
     Properties server1Props = new Properties();
     server1Props.setProperty("security-username", "user");
     server1Props.setProperty("security-password", "user");
-    lsRule.getServerVM(1, server1Props, locatorPort);
+    lsRule.startServerVM(1, server1Props, locatorPort);
 
 
     Properties server2Props = new Properties();
     server2Props.setProperty("security-username", "bogus");
     server2Props.setProperty("security-password", "user");
-    VM server2 = lsRule.getNodeVM(2);
+    VM server2 = getHost(0).getVM(2);
 
     server2.invoke(() -> {
       ServerStarterRule serverStarter = new ServerStarterRule(server2Props);

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/security/PeerSecurityWithEmbeddedLocatorDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/PeerSecurityWithEmbeddedLocatorDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/PeerSecurityWithEmbeddedLocatorDUnitTest.java
index d69e379..66c5be6 100644
--- a/geode-core/src/test/java/org/apache/geode/security/PeerSecurityWithEmbeddedLocatorDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/PeerSecurityWithEmbeddedLocatorDUnitTest.java
@@ -16,10 +16,13 @@
 package org.apache.geode.security;
 
 import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Host.getHost;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
 import java.util.Properties;
 
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -28,7 +31,6 @@ import org.apache.geode.internal.AvailablePortHelper;
 import org.apache.geode.security.templates.DummyAuthenticator;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.apache.geode.test.dunit.rules.ServerStarterRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.SecurityTest;
@@ -47,19 +49,19 @@ public class PeerSecurityWithEmbeddedLocatorDUnitTest extends JUnit4DistributedT
     Properties server0Props = new Properties();
     server0Props.setProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName());
     server0Props.setProperty("start-locator", "localhost[" + locatorPort + "]");
-    lsRule.getServerVM(0, server0Props);
+    lsRule.startServerVM(0, server0Props);
 
 
     Properties server1Props = new Properties();
     server1Props.setProperty("security-username", "cluster");
     server1Props.setProperty("security-password", "cluster");
-    lsRule.getServerVM(1, server1Props, locatorPort);
+    lsRule.startServerVM(1, server1Props, locatorPort);
 
     Properties server2Props = new Properties();
     server2Props.setProperty("security-username", "user");
     server2Props.setProperty("security-password", "wrongPwd");
 
-    VM server2 = lsRule.getNodeVM(2);
+    VM server2 = getHost(0).getVM(2);
     server2.invoke(() -> {
       ServerStarterRule serverStarter = new ServerStarterRule(server2Props);
       assertThatThrownBy(() -> serverStarter.startServer(locatorPort))
@@ -68,6 +70,8 @@ public class PeerSecurityWithEmbeddedLocatorDUnitTest extends JUnit4DistributedT
     });
   }
 
+
+
   @Test
   public void testPeerAuthenticator() throws Exception {
     int locatorPort = AvailablePortHelper.getRandomAvailableTCPPort();
@@ -75,19 +79,19 @@ public class PeerSecurityWithEmbeddedLocatorDUnitTest extends JUnit4DistributedT
     Properties server0Props = new Properties();
     server0Props.setProperty(SECURITY_PEER_AUTHENTICATOR, DummyAuthenticator.class.getName());
     server0Props.setProperty("start-locator", "localhost[" + locatorPort + "]");
-    lsRule.getServerVM(0, server0Props);
+    lsRule.startServerVM(0, server0Props);
 
 
     Properties server1Props = new Properties();
     server1Props.setProperty("security-username", "user");
     server1Props.setProperty("security-password", "user");
-    lsRule.getServerVM(1, server1Props, locatorPort);
+    lsRule.startServerVM(1, server1Props, locatorPort);
 
     Properties server2Props = new Properties();
     server2Props.setProperty("security-username", "bogus");
     server2Props.setProperty("security-password", "user");
 
-    VM server2 = lsRule.getNodeVM(2);
+    VM server2 = getHost(0).getVM(2);
     server2.invoke(() -> {
       ServerStarterRule serverStarter = new ServerStarterRule(server2Props);
       assertThatThrownBy(() -> serverStarter.startServer(locatorPort))

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
index 220449d..cd6518e 100644
--- a/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
@@ -34,6 +34,7 @@ import org.apache.geode.test.dunit.rules.ServerStarterRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.SecurityTest;
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -58,7 +59,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
     props.setProperty(JMX_MANAGER_START, "false");
     props.setProperty(JMX_MANAGER_PORT, 0 + "");
     props.setProperty(SECURITY_POST_PROCESSOR, PDXPostProcessor.class.getName());
-    lsRule.getLocatorVM(0, props);
+    lsRule.startLocatorVM(0, props);
   }
 
   @Test
@@ -71,7 +72,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
 
     // initial security properties should only contain initial set of values
     ServerStarterRule serverStarter = new ServerStarterRule(props);
-    serverStarter.startServer(lsRule.getPort(0));
+    serverStarter.startServer(lsRule.getMember(0).getPort());
     DistributedSystem ds = serverStarter.cache.getDistributedSystem();
 
     // after cache is created, we got the security props passed in by cluster config
@@ -93,7 +94,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
 
     // initial security properties should only contain initial set of values
     ServerStarterRule serverStarter = new ServerStarterRule(props);
-    serverStarter.startServer(lsRule.getPort(0));
+    serverStarter.startServer(lsRule.getMember(0).getPort());
     DistributedSystem ds = serverStarter.cache.getDistributedSystem();
 
     // after cache is created, we got the security props passed in by cluster config
@@ -115,7 +116,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
     // initial security properties should only contain initial set of values
     ServerStarterRule serverStarter = new ServerStarterRule(props);
 
-    assertThatThrownBy(() -> serverStarter.startServer(lsRule.getPort(0)))
+    assertThatThrownBy(() -> serverStarter.startServer(lsRule.getMember(0).getPort()))
         .isInstanceOf(GemFireConfigException.class)
         .hasMessage(LocalizedStrings.GEMFIRE_CACHE_SECURITY_MISCONFIGURATION.toLocalizedString());
 
@@ -134,7 +135,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
     // initial security properties should only contain initial set of values
     ServerStarterRule serverStarter = new ServerStarterRule(props);
 
-    assertThatThrownBy(() -> serverStarter.startServer(lsRule.getPort(0)))
+    assertThatThrownBy(() -> serverStarter.startServer(lsRule.getMember(0).getPort()))
         .isInstanceOf(GemFireConfigException.class)
         .hasMessage(LocalizedStrings.GEMFIRE_CACHE_SECURITY_MISCONFIGURATION.toLocalizedString());
 
@@ -152,7 +153,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
 
     ServerStarterRule serverStarter = new ServerStarterRule(props);
 
-    assertThatThrownBy(() -> serverStarter.startServer(lsRule.getPort(0)))
+    assertThatThrownBy(() -> serverStarter.startServer(lsRule.getMember(0).getPort()))
         .isInstanceOf(GemFireConfigException.class)
         .hasMessage(LocalizedStrings.GEMFIRE_CACHE_SECURITY_MISCONFIGURATION_2.toLocalizedString());
 

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/security/SecurityWithoutClusterConfigDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/SecurityWithoutClusterConfigDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/SecurityWithoutClusterConfigDUnitTest.java
index 17b1031..72654cb 100644
--- a/geode-core/src/test/java/org/apache/geode/security/SecurityWithoutClusterConfigDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/SecurityWithoutClusterConfigDUnitTest.java
@@ -20,7 +20,9 @@ import static org.junit.Assert.*;
 
 import java.util.Properties;
 
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -29,7 +31,6 @@ import org.apache.geode.distributed.DistributedSystem;
 import org.apache.geode.internal.i18n.LocalizedStrings;
 import org.apache.geode.test.dunit.IgnoredException;
 import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.apache.geode.test.dunit.rules.ServerStarterRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.SecurityTest;
@@ -51,7 +52,7 @@ public class SecurityWithoutClusterConfigDUnitTest extends JUnit4DistributedTest
     props.setProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName());
     props.setProperty(SECURITY_POST_PROCESSOR, PDXPostProcessor.class.getName());
     props.setProperty(ENABLE_CLUSTER_CONFIGURATION, "false");
-    lsRule.getLocatorVM(0, props);
+    lsRule.startLocatorVM(0, props);
   }
 
   @Test
@@ -69,7 +70,7 @@ public class SecurityWithoutClusterConfigDUnitTest extends JUnit4DistributedTest
 
     // initial security properties should only contain initial set of values
     ServerStarterRule serverStarter = new ServerStarterRule(props);
-    serverStarter.startServer(lsRule.getPort(0));
+    serverStarter.startServer(lsRule.getMember(0).getPort());
     DistributedSystem ds = serverStarter.cache.getDistributedSystem();
     assertEquals(3, ds.getSecurityProperties().size());
 

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/security/StartServerAuthorizationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/StartServerAuthorizationTest.java b/geode-core/src/test/java/org/apache/geode/security/StartServerAuthorizationTest.java
index dfa0f3d..24d0db5 100644
--- a/geode-core/src/test/java/org/apache/geode/security/StartServerAuthorizationTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/StartServerAuthorizationTest.java
@@ -15,22 +15,23 @@
 
 package org.apache.geode.security;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.assertj.core.api.Assertions.*;
-
-import java.util.Properties;
+import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
+import static org.apache.geode.test.dunit.Host.getHost;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.apache.geode.test.dunit.rules.ServerStarterRule;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.SecurityTest;
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.SecurityTest;
+import java.util.Properties;
 
 @Category({DistributedTest.class, SecurityTest.class})
 public class StartServerAuthorizationTest extends JUnit4DistributedTestCase {
@@ -42,7 +43,7 @@ public class StartServerAuthorizationTest extends JUnit4DistributedTestCase {
   public void before() throws Exception {
     Properties props = new Properties();
     props.setProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName());
-    lsRule.getLocatorVM(0, props);
+    lsRule.startLocatorVM(0, props);
   }
 
   @Test
@@ -52,10 +53,10 @@ public class StartServerAuthorizationTest extends JUnit4DistributedTestCase {
     props.setProperty("security-username", "user");
     props.setProperty("security-password", "wrongPswd");
 
-    VM server = lsRule.getNodeVM(1);
+    VM server = getHost(0).getVM(1);
     server.invoke(() -> {
       ServerStarterRule serverStarter = new ServerStarterRule(props);
-      assertThatThrownBy(() -> serverStarter.startServer(lsRule.getPort(0)))
+      assertThatThrownBy(() -> serverStarter.startServer(lsRule.getMember(0).getPort()))
           .isInstanceOf(GemFireSecurityException.class).hasMessageContaining(
               "Security check failed. Authentication error. Please check your credentials");
     });
@@ -69,15 +70,13 @@ public class StartServerAuthorizationTest extends JUnit4DistributedTestCase {
     props.setProperty("security-username", "user");
     props.setProperty("security-password", "user");
 
-    VM server = lsRule.getNodeVM(1);
+    VM server = getHost(0).getVM(1);
     server.invoke(() -> {
       ServerStarterRule serverStarter = new ServerStarterRule(props);
-      assertThatThrownBy(() -> serverStarter.startServer(lsRule.getPort(0)))
+      assertThatThrownBy(() -> serverStarter.startServer(lsRule.getMember(0).getPort()))
           .isInstanceOf(GemFireSecurityException.class)
           .hasMessageContaining("user not authorized for CLUSTER:MANAGE");
     });
-
-
   }
 
   @Test
@@ -88,7 +87,7 @@ public class StartServerAuthorizationTest extends JUnit4DistributedTestCase {
     props.setProperty("security-username", "cluster");
     props.setProperty("security-password", "cluster");
 
-    lsRule.getServerVM(1, props);
+    lsRule.startServerVM(1, props);
   }
 
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java
index 6053e1e..c56f7ab 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java
@@ -11,6 +11,7 @@
  * 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;
@@ -21,57 +22,72 @@ import static org.apache.geode.test.dunit.Host.getHost;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.Invoke;
 import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.rules.ExternalResource;
+import org.junit.rules.TemporaryFolder;
 
+import java.io.File;
 import java.io.IOException;
 import java.io.Serializable;
 import java.util.Properties;
 
 
 /**
- * this rule can help you start up locator/server in different VMs you can multiple locators/servers
- * combination
+ * A rule to help you start locators and servers inside of a
+ * <a href="https://cwiki.apache.org/confluence/display/GEODE/Distributed-Unit-Tests">DUnit
+ * test</a>. This rule will start Servers and Locators inside of the four remote {@link VM}s created
+ * by the DUnit framework.
  */
 public class LocatorServerStartupRule extends ExternalResource implements Serializable {
 
-  // these are only avaialbe in each VM
+  /**
+   * This is only available in each Locator/Server VM, not in the controller (test) VM.
+   */
   public static ServerStarterRule serverStarter;
+
+  /**
+   * This is only available in each Locator/Server VM, not in the controller (test) VM.
+   */
   public static LocatorStarterRule locatorStarter;
-  public int[] ports = new int[4];
-  private Host host = getHost(0);
+
+  private TemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
+  private Member[] members;
 
   @Before
-  public void before() {
-    after();
+  public void before() throws IOException {
+    temporaryFolder.create();
+    Invoke.invokeInEveryVM("Stop each VM", this::stop);
+    members = new Member[4];
   }
 
   @After
   public void after() {
-    stop();
-    Invoke.invokeInEveryVM("Stop each VM", () -> stop());
+    temporaryFolder.delete();
+    Invoke.invokeInEveryVM("Stop each VM", this::stop);
   }
 
   /**
-   * Returns getHost(0).getVM(0) as a locator instance with the given configuration properties.
-   * 
-   * @param locatorProperties
+   * Starts a locator instance with the given configuration properties inside
+   * {@code getHost(0).getVM(index)}.
    *
    * @return VM locator vm
-   *
-   * @throws IOException
    */
-  public VM getLocatorVM(int index, Properties locatorProperties) throws IOException {
-    VM locatorVM = host.getVM(index);
-    locatorProperties.setProperty(NAME, "locator-" + index);
+  public Member startLocatorVM(int index, Properties locatorProperties) throws IOException {
+    String name = "locator-" + index;
+    locatorProperties.setProperty(NAME, name);
+    File workingDir = createWorkingDirForMember(name);
+
+    VM locatorVM = getHost(0).getVM(index);
     int locatorPort = locatorVM.invoke(() -> {
+      System.setProperty("user.dir", workingDir.getCanonicalPath());
       locatorStarter = new LocatorStarterRule(locatorProperties);
       locatorStarter.startLocator();
       return locatorStarter.locator.getPort();
     });
-    ports[index] = locatorPort;
-    return locatorVM;
+    members[index] = new Member(locatorVM, locatorPort, workingDir);
+    return members[index];
   }
 
   /**
@@ -79,48 +95,41 @@ public class LocatorServerStartupRule extends ExternalResource implements Serial
    * 
    * @return VM node vm
    */
-
-  public VM getServerVM(int index, Properties properties) {
-    return getServerVM(index, properties, 0);
+  public Member startServerVM(int index, Properties properties) throws IOException {
+    return startServerVM(index, properties, 0);
   }
 
   /**
-   * starts a cache server that connect to the locator running at the given port.
-   * 
-   * @param index
-   * @param properties
-   * @param locatorPort
-   * @return
+   * Starts a cache server that connect to the locator running at the given port.
    */
-  public VM getServerVM(int index, Properties properties, int locatorPort) {
-    VM nodeVM = getNodeVM(index);
-    properties.setProperty(NAME, "server-" + index);
-    int port = nodeVM.invoke(() -> {
+  public Member startServerVM(int index, Properties properties, int locatorPort)
+      throws IOException {
+    String name = "server-" + index;
+    properties.setProperty(NAME, name);
+    File workingDir = createWorkingDirForMember(name);
+
+    VM serverVM = getHost(0).getVM(index);
+    int port = serverVM.invoke(() -> {
+      System.setProperty("user.dir", workingDir.getCanonicalPath());
       serverStarter = new ServerStarterRule(properties);
       serverStarter.startServer(locatorPort);
       return serverStarter.server.getPort();
     });
-    ports[index] = port;
-    return nodeVM;
+    members[index] = new Member(serverVM, port, workingDir);
+    return members[index];
   }
 
-
-
   /**
-   * this will simply returns the node
-   * 
-   * @param index
-   * @return
+   * Returns the {@link Member} running inside the VM with the specified {@code index}
    */
-  public VM getNodeVM(int index) {
-    return host.getVM(index);
+  public Member getMember(int index) {
+    return members[index];
   }
 
-  public int getPort(int index) {
-    return ports[index];
+  public TemporaryFolder getRootFolder() {
+    return temporaryFolder;
   }
 
-
   public final void stop() {
     if (serverStarter != null) {
       serverStarter.after();
@@ -130,4 +139,13 @@ public class LocatorServerStartupRule extends ExternalResource implements Serial
     }
   }
 
+  private File createWorkingDirForMember(String dirName) throws IOException {
+    File workingDir = new File(temporaryFolder.getRoot(), dirName);
+    if (!workingDir.exists()) {
+      temporaryFolder.newFolder(dirName);
+    }
+
+    return workingDir;
+  }
+
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorStarterRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorStarterRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorStarterRule.java
index 3329a40..6fc0d03 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorStarterRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorStarterRule.java
@@ -33,11 +33,14 @@ import java.util.concurrent.TimeUnit;
 /**
  * This is a rule to start up a locator in your current VM. It's useful for your Integration Tests.
  *
- * If you need a rule to start a server/locator in different VM for Distribution tests, You should
- * use LocatorServerStartupRule
+ * If you need a rule to start a server/locator in different VMs for Distributed tests, You should
+ * use {@link LocatorServerStartupRule}.
  *
- * You may choose to use this class not as a rule or use it in your own rule, (see
- * LocatorServerStartupRule) you will need to call startLocator() and after() manually in that case.
+ * <p>
+ * You may choose to use this class not as a rule or use it in your own rule (see
+ * {@link LocatorServerStartupRule}), in which case you will need to call startLocator() and after()
+ * manually.
+ * </p>
  */
 
 public class LocatorStarterRule extends ExternalResource implements Serializable {

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/test/dunit/rules/Member.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/Member.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/Member.java
new file mode 100644
index 0000000..10b6743
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/Member.java
@@ -0,0 +1,62 @@
+/*
+ * 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.dunit.SerializableRunnableIF;
+import org.apache.geode.test.dunit.VM;
+
+import java.io.File;
+import java.io.Serializable;
+
+/**
+ * A server or locator inside a DUnit {@link VM}.
+ */
+public class Member implements Serializable {
+  private VM vm;
+  private int port;
+  private File workingDir;
+
+  public Member(VM vm, int port, File workingDir) {
+    this.vm = vm;
+    this.port = port;
+    this.workingDir = workingDir;
+  }
+
+  /**
+   * The VM object is an RMI stub which lets us execute code in the JVM of this member.
+   * 
+   * @return the {@link VM}
+   */
+  public VM getVM() {
+    return vm;
+  }
+
+  public int getPort() {
+    return port;
+  }
+
+  public File getWorkingDir() {
+    return workingDir;
+  }
+
+  /**
+   * Invokes {@code runnable.run()} in the {@code VM} of this member.
+   */
+  public void invoke(final SerializableRunnableIF runnable) {
+    this.vm.invoke(runnable);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ServerStarterRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ServerStarterRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ServerStarterRule.java
index 8da0778..c94185a 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ServerStarterRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ServerStarterRule.java
@@ -25,6 +25,7 @@ import static org.apache.geode.distributed.ConfigurationProperties.NAME;
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.server.CacheServer;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.junit.rules.ExternalResource;
 
 import java.io.Serializable;
@@ -34,11 +35,13 @@ import java.util.Properties;
 /**
  * This is a rule to start up a server in your current VM. It's useful for your Integration Tests.
  *
- * If you need a rule to start a server/locator in different VM for Distribution tests, You should
- * use LocatorServerStartupRule
- *
- * You may choose to use this class not as a rule or use it in your own rule, (see
- * LocatorServerStartupRule) you will need to call startServer and after() manually in that case.
+ * If you need a rule to start a server/locator in different VMs for Distributed tests, You should
+ * use {@link LocatorServerStartupRule}.
+ * <p>
+ * You may choose to use this class not as a rule or use it in your own rule (see
+ * {@link LocatorServerStartupRule}), in which case you will need to call startLocator() and after()
+ * manually.
+ * </p>
  */
 public class ServerStarterRule extends ExternalResource implements Serializable {
 
@@ -66,10 +69,12 @@ public class ServerStarterRule extends ExternalResource implements Serializable
     if (!properties.containsKey(NAME)) {
       properties.setProperty(NAME, this.getClass().getName());
     }
-    if (locatorPort > 0) {
-      properties.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
-    } else {
-      properties.setProperty(LOCATORS, "");
+    if (!properties.containsKey(LOCATORS)) {
+      if (locatorPort > 0) {
+        properties.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
+      } else {
+        properties.setProperty(LOCATORS, "");
+      }
     }
     if (properties.containsKey(JMX_MANAGER_PORT)) {
       int jmxPort = Integer.parseInt(properties.getProperty(JMX_MANAGER_PORT));
@@ -84,7 +89,6 @@ public class ServerStarterRule extends ExternalResource implements Serializable
     CacheFactory cf = new CacheFactory(properties);
     cf.setPdxReadSerialized(pdxPersistent);
     cf.setPdxPersistent(pdxPersistent);
-
     cache = cf.create();
     server = cache.addCacheServer();
     server.setPort(0);
@@ -102,9 +106,13 @@ public class ServerStarterRule extends ExternalResource implements Serializable
 
   @Override
   public void after() {
-    if (cache != null)
+    if (cache != null) {
       cache.close();
-    if (server != null)
+      cache = null;
+    }
+    if (server != null) {
       server.stop();
+      server = null;
+    }
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-core/src/test/resources/org/apache/geode/management/internal/configuration/cluster_config.zip
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/org/apache/geode/management/internal/configuration/cluster_config.zip b/geode-core/src/test/resources/org/apache/geode/management/internal/configuration/cluster_config.zip
new file mode 100644
index 0000000..37cacbf
Binary files /dev/null and b/geode-core/src/test/resources/org/apache/geode/management/internal/configuration/cluster_config.zip differ

http://git-wip-us.apache.org/repos/asf/geode/blob/adfd41f4/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/configuration/LuceneClusterConfigurationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/configuration/LuceneClusterConfigurationDUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/configuration/LuceneClusterConfigurationDUnitTest.java
index 02b7fe4..0b0e936 100755
--- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/configuration/LuceneClusterConfigurationDUnitTest.java
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/configuration/LuceneClusterConfigurationDUnitTest.java
@@ -26,6 +26,8 @@ import java.util.Arrays;
 import java.util.Map;
 import java.util.Properties;
 
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
+import org.apache.geode.test.dunit.rules.Member;
 import org.apache.lucene.analysis.Analyzer;
 import org.junit.Rule;
 import org.junit.Test;
@@ -45,7 +47,6 @@ import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 
@@ -59,8 +60,8 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
 
   @Test
   public void indexGetsCreatedUsingClusterConfiguration() throws Exception {
-    VM locator = startLocatorWithClusterConfigurationEnabled();
-    VM vm1 = startNodeUsingClusterConfiguration(1, false);
+    Member locator = startLocatorWithClusterConfigurationEnabled();
+    Member vm1 = startNodeUsingClusterConfiguration(1, false);
 
     // Connect Gfsh to locator.
     createAndConnectGfshToLocator();
@@ -72,7 +73,7 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
 
     // Start vm2. This should have lucene index created using cluster
     // configuration.
-    VM vm2 = startNodeUsingClusterConfiguration(2, false);
+    Member vm2 = startNodeUsingClusterConfiguration(2, false);
     vm2.invoke(() -> {
       LuceneService luceneService = LuceneServiceProvider.get(ls.serverStarter.cache);
       final LuceneIndex index = luceneService.getIndex(INDEX_NAME, REGION_NAME);
@@ -83,8 +84,8 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
 
   @Test
   public void indexWithAnalyzerGetsCreatedUsingClusterConfiguration() throws Exception {
-    VM locator = startLocatorWithClusterConfigurationEnabled();
-    VM vm1 = startNodeUsingClusterConfiguration(1, false);
+    Member locator = startLocatorWithClusterConfigurationEnabled();
+    Member vm1 = startNodeUsingClusterConfiguration(1, false);
 
     // Connect Gfsh to locator.
     createAndConnectGfshToLocator();
@@ -97,7 +98,7 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
 
     // Start vm2. This should have lucene index created using cluster
     // configuration.
-    VM vm2 = startNodeUsingClusterConfiguration(2, false);
+    Member vm2 = startNodeUsingClusterConfiguration(2, false);
     vm2.invoke(() -> {
       LuceneService luceneService = LuceneServiceProvider.get(ls.serverStarter.cache);
       final LuceneIndex index = luceneService.getIndex(INDEX_NAME, REGION_NAME);
@@ -115,14 +116,14 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
 
   @Test
   public void indexGetsCreatedOnGroupOfNodes() throws Exception {
-    VM locator = startLocatorWithClusterConfigurationEnabled();
+    Member locator = startLocatorWithClusterConfigurationEnabled();
 
     // Start vm1, vm2 in group
-    VM vm1 = startNodeUsingClusterConfiguration(1, true);
-    VM vm2 = startNodeUsingClusterConfiguration(2, true);
+    Member vm1 = startNodeUsingClusterConfiguration(1, true);
+    Member vm2 = startNodeUsingClusterConfiguration(2, true);
 
     // Start vm3 outside the group. The Lucene index should not be present here.
-    VM vm3 = startNodeUsingClusterConfiguration(3, true);
+    Member vm3 = startNodeUsingClusterConfiguration(3, true);
 
     // Connect Gfsh to locator.
     createAndConnectGfshToLocator();
@@ -151,14 +152,14 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
 
   @Test
   public void indexNotCreatedOnNodeOutSideTheGroup() throws Exception {
-    VM locator = startLocatorWithClusterConfigurationEnabled();
+    Member locator = startLocatorWithClusterConfigurationEnabled();
 
     // Start vm1, vm2 in group
-    VM vm1 = startNodeUsingClusterConfiguration(1, true);
-    VM vm2 = startNodeUsingClusterConfiguration(2, true);
+    Member vm1 = startNodeUsingClusterConfiguration(1, true);
+    Member vm2 = startNodeUsingClusterConfiguration(2, true);
 
     // Start vm3 outside the group. The Lucene index should not be present here.
-    VM vm3 = startNodeUsingClusterConfiguration(3, false);
+    Member vm3 = startNodeUsingClusterConfiguration(3, false);
 
     // Connect Gfsh to locator.
     createAndConnectGfshToLocator();
@@ -187,10 +188,10 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
 
   @Test
   public void indexAreCreatedInValidGroupOfNodesJoiningLater() throws Exception {
-    VM locator = startLocatorWithClusterConfigurationEnabled();
+    Member locator = startLocatorWithClusterConfigurationEnabled();
 
     // Start vm1 in group
-    VM vm1 = startNodeUsingClusterConfiguration(1, true);
+    Member vm1 = startNodeUsingClusterConfiguration(1, true);
     // Connect Gfsh to locator.
     createAndConnectGfshToLocator();
 
@@ -200,10 +201,10 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
     createRegionUsingGfsh(REGION_NAME, RegionShortcut.PARTITION, groupName);
 
     // Start vm2 in group
-    VM vm2 = startNodeUsingClusterConfiguration(2, true);
+    Member vm2 = startNodeUsingClusterConfiguration(2, true);
 
     // Start vm3 outside the group. The Lucene index should not be present here.
-    VM vm3 = startNodeUsingClusterConfiguration(3, false);
+    Member vm3 = startNodeUsingClusterConfiguration(3, false);
 
     // VM2 should have lucene index created using gfsh execution
     vm2.invoke(() -> {
@@ -226,7 +227,8 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
     connect(jmxHost, jmxPort, httpPort, gfsh);
   }
 
-  private VM startNodeUsingClusterConfiguration(int vmIndex, boolean addGroup) throws Exception {
+  private Member startNodeUsingClusterConfiguration(int vmIndex, boolean addGroup)
+      throws Exception {
     File dir = this.temporaryFolder.newFolder();
     Properties nodeProperties = new Properties();
     nodeProperties.setProperty(USE_CLUSTER_CONFIGURATION, "true");
@@ -234,10 +236,10 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
     if (addGroup) {
       nodeProperties.setProperty(GROUPS, groupName);
     }
-    return ls.getServerVM(vmIndex, nodeProperties, ls.getPort(0));
+    return ls.startServerVM(vmIndex, nodeProperties, ls.getMember(0).getPort());
   }
 
-  private VM startLocatorWithClusterConfigurationEnabled() throws Exception {
+  private Member startLocatorWithClusterConfigurationEnabled() throws Exception {
     try {
       jmxHost = InetAddress.getLocalHost().getHostName();
     } catch (UnknownHostException ignore) {
@@ -258,7 +260,7 @@ public class LuceneClusterConfigurationDUnitTest extends CliCommandTestBase {
     locatorProps.setProperty(JMX_MANAGER_PORT, String.valueOf(jmxPort));
     locatorProps.setProperty(HTTP_SERVICE_PORT, String.valueOf(httpPort));
     locatorProps.setProperty(CLUSTER_CONFIGURATION_DIR, dir.getCanonicalPath());
-    return ls.getLocatorVM(0, locatorProps);
+    return ls.startLocatorVM(0, locatorProps);
   }
 
   private void createLuceneIndexUsingGfsh(boolean addGroup) throws Exception {


[19/50] [abbrv] geode git commit: GEODE-1984: Fix Issue Make GatewaySender destroy a public API

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateGatewaySenderDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateGatewaySenderDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateGatewaySenderDUnitTest.java
deleted file mode 100644
index db9aa91..0000000
--- a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateGatewaySenderDUnitTest.java
+++ /dev/null
@@ -1,663 +0,0 @@
-/*
- * 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.cache.wan.wancommand;
-
-import org.apache.geode.cache.wan.GatewaySender;
-import org.apache.geode.cache.wan.GatewaySender.OrderPolicy;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.wan.GatewaySenderException;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResult;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.test.dunit.IgnoredException;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-
-@Category(DistributedTest.class)
-public class WanCommandCreateGatewaySenderDUnitTest extends WANCommandTestBase {
-
-  private static final long serialVersionUID = 1L;
-
-  private CommandResult executeCommandWithIgnoredExceptions(String command) {
-    final IgnoredException exln = IgnoredException.addIgnoredException("Could not connect");
-    try {
-      CommandResult commandResult = executeCommand(command);
-      return commandResult;
-    } finally {
-      exln.remove();
-    }
-  }
-
-
-  /**
-   * GatewaySender with all default attributes
-   */
-  @Test
-  public void testCreateGatewaySenderWithDefault() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCache(punePort));
-    vm4.invoke(() -> createCache(punePort));
-    vm5.invoke(() -> createCache(punePort));
-
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderState("ln", true, false));
-    vm4.invoke(() -> verifySenderState("ln", true, false));
-    vm5.invoke(() -> verifySenderState("ln", true, false));
-  }
-
-  /**
-   * GatewaySender with given attribute values
-   */
-  @Test
-  public void testCreateGatewaySender() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCache(punePort));
-    vm4.invoke(() -> createCache(punePort));
-    vm5.invoke(() -> createCache(punePort));
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderState("ln", false, false));
-    vm4.invoke(() -> verifySenderState("ln", false, false));
-    vm5.invoke(() -> verifySenderState("ln", false, false));
-
-    vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
-    vm4.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
-    vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
-  }
-
-  /**
-   * GatewaySender with given attribute values. Error scenario where dispatcher threads is set to
-   * more than 1 and no order policy provided.
-   */
-  @Test
-  public void testCreateGatewaySender_Error() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCache(punePort));
-    vm4.invoke(() -> createCache(punePort));
-    vm5.invoke(() -> createCache(punePort));
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation should fail", status.get(i).indexOf("ERROR:") != -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-  }
-
-  /**
-   * GatewaySender with given attribute values and event filters.
-   */
-  @Test
-  public void testCreateGatewaySenderWithGatewayEventFilters() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCache(punePort));
-    vm4.invoke(() -> createCache(punePort));
-    vm5.invoke(() -> createCache(punePort));
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__GATEWAYEVENTFILTER
-        + "=org.apache.geode.cache30.MyGatewayEventFilter1,org.apache.geode.cache30.MyGatewayEventFilter2";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderState("ln", false, false));
-    vm4.invoke(() -> verifySenderState("ln", false, false));
-    vm5.invoke(() -> verifySenderState("ln", false, false));
-
-    List<String> eventFilters = new ArrayList<String>();
-    eventFilters.add("org.apache.geode.cache30.MyGatewayEventFilter1");
-    eventFilters.add("org.apache.geode.cache30.MyGatewayEventFilter2");
-    vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, eventFilters, null));
-    vm4.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, eventFilters, null));
-    vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, eventFilters, null));
-  }
-
-  /**
-   * GatewaySender with given attribute values and transport filters.
-   */
-  @Test
-  public void testCreateGatewaySenderWithGatewayTransportFilters() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCache(punePort));
-    vm4.invoke(() -> createCache(punePort));
-    vm5.invoke(() -> createCache(punePort));
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__GATEWAYTRANSPORTFILTER
-        + "=org.apache.geode.cache30.MyGatewayTransportFilter1";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderState("ln", false, false));
-    vm4.invoke(() -> verifySenderState("ln", false, false));
-    vm5.invoke(() -> verifySenderState("ln", false, false));
-
-    List<String> transportFilters = new ArrayList<String>();
-    transportFilters.add("org.apache.geode.cache30.MyGatewayTransportFilter1");
-    vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, transportFilters));
-    vm4.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, transportFilters));
-    vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, transportFilters));
-  }
-
-  /**
-   * GatewaySender with given attribute values on given member.
-   */
-  @Test
-  public void testCreateGatewaySender_OnMember() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCache(punePort));
-    vm4.invoke(() -> createCache(punePort));
-    vm5.invoke(() -> createCache(punePort));
-
-    final DistributedMember vm3Member = (DistributedMember) vm3.invoke(() -> getMember());
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__MEMBER + "=" + vm3Member.getId() + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(1, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderState("ln", false, false));
-
-    vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
-        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
-  }
-
-  /**
-   * GatewaySender with given attribute values on given group
-   */
-  @Test
-  public void testCreateGatewaySender_Group() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
-    vm4.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
-    vm5.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__GROUP + "=SenderGroup1" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(3, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderState("ln", true, false));
-    vm4.invoke(() -> verifySenderState("ln", true, false));
-    vm5.invoke(() -> verifySenderState("ln", true, false));
-  }
-
-  /**
-   * GatewaySender with given attribute values on given group. Only 2 of 3 members are part of the
-   * group.
-   */
-  @Test
-  public void testCreateGatewaySender_Group_Scenario2() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
-    vm4.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
-    vm5.invoke(() -> createCacheWithGroups(punePort, "SenderGroup2"));
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__GROUP + "=SenderGroup1" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(2, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderState("ln", true, false));
-    vm4.invoke(() -> verifySenderState("ln", true, false));
-  }
-
-  /**
-   * Parallel GatewaySender with given attribute values
-   */
-  @Test
-  public void testCreateParallelGatewaySender() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCache(punePort));
-    vm4.invoke(() -> createCache(punePort));
-    vm5.invoke(() -> createCache(punePort));
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100";
-    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-    if (cmdResult != null) {
-      String strCmdResult = commandResultToString(cmdResult);
-      getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-      List<String> status = resultData.retrieveAllValues("Status");
-      assertEquals(5, status.size());
-      for (int i = 0; i < status.size(); i++) {
-        assertTrue("GatewaySender creation failed with: " + status.get(i),
-            status.get(i).indexOf("ERROR:") == -1);
-      }
-    } else {
-      fail("testCreateGatewaySender failed as did not get CommandResult");
-    }
-
-    vm3.invoke(() -> verifySenderState("ln", false, false));
-    vm4.invoke(() -> verifySenderState("ln", false, false));
-    vm5.invoke(() -> verifySenderState("ln", false, false));
-
-    vm3.invoke(
-        () -> verifySenderAttributes("ln", 2, true, true, 1000, socketReadTimeout, true, 1000, 5000,
-            true, false, 1000, 100, GatewaySender.DEFAULT_DISPATCHER_THREADS, null, null, null));
-    vm4.invoke(
-        () -> verifySenderAttributes("ln", 2, true, true, 1000, socketReadTimeout, true, 1000, 5000,
-            true, false, 1000, 100, GatewaySender.DEFAULT_DISPATCHER_THREADS, null, null, null));
-    vm5.invoke(
-        () -> verifySenderAttributes("ln", 2, true, true, 1000, socketReadTimeout, true, 1000, 5000,
-            true, false, 1000, 100, GatewaySender.DEFAULT_DISPATCHER_THREADS, null, null, null));
-  }
-
-  /**
-   * Parallel GatewaySender with given attribute values. Provide dispatcherThreads as 2 which is not
-   * valid for Parallel sender.
-   */
-  @Test
-  public void testCreateParallelGatewaySender_Error() {
-
-    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
-
-    Properties props = getDistributedSystemProperties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
-    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
-    setUpJmxManagerOnVm0ThenConnect(props);
-
-    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
-
-    vm3.invoke(() -> createCache(punePort));
-    vm4.invoke(() -> createCache(punePort));
-    vm5.invoke(() -> createCache(punePort));
-
-    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
-    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
-        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
-        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
-    IgnoredException exp =
-        IgnoredException.addIgnoredException(GatewaySenderException.class.getName());
-    try {
-      CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
-      if (cmdResult != null) {
-        String strCmdResult = commandResultToString(cmdResult);
-        getLogWriter().info("testCreateGatewaySender stringResult : " + strCmdResult + ">>>>");
-        assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-        TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
-        List<String> status = resultData.retrieveAllValues("Status");
-        assertEquals(5, status.size());
-        for (int i = 0; i < status.size(); i++) {
-          assertTrue("GatewaySender creation should have failed",
-              status.get(i).indexOf("ERROR:") != -1);
-        }
-      } else {
-        fail("testCreateGatewaySender failed as did not get CommandResult");
-      }
-    } finally {
-      exp.remove();
-    }
-
-  }
-}


[10/50] [abbrv] geode git commit: GEODE-2179 - Checking for disconnected connection in GatewaySenderMBean

Posted by kl...@apache.org.
GEODE-2179 - Checking for disconnected connection in GatewaySenderMBean

Making sure that the mbean returns false for isConnected if the gateway
is not actually connected to the remote side.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 0494b31caf6f43cec85660fd8d939f2b1c6739c2
Parents: 1d34eeb
Author: Dan Smith <up...@apache.org>
Authored: Fri Dec 2 15:47:13 2016 -0800
Committer: Dan Smith <up...@apache.org>
Committed: Wed Dec 7 15:14:28 2016 -0800

----------------------------------------------------------------------
 .../wan/GatewaySenderEventRemoteDispatcher.java |  2 +-
 .../management/WANManagementDUnitTest.java      | 40 +++++++++++---------
 2 files changed, 24 insertions(+), 18 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/0494b31c/geode-wan/src/main/java/org/apache/geode/internal/cache/wan/GatewaySenderEventRemoteDispatcher.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/main/java/org/apache/geode/internal/cache/wan/GatewaySenderEventRemoteDispatcher.java b/geode-wan/src/main/java/org/apache/geode/internal/cache/wan/GatewaySenderEventRemoteDispatcher.java
index 16b1965..8da5613 100644
--- a/geode-wan/src/main/java/org/apache/geode/internal/cache/wan/GatewaySenderEventRemoteDispatcher.java
+++ b/geode-wan/src/main/java/org/apache/geode/internal/cache/wan/GatewaySenderEventRemoteDispatcher.java
@@ -802,7 +802,7 @@ public class GatewaySenderEventRemoteDispatcher implements GatewaySenderEventDis
 
   @Override
   public boolean isConnectedToRemote() {
-    return connection != null;
+    return connection != null && !connection.isDestroyed();
   }
 
   public void stop() {

http://git-wip-us.apache.org/repos/asf/geode/blob/0494b31c/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java
index 9a6cc10..3cc37eb 100644
--- a/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java
+++ b/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java
@@ -19,12 +19,14 @@ import org.junit.Test;
 
 import static org.junit.Assert.*;
 
+import com.jayway.awaitility.Awaitility;
 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.util.Map;
+import java.util.concurrent.TimeUnit;
 
 import javax.management.MBeanServer;
 import javax.management.ObjectName;
@@ -60,7 +62,17 @@ public class WANManagementDUnitTest extends ManagementTestBase {
   }
 
   @Test
-  public void testMBeanCallback() throws Exception {
+  public void testMBeanCallbackSerial() throws Exception {
+    testMBeanCallback(false);
+  }
+
+  @Test
+  public void testMBeanCallbackParallel() throws Exception {
+    testMBeanCallback(true);
+
+  }
+
+  public void testMBeanCallback(boolean parallel) throws Exception {
 
     VM nyLocator = getManagedNodeList().get(0);
     VM nyReceiver = getManagedNodeList().get(1);
@@ -103,10 +115,8 @@ public class WANManagementDUnitTest extends ManagementTestBase {
     puneSender.invoke(() -> WANTestBase.waitForSenderRunningState("pn"));
     managing.invoke(() -> WANTestBase.waitForSenderRunningState("pn"));
 
-
-
-    checkSenderMBean(puneSender, getTestMethodName() + "_PR");
-    checkSenderMBean(managing, getTestMethodName() + "_PR");
+    checkSenderMBean(puneSender, getTestMethodName() + "_PR", true);
+    checkSenderMBean(managing, getTestMethodName() + "_PR", true);
 
     checkReceiverMBean(nyReceiver);
 
@@ -119,6 +129,10 @@ public class WANManagementDUnitTest extends ManagementTestBase {
     checkProxySender(managing, puneMember);
     checkSenderNavigationAPIS(managing, puneMember);
 
+    nyReceiver.invoke(() -> WANTestBase.stopReceivers());
+
+    checkSenderMBean(puneSender, getTestMethodName() + "_PR", false);
+    checkSenderMBean(managing, getTestMethodName() + "_PR", false);
   }
 
   @Category(FlakyTest.class) // GEODE-1603
@@ -159,8 +173,7 @@ public class WANManagementDUnitTest extends ManagementTestBase {
     managing.invoke(() -> WANTestBase.createManagementCache(nyPort));
     startManagingNode(managing);
 
-
-    checkSenderMBean(puneSender, getTestMethodName() + "_PR");
+    checkSenderMBean(puneSender, getTestMethodName() + "_PR", true);
     checkReceiverMBean(nyReceiver);
 
     DistributedMember nyMember =
@@ -168,8 +181,6 @@ public class WANManagementDUnitTest extends ManagementTestBase {
 
     checkProxyReceiver(managing, nyMember);
     checkReceiverNavigationAPIS(managing, nyMember);
-
-
   }
 
 
@@ -187,19 +198,15 @@ public class WANManagementDUnitTest extends ManagementTestBase {
     Integer nyPort =
         (Integer) nyLocator.invoke(() -> WANTestBase.createFirstRemoteLocator(12, punePort));
 
-
-
     puneSender.invoke(() -> WANTestBase.createCache(punePort));
     managing.invoke(() -> WANTestBase.createManagementCache(punePort));
     startManagingNode(managing);
 
-
     puneSender.invoke(() -> WANTestBase.createAsyncEventQueue("pn", false, 100, 100, false, false,
         "puneSender", false));
     managing.invoke(() -> WANTestBase.createAsyncEventQueue("pn", false, 100, 100, false, false,
         "managing", false));
 
-
     puneSender.invoke(() -> WANTestBase
         .createReplicatedRegionWithAsyncEventQueue(getTestMethodName() + "_RR", "pn", false));
     managing.invoke(() -> WANTestBase
@@ -213,7 +220,6 @@ public class WANManagementDUnitTest extends ManagementTestBase {
     checkAsyncQueueMBean(puneSender);
     checkAsyncQueueMBean(managing);
 
-
     DistributedMember puneMember =
         (DistributedMember) puneSender.invoke(() -> WANManagementDUnitTest.getMember());
 
@@ -392,7 +398,6 @@ public class WANManagementDUnitTest extends ManagementTestBase {
   }
 
 
-
   /**
    * Checks whether a GatewayReceiverMBean is created or not
    * 
@@ -417,7 +422,7 @@ public class WANManagementDUnitTest extends ManagementTestBase {
    * @param vm reference to VM
    */
   @SuppressWarnings("serial")
-  protected void checkSenderMBean(final VM vm, final String regionPath) {
+  protected void checkSenderMBean(final VM vm, final String regionPath, boolean connected) {
     SerializableRunnable checkMBean = new SerializableRunnable("Check Sender MBean") {
       public void run() {
         Cache cache = GemFireCacheImpl.getInstance();
@@ -425,7 +430,8 @@ public class WANManagementDUnitTest extends ManagementTestBase {
 
         GatewaySenderMXBean bean = service.getLocalGatewaySenderMXBean("pn");
         assertNotNull(bean);
-        assertTrue(bean.isConnected());
+        Awaitility.await().atMost(1, TimeUnit.MINUTES)
+            .until(() -> assertEquals(connected, bean.isConnected()));
 
         ObjectName regionBeanName = service.getRegionMBeanName(
             cache.getDistributedSystem().getDistributedMember(), "/" + regionPath);


[15/50] [abbrv] geode git commit: GEODE-2190: add FlakyTest category to flaky test

Posted by kl...@apache.org.
GEODE-2190: add FlakyTest category to flaky test


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

Branch: refs/heads/feature/GEODE-1930
Commit: 2075ee348e221d662468ead4c18b56923d3d7329
Parents: ef74181
Author: Kirk Lund <kl...@apache.org>
Authored: Thu Dec 8 09:49:01 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Thu Dec 8 09:49:01 2016 -0800

----------------------------------------------------------------------
 .../cache/wan/parallel/ParallelWANPropagationDUnitTest.java         | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/2075ee34/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/parallel/ParallelWANPropagationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/parallel/ParallelWANPropagationDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/parallel/ParallelWANPropagationDUnitTest.java
index bbd65fe..6a190ef 100644
--- a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/parallel/ParallelWANPropagationDUnitTest.java
+++ b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/parallel/ParallelWANPropagationDUnitTest.java
@@ -285,6 +285,7 @@ public class ParallelWANPropagationDUnitTest extends WANTestBase {
    * 
    * @throws Exception
    */
+  @Category(FlakyTest.class)
   @Test
   public void testParallelPropagationWithLocalCacheClosedAndRebuilt() throws Exception {
     Integer lnPort = (Integer) vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1));


[12/50] [abbrv] geode git commit: GEODE-734: Remove txt file restriction when exporting stack traces

Posted by kl...@apache.org.
GEODE-734: Remove txt file restriction when exporting stack traces

Adding throws clause to signature instead of catching it in Test.

Separating test scenarios into multiple test cases. Creating files in
TemporaryFolder.

Applying spotless checks

Updated export stack-traces in controller. Removed compulsory file
option. If file is not provided then name is generated. Added one
boolean option fail-if-file-present, if true and file already exists
then command will fail.

Updated Offline help file.

Added test cases to verify new added options

Removed compulsory file option. If file is not provided then name is
generated. Added one boolean option fail-if-file-present, if true and
file already exists then command will fail.

Added message warning user about possible overwrite of file if already
present.

Added test to check if non txt extension file is allowed.

This closes #297


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

Branch: refs/heads/feature/GEODE-1930
Commit: 903135115a0466d86fa663e965ace3ff47eba6b4
Parents: 67dafd8
Author: Deepak Dixit <de...@gmail.com>
Authored: Sat Nov 26 19:11:52 2016 +0530
Committer: Kirk Lund <kl...@apache.org>
Committed: Thu Dec 8 08:44:52 2016 -0800

----------------------------------------------------------------------
 .../cli/commands/MiscellaneousCommands.java     |  50 +++++-
 .../internal/cli/i18n/CliStrings.java           |  10 +-
 .../MiscellaneousCommandsController.java        |  15 +-
 .../cli/commands/ShowStackTraceDUnitTest.java   | 158 ++++++++++++++++---
 .../cli/commands/golden-help-offline.properties |   9 +-
 5 files changed, 204 insertions(+), 38 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/90313511/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
index 9acdcf1..4ef710c 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
@@ -1023,22 +1023,31 @@ public class MiscellaneousCommands implements CommandMarker {
           optionContext = ConverterHint.ALL_MEMBER_IDNAME,
           help = CliStrings.EXPORT_STACKTRACE__GROUP) String group,
 
-      @CliOption(key = CliStrings.EXPORT_STACKTRACE__FILE, mandatory = true,
-          help = CliStrings.EXPORT_STACKTRACE__FILE__HELP) String fileName) {
+      @CliOption(key = CliStrings.EXPORT_STACKTRACE__FILE,
+          help = CliStrings.EXPORT_STACKTRACE__FILE__HELP) String fileName,
+
+      @CliOption(key = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT,
+          unspecifiedDefaultValue = "false",
+          help = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT__HELP) boolean failIfFilePresent) {
 
     Result result = null;
+    StringBuffer filePrefix = new StringBuffer("stacktrace");
     try {
+      if (fileName == null) {
+        fileName = filePrefix.append("_").append(System.currentTimeMillis()).toString();
+      }
+      final File outFile = new File(fileName);
+      if (outFile.exists() && failIfFilePresent) {
+        return ResultBuilder.createShellClientErrorResult(CliStrings.format(
+            CliStrings.EXPORT_STACKTRACE__ERROR__FILE__PRESENT, outFile.getCanonicalPath()));
+      }
+
       Cache cache = CacheFactory.getAnyInstance();
       GemFireCacheImpl gfeCacheImpl = (GemFireCacheImpl) cache;
       InternalDistributedSystem ads = gfeCacheImpl.getSystem();
 
       InfoResultData resultData = ResultBuilder.createInfoResultData();
 
-      if (!fileName.endsWith(".txt")) {
-        return ResultBuilder
-            .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENTION, ".txt"));
-      }
-
       Map<String, byte[]> dumps = new HashMap<String, byte[]>();
       Set<DistributedMember> targetMembers = null;
 
@@ -1074,6 +1083,33 @@ public class MiscellaneousCommands implements CommandMarker {
     return result;
   }
 
+  /**
+   * Interceptor used by gfsh to intercept execution of shutdownall.
+   */
+  public static class ExportStackTraceInterceptor extends AbstractCliAroundInterceptor {
+    @Override
+    public Result preExecution(GfshParseResult parseResult) {
+
+      Map<String, String> paramValueMap = parseResult.getParamValueStrings();
+      String fileName = paramValueMap.get(CliStrings.EXPORT_STACKTRACE__FILE);
+
+      Response response = readYesNo(
+          CliStrings.format(CliStrings.EXPORT_STACKTRACE_WARN_USER, fileName), Response.YES);
+      if (response == Response.NO) {
+        return ResultBuilder
+            .createShellClientAbortOperationResult(CliStrings.EXPORT_STACKTRACE_MSG_ABORTING);
+      } else {
+        // we dont to show any info result
+        return ResultBuilder.createInfoResult("");
+      }
+    }
+
+    @Override
+    public Result postExecution(GfshParseResult parseResult, Result commandResult) {
+      return commandResult;
+    }
+  }
+
   /***
    * Writes the Stack traces member-wise to a text file
    * 

http://git-wip-us.apache.org/repos/asf/geode/blob/90313511/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
index 9aaef4d..68dd438 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
@@ -1427,12 +1427,18 @@ public class CliStrings {
   public static final String EXPORT_STACKTRACE__FILE = "file";
   public static final String EXPORT_STACKTRACE__FILE__HELP =
       "Name of the file to which the stack traces will be written.";
+  public static final String EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT = "abort-if-file-exists";
+  public static final String EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT__HELP =
+      "Abort the command if already exists at locator directory";
   public static final String EXPORT_STACKTRACE__MEMBER__NOT__FOUND = "Member not found";
   public static final String EXPORT_STACKTRACE__SUCCESS = "stack-trace(s) exported to file: {0}";
   public static final String EXPORT_STACKTRACE__ERROR = "Error occured while showing stack-traces";
+  public static final String EXPORT_STACKTRACE__ERROR__FILE__PRESENT =
+      "Error occured while exporting stack-traces, file {0} already present";
   public static final String EXPORT_STACKTRACE__HOST = "On host : ";
-  public static final String EXPORT_STACKTRACE__INVALID_FILE_TYPE =
-      "Invalid file extension. File must be a text file (.txt)";
+  public static final String EXPORT_STACKTRACE_WARN_USER =
+      "If file {0} already present at locator directory it will be overwritten, do you want to continue?";
+  public static final String EXPORT_STACKTRACE_MSG_ABORTING = "Aborting export stack-traces";
 
   /* 'gc' command */
   public static final String GC = "gc";

http://git-wip-us.apache.org/repos/asf/geode/blob/90313511/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
index a0fc1e3..ac912c8 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
@@ -100,14 +100,18 @@ public class MiscellaneousCommandsController extends AbstractCommandsController
   @RequestMapping(method = RequestMethod.GET, value = "/stacktraces")
   @ResponseBody
   public String exportStackTraces(
-      @RequestParam(value = CliStrings.EXPORT_STACKTRACE__FILE) final String file,
+      @RequestParam(value = CliStrings.EXPORT_STACKTRACE__FILE, required = false) final String file,
       @RequestParam(value = CliStrings.EXPORT_STACKTRACE__GROUP,
           required = false) final String groupName,
       @RequestParam(value = CliStrings.EXPORT_STACKTRACE__MEMBER,
-          required = false) final String memberNameId) {
+          required = false) final String memberNameId,
+      @RequestParam(value = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT,
+          required = false) final boolean failIfFilePresent) {
     CommandStringBuilder command = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
 
-    command.addOption(CliStrings.EXPORT_STACKTRACE__FILE, decode(file));
+    if (hasValue(file)) {
+      command.addOption(CliStrings.EXPORT_STACKTRACE__FILE, decode(file));
+    }
 
     if (hasValue(groupName)) {
       command.addOption(CliStrings.EXPORT_STACKTRACE__GROUP, groupName);
@@ -117,6 +121,11 @@ public class MiscellaneousCommandsController extends AbstractCommandsController
       command.addOption(CliStrings.EXPORT_STACKTRACE__MEMBER, memberNameId);
     }
 
+    if (hasValue(failIfFilePresent)) {
+      command.addOption(CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT,
+          String.valueOf(failIfFilePresent));
+    }
+
     return processCommand(command.toString());
   }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/90313511/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
index f5d6cde..dda50f6 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
@@ -15,26 +15,27 @@
 package org.apache.geode.management.internal.cli.commands;
 
 import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Assert.*;
+import static org.apache.geode.test.dunit.LogWriterUtils.*;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Properties;
 
 import org.apache.geode.management.cli.Result.Status;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.json.GfJsonException;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Properties;
-
-import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
-import static org.apache.geode.test.dunit.Assert.assertFalse;
-import static org.apache.geode.test.dunit.Assert.assertTrue;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import org.junit.rules.TemporaryFolder;
 
 /***
  * DUnit test for 'show stack-trace' command
@@ -44,6 +45,9 @@ public class ShowStackTraceDUnitTest extends CliCommandTestBase {
 
   private static final long serialVersionUID = 1L;
 
+  @Rule
+  public TemporaryFolder workDirectory = new SerializableTemporaryFolder();
+
   private void createCache(Properties props) {
     getSystem(props);
     getCache();
@@ -90,9 +94,7 @@ public class ShowStackTraceDUnitTest extends CliCommandTestBase {
   public void testExportStacktrace() throws ClassNotFoundException, IOException {
     setupSystem();
 
-    File allStacktracesFile = new File("allStackTraces.txt");
-    allStacktracesFile.createNewFile();
-    allStacktracesFile.deleteOnExit();
+    File allStacktracesFile = workDirectory.newFile("allStackTraces.txt");
     CommandStringBuilder csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
     csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, allStacktracesFile.getCanonicalPath());
     String commandString = csb.toString();
@@ -101,9 +103,7 @@ public class ShowStackTraceDUnitTest extends CliCommandTestBase {
     getLogWriter().info("Output : \n" + commandResultToString(commandResult));
     assertTrue(commandResult.getStatus().equals(Status.OK));
 
-    File mgrStacktraceFile = new File("managerStacktrace.txt");
-    mgrStacktraceFile.createNewFile();
-    mgrStacktraceFile.deleteOnExit();
+    File mgrStacktraceFile = workDirectory.newFile("managerStacktrace.txt");
     csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
     csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, mgrStacktraceFile.getCanonicalPath());
     csb.addOption(CliStrings.EXPORT_STACKTRACE__MEMBER, "Manager");
@@ -113,9 +113,7 @@ public class ShowStackTraceDUnitTest extends CliCommandTestBase {
     getLogWriter().info("Output : \n" + commandResultToString(commandResult));
     assertTrue(commandResult.getStatus().equals(Status.OK));
 
-    File serverStacktraceFile = new File("serverStacktrace.txt");
-    serverStacktraceFile.createNewFile();
-    serverStacktraceFile.deleteOnExit();
+    File serverStacktraceFile = workDirectory.newFile("serverStacktrace.txt");
     csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
     csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, serverStacktraceFile.getCanonicalPath());
     csb.addOption(CliStrings.EXPORT_STACKTRACE__MEMBER, "Server");
@@ -125,9 +123,7 @@ public class ShowStackTraceDUnitTest extends CliCommandTestBase {
     getLogWriter().info("Output : \n" + commandResultToString(commandResult));
     assertTrue(commandResult.getStatus().equals(Status.OK));
 
-    File groupStacktraceFile = new File("groupstacktrace.txt");
-    groupStacktraceFile.createNewFile();
-    groupStacktraceFile.deleteOnExit();
+    File groupStacktraceFile = workDirectory.newFile("groupstacktrace.txt");
     csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
     csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, groupStacktraceFile.getCanonicalPath());
     csb.addOption(CliStrings.EXPORT_STACKTRACE__GROUP, "G2");
@@ -137,9 +133,7 @@ public class ShowStackTraceDUnitTest extends CliCommandTestBase {
     getLogWriter().info("Output : \n" + commandResultToString(commandResult));
     assertTrue(commandResult.getStatus().equals(Status.OK));
 
-    File wrongStackTraceFile = new File("wrongStackTrace.txt");
-    wrongStackTraceFile.createNewFile();
-    wrongStackTraceFile.deleteOnExit();
+    File wrongStackTraceFile = workDirectory.newFile("wrongStackTrace.txt");
     csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
     csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, wrongStackTraceFile.getCanonicalPath());
     csb.addOption(CliStrings.EXPORT_STACKTRACE__MEMBER, "WrongMember");
@@ -149,4 +143,120 @@ public class ShowStackTraceDUnitTest extends CliCommandTestBase {
     getLogWriter().info("Output : \n" + commandResultToString(commandResult));
     assertFalse(commandResult.getStatus().equals(Status.OK));
   }
+
+  /***
+   * Tests the behavior of the show stack-trace command to verify that files with any extension are
+   * allowed Refer: GEODE-734
+   *
+   * @throws ClassNotFoundException
+   * @throws IOException
+   */
+  @Test
+  public void testExportStacktraceWithNonTXTFile() throws ClassNotFoundException, IOException {
+    setupSystem();
+
+    // Test non txt extension file is allowed
+    File stacktracesFile = workDirectory.newFile("allStackTraces.log");
+    CommandStringBuilder commandStringBuilder =
+        new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+    commandStringBuilder.addOption(CliStrings.EXPORT_STACKTRACE__FILE,
+        stacktracesFile.getCanonicalPath());
+    String exportCommandString = commandStringBuilder.toString();
+    getLogWriter().info("CommandString : " + exportCommandString);
+    CommandResult exportCommandResult = executeCommand(exportCommandString);
+    getLogWriter().info("Output : \n" + commandResultToString(exportCommandResult));
+    assertTrue(exportCommandResult.getStatus().equals(Status.OK));
+
+    // test file with-out any extension
+    File allStacktracesFile = workDirectory.newFile("allStackTraces");
+    commandStringBuilder = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+    commandStringBuilder.addOption(CliStrings.EXPORT_STACKTRACE__FILE,
+        allStacktracesFile.getCanonicalPath());
+    exportCommandString = commandStringBuilder.toString();
+    getLogWriter().info("CommandString : " + exportCommandString);
+    exportCommandResult = executeCommand(exportCommandString);
+    getLogWriter().info("Output : \n" + commandResultToString(exportCommandResult));
+    assertTrue(exportCommandResult.getStatus().equals(Status.OK));
+  }
+
+  /***
+   * Tests the behavior of the show stack-trace command when file is already present and
+   * abort-if-file-exists option is set to false(which is default). As a result it should overwrite
+   * the file and return OK status
+   *
+   * @throws ClassNotFoundException
+   * @throws IOException
+   */
+  @Test
+  public void testExportStacktraceWhenFilePresent() throws ClassNotFoundException, IOException {
+    setupSystem();
+
+    // test pass although file present
+    File stacktracesFile = workDirectory.newFile("allStackTraces.log");
+    CommandStringBuilder commandStringBuilder =
+        new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+    commandStringBuilder.addOption(CliStrings.EXPORT_STACKTRACE__FILE,
+        stacktracesFile.getCanonicalPath());
+    String exportCommandString = commandStringBuilder.toString();
+    getLogWriter().info("CommandString : " + exportCommandString);
+    CommandResult exportCommandResult = executeCommand(exportCommandString);
+    getLogWriter().info("Output : \n" + commandResultToString(exportCommandResult));
+    assertTrue(exportCommandResult.getStatus().equals(Status.OK));
+
+  }
+
+  /***
+   * Tests the behavior of the show stack-trace command when file is already present and when
+   * abort-if-file-exists option is set to true. As a result it should fail with ERROR status
+   *
+   * @throws ClassNotFoundException
+   * @throws IOException
+   */
+  @Test
+  public void testExportStacktraceFilePresentWithAbort()
+      throws ClassNotFoundException, IOException, GfJsonException {
+    setupSystem();
+
+    File stacktracesFile = workDirectory.newFile("allStackTraces.log");
+    CommandStringBuilder commandStringBuilder =
+        new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+    commandStringBuilder.addOption(CliStrings.EXPORT_STACKTRACE__FILE,
+        stacktracesFile.getCanonicalPath());
+    commandStringBuilder.addOption(CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT,
+        Boolean.TRUE.toString());
+    String exportCommandString = commandStringBuilder.toString();
+    getLogWriter().info("CommandString : " + exportCommandString);
+    CommandResult exportCommandResult = executeCommand(exportCommandString);
+    getLogWriter().info("Output : \n" + commandResultToString(exportCommandResult));
+    assertTrue(exportCommandResult.getStatus().equals(Status.ERROR));
+    assertTrue(((String) exportCommandResult.getResultData().getGfJsonObject()
+        .getJSONObject("content").getJSONArray("message").get(0))
+            .contains("file " + stacktracesFile.getCanonicalPath() + " already present"));
+  }
+
+  /***
+   * Tests the behavior of the show stack-trace command when file option is not provided File should
+   * get auto-generated
+   *
+   * @throws ClassNotFoundException
+   * @throws IOException
+   */
+  @Test
+  public void testExportStacktraceAutoGenerateFile()
+      throws ClassNotFoundException, IOException, GfJsonException {
+    setupSystem();
+
+    // test auto generated file when file name is not provided
+    CommandStringBuilder commandStringBuilder =
+        new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+    String exportCommandString = commandStringBuilder.toString();
+    getLogWriter().info("CommandString : " + exportCommandString);
+    CommandResult exportCommandResult = executeCommand(exportCommandString);
+    getLogWriter().info("Output : \n" + commandResultToString(exportCommandResult));
+    assertTrue(exportCommandResult.getStatus().equals(Status.OK));
+    assertTrue(
+        ((String) exportCommandResult.getResultData().getGfJsonObject().getJSONObject("content")
+            .getJSONArray("message").get(0)).contains("stack-trace(s) exported to file:"));
+
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/90313511/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties b/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties
index f08a257..786dd40 100644
--- a/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties
+++ b/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties
@@ -1511,7 +1511,8 @@ IS AVAILABLE\n\
 SYNOPSIS\n\
 \ \ \ \ Export the stack trace for a member or members.\n\
 SYNTAX\n\
-\ \ \ \ export stack-traces --file=value [--member=value] [--group=value]\n\
+\ \ \ \ export stack-traces [--member=value] [--group=value] [--file=value]\n\
+\ \ \ \ [--abort-if-file-exists=value]\n\
 PARAMETERS\n\
 \ \ \ \ member\n\
 \ \ \ \ \ \ \ \ Export the stack trace for a member or members.\n\
@@ -1521,7 +1522,11 @@ PARAMETERS\n\
 \ \ \ \ \ \ \ \ Required: false\n\
 \ \ \ \ file\n\
 \ \ \ \ \ \ \ \ Name of the file to which the stack traces will be written.\n\
-\ \ \ \ \ \ \ \ Required: true\n\
+\ \ \ \ \ \ \ \ Required: false\n\
+\ \ \ \ abort-if-file-exists\n\
+\ \ \ \ \ \ \ \ Abort the command if already exists at locator directory\n\
+\ \ \ \ \ \ \ \ Required: false\n\
+\ \ \ \ \ \ \ \ Default (if the parameter is not specified): false\n\
 
 gc.help=\
 NAME\n\


[06/50] [abbrv] geode git commit: GEODE-2187: Docs: bad subnav link in REST Apps > Troubleshooting

Posted by kl...@apache.org.
GEODE-2187: Docs: bad subnav link in REST Apps > Troubleshooting


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

Branch: refs/heads/feature/GEODE-1930
Commit: f58a11d943bbde29a237968a67392e75690698ee
Parents: 7fb0e68
Author: Dave Barnes <db...@pivotal.io>
Authored: Wed Dec 7 10:15:44 2016 -0800
Committer: Dave Barnes <db...@pivotal.io>
Committed: Wed Dec 7 10:15:44 2016 -0800

----------------------------------------------------------------------
 geode-book/master_middleman/source/subnavs/geode-subnav.erb | 9 ++-------
 geode-docs/rest_apps/troubleshooting.html.md.erb            | 5 +----
 2 files changed, 3 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/f58a11d9/geode-book/master_middleman/source/subnavs/geode-subnav.erb
----------------------------------------------------------------------
diff --git a/geode-book/master_middleman/source/subnavs/geode-subnav.erb b/geode-book/master_middleman/source/subnavs/geode-subnav.erb
index aec611d..16aa1e7 100644
--- a/geode-book/master_middleman/source/subnavs/geode-subnav.erb
+++ b/geode-book/master_middleman/source/subnavs/geode-subnav.erb
@@ -21,7 +21,7 @@ limitations under the License.
     <div class="nav-content">
         <ul>
             <li>
-                <a href="/docs/guide/about_geode.html">Apache Geode 1.0.0-incubating Documentation</a>
+                <a href="/docs/guide/about_geode.html">Apache Geode Documentation</a>
             </li>
             <li class="has_submenu">
                 <a href="/docs/guide/getting_started/book_intro.html">Getting Started with Apache Geode</a>
@@ -1642,13 +1642,8 @@ limitations under the License.
                     <li>
                         <a href="/docs/guide/rest_apps/rest_examples.html">Sample REST Applications</a>
                     </li>
-                    <li class="has_submenu">
+                    <li>
                         <a href="/docs/guide/rest_apps/troubleshooting.html">Troubleshooting and FAQ</a>
-                        <ul>
-                            <li>
-                                <a href="/docs/guide/rest_apps/troubleshooting.html#concept_gsv_zd5_m4">Key Types and JSON Support</a>
-                            </li>
-                        </ul>
                     </li>
                     <li class="has_submenu">
                         <a href="/docs/guide/rest_apps/rest_api_reference.html">Apache Geode REST API Reference</a>

http://git-wip-us.apache.org/repos/asf/geode/blob/f58a11d9/geode-docs/rest_apps/troubleshooting.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/rest_apps/troubleshooting.html.md.erb b/geode-docs/rest_apps/troubleshooting.html.md.erb
index 027e2c6..0f47fff 100644
--- a/geode-docs/rest_apps/troubleshooting.html.md.erb
+++ b/geode-docs/rest_apps/troubleshooting.html.md.erb
@@ -23,10 +23,6 @@ limitations under the License.
 
 This section provides troubleshooting guidance and frequently asked questions about Geode Developer REST APIs.
 
--   **[Key Types and JSON Support](../rest_apps/troubleshooting.html#concept_gsv_zd5_m4)**
-
-    When defining regions (your REST resources), you must only use scalar values for keys and also set value constraints in order to avoid producing JSON that cannot be parsed by Geode.
-
 ## Checking if the REST API Service is Up and Running
 
 Use the ping endpoint to verify whether the REST API server is available.
@@ -52,6 +48,7 @@ If the server is not available, your client will receive an HTTP error code and
 When defining regions (your REST resources), you must only use scalar values for keys and also set value constraints in order to avoid producing JSON that cannot be parsed by Geode.
 
 If Geode regions are not defined with scalar values as keys and value constraints, then you may receive the following error message (even though the JSON is technically valid) in your REST client applications:
+
 ``` pre
 Json doc specified in request body is malformed..!!'
 ```


[41/50] [abbrv] geode git commit: [GEODE-2144] Improve error message when no security credentials are provided.

Posted by kl...@apache.org.
[GEODE-2144] Improve error message when no security credentials are provided.

- Improve error message when no security credentials are provided.
- Add tests for the code paths exposing this message.
- Refactor making those code paths more testable.

This closes #310


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

Branch: refs/heads/feature/GEODE-1930
Commit: 80525b7e8414456fe18d1c4c55df48d9c3bf9f71
Parents: 70800f5
Author: Jared Stewart <js...@pivotal.io>
Authored: Fri Dec 9 13:29:36 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Tue Dec 13 10:06:22 2016 -0800

----------------------------------------------------------------------
 .../java/org/apache/geode/internal/Version.java |   3 +
 .../internal/cache/tier/sockets/AuthIds.java    |  48 +++++++
 .../internal/cache/tier/sockets/HandShake.java  |  38 +++---
 .../cache/tier/sockets/MessageIdExtractor.java  |  43 +++++++
 .../cache/tier/sockets/ServerConnection.java    |  83 ++++---------
 .../geode/internal/i18n/LocalizedStrings.java   |   4 +-
 .../apache/geode/internal/VersionJUnitTest.java |   8 ++
 .../cache/tier/sockets/HandShakeTest.java       |  52 ++++++++
 .../tier/sockets/MessageIdExtractorTest.java    |  83 +++++++++++++
 .../tier/sockets/ServerConnectionTest.java      | 124 +++++++++++++++++++
 10 files changed, 410 insertions(+), 76 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/main/java/org/apache/geode/internal/Version.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/Version.java b/geode-core/src/main/java/org/apache/geode/internal/Version.java
index 5f7c5ba..0f64e72 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/Version.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/Version.java
@@ -587,4 +587,7 @@ public final class Version implements Comparable<Version> {
     return bytes;
   }
 
+  public boolean isPre65() {
+    return compareTo(Version.GFE_65) < 0;
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/AuthIds.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/AuthIds.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/AuthIds.java
new file mode 100644
index 0000000..556cb36
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/AuthIds.java
@@ -0,0 +1,48 @@
+/*
+ * 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.cache.tier.sockets;
+
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+
+public class AuthIds {
+  private long connectionId;
+  private long uniqueId;
+
+  public AuthIds(byte[] bytes) throws Exception {
+    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
+    if (bytes.length == 8) {
+      // only connectionid
+      connectionId = dis.readLong();
+    } else if (bytes.length == 16) {
+      // first connectionId and then uniqueID
+      connectionId = dis.readLong();
+      uniqueId = dis.readLong();
+    } else {
+      throw new Exception("Auth ids are not in right form");
+    }
+  }
+
+
+  public long getConnectionId() {
+    return connectionId;
+  }
+
+  public long getUniqueId() {
+    return this.uniqueId;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/HandShake.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/HandShake.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/HandShake.java
index c0db945..9a5c6c6 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/HandShake.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/HandShake.java
@@ -245,6 +245,12 @@ public class HandShake implements ClientHandShake {
    */
   private static short overrideClientVersion = -1;
 
+  /** Constructor used for mocking */
+  protected HandShake() {
+    system = null;
+    id = null;
+  }
+
   /** Constructor used by server side connection */
   public HandShake(Socket sock, int timeout, DistributedSystem sys, Version clientVersion,
       byte communicationMode) throws IOException, AuthenticationRequiredException {
@@ -852,6 +858,18 @@ public class HandShake implements ClientHandShake {
     return _encrypt;
   }
 
+  /**
+   * Throws AuthenticationRequiredException if authentication is required but there are no
+   * credentials.
+   */
+  static void throwIfMissingRequiredCredentials(boolean requireAuthentication,
+      boolean hasCredentials) {
+    if (requireAuthentication && !hasCredentials) {
+      throw new AuthenticationRequiredException(
+          LocalizedStrings.HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED.toLocalizedString());
+    }
+  }
+
   // This assumes that authentication is the last piece of info in handshake
   public Properties readCredential(DataInputStream dis, DataOutputStream dos,
       DistributedSystem system) throws GemFireSecurityException, IOException {
@@ -860,14 +878,8 @@ public class HandShake implements ClientHandShake {
     boolean requireAuthentication = securityService.isClientSecurityRequired();
     try {
       byte secureMode = dis.readByte();
-      if (secureMode == CREDENTIALS_NONE) {
-        // when server is configured with authenticator, new joiner must
-        // pass its credentials.
-        if (requireAuthentication) {
-          throw new AuthenticationRequiredException(
-              LocalizedStrings.HandShake_NO_SECURITY_PROPERTIES_ARE_PROVIDED.toLocalizedString());
-        }
-      } else if (secureMode == CREDENTIALS_NORMAL) {
+      throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
+      if (secureMode == CREDENTIALS_NORMAL) {
         this.appSecureMode = CREDENTIALS_NORMAL;
         /*
          * if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else {
@@ -1553,14 +1565,8 @@ public class HandShake implements ClientHandShake {
     Properties credentials = null;
     try {
       byte secureMode = dis.readByte();
-      if (secureMode == CREDENTIALS_NONE) {
-        // when server is configured with authenticator, new joiner must
-        // pass its credentials.
-        if (requireAuthentication) {
-          throw new AuthenticationRequiredException(
-              LocalizedStrings.HandShake_NO_SECURITY_PROPERTIES_ARE_PROVIDED.toLocalizedString());
-        }
-      } else if (secureMode == CREDENTIALS_NORMAL) {
+      throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
+      if (secureMode == CREDENTIALS_NORMAL) {
         if (requireAuthentication) {
           credentials = DataSerializer.readProperties(dis);
         } else {

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageIdExtractor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageIdExtractor.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageIdExtractor.java
new file mode 100644
index 0000000..311c074
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageIdExtractor.java
@@ -0,0 +1,43 @@
+/*
+ * 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.cache.tier.sockets;
+
+import org.apache.geode.internal.i18n.LocalizedStrings;
+import org.apache.geode.security.AuthenticationRequiredException;
+
+public class MessageIdExtractor {
+  public long getUniqueIdFromMessage(Message requestMessage, HandShake handshake, long connectionId)
+      throws AuthenticationRequiredException {
+    AuthIds aIds = getAuthIdsFromMessage(requestMessage, handshake);
+    if (connectionId != aIds.getConnectionId()) {
+      throw new AuthenticationRequiredException(
+          LocalizedStrings.HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED.toLocalizedString());
+    }
+    return aIds.getUniqueId();
+  }
+
+  private AuthIds getAuthIdsFromMessage(Message requestMessage, HandShake handshake)
+      throws AuthenticationRequiredException {
+    try {
+      byte[] secureBytes = requestMessage.getSecureBytes();
+      secureBytes = handshake.decryptBytes(secureBytes);
+      return new AuthIds(secureBytes);
+    } catch (Exception ex) {
+      throw new AuthenticationRequiredException(
+          LocalizedStrings.HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED.toLocalizedString(), ex);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java
index 59b0fa4..ecd9c7a 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java
@@ -238,6 +238,8 @@ public class ServerConnection implements Runnable {
 
   private Principal principal;
 
+  private MessageIdExtractor messageIdExtractor = new MessageIdExtractor();
+
   /**
    * A debug flag used for testing Backward compatibility
    */
@@ -395,6 +397,10 @@ public class ServerConnection implements Runnable {
     this.keySetResponseMsg.setVersion(v);
   }
 
+  public void setRequestMsg(Message requestMsg) {
+    this.requestMsg = requestMsg;
+  }
+
   public Version getClientVersion() {
     return this.handshake.getVersion();
   }
@@ -1441,8 +1447,7 @@ public class ServerConnection implements Runnable {
     if (isClosed()) {
       return false;
     }
-    if (this.communicationMode == Acceptor.CLIENT_TO_SERVER
-        || this.communicationMode == Acceptor.GATEWAY_TO_GATEWAY
+    if (this.communicationMode == Acceptor.CLIENT_TO_SERVER || isGatewayConnection()
         || this.communicationMode == Acceptor.MONITOR_TO_SERVER
     /* || this.communicationMode == Acceptor.CLIENT_TO_SERVER_FOR_QUEUE */) {
       getAcceptor().decClientServerCnxCount();
@@ -1703,34 +1708,6 @@ public class ServerConnection implements Runnable {
     this.userAuthId = uniqueId;
   }
 
-  private static class AuthIds {
-    private long connectionId;
-    private long uniqueId;
-
-    public AuthIds(byte[] bytes) throws Exception {
-      DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
-      if (bytes.length == 8) {
-        // only connectionid
-        connectionId = dis.readLong();
-      } else if (bytes.length == 16) {
-        // first connectionId and then uniqueID
-        connectionId = dis.readLong();
-        uniqueId = dis.readLong();
-      } else {
-        throw new Exception("Auth ids are not in right form");
-      }
-    }
-
-
-    public long getConnectionId() {
-      return connectionId;
-    }
-
-    public long getUniqueId() {
-      return this.uniqueId;
-    }
-  }
-
   private byte[] encryptId(long id, ServerConnection servConn) throws Exception {
     // deserialize this using handshake keys
     HeapDataOutputStream hdos = null;
@@ -1748,40 +1725,22 @@ public class ServerConnection implements Runnable {
   public long getUniqueId() {
     long uniqueId = 0;
 
-    if (this.handshake.getVersion().compareTo(Version.GFE_65) < 0
-        || this.communicationMode == Acceptor.GATEWAY_TO_GATEWAY) {
+    if (this.handshake.getVersion().isPre65() || isGatewayConnection()) {
       uniqueId = this.userAuthId;
+    } else if (this.requestMsg.isSecureMode()) {
+      uniqueId = messageIdExtractor.getUniqueIdFromMessage(this.requestMsg,
+          (HandShake) this.handshake, this.connectionId);
     } else {
-      try {
-        // this.logger.fine("getAuthzRequest() isSecureMode = " + this.requestMsg.isSecureMode());
-        if (this.requestMsg.isSecureMode()) {
-          // get uniqueID from message
-          byte[] secureBytes = this.requestMsg.getSecureBytes();
-
-          secureBytes = ((HandShake) this.handshake).decryptBytes(secureBytes);
-          AuthIds aIds = new AuthIds(secureBytes);
-
-          if (this.connectionId != aIds.getConnectionId()) {
-            throw new AuthenticationRequiredException(
-                LocalizedStrings.HandShake_NO_SECURITY_PROPERTIES_ARE_PROVIDED.toLocalizedString());
-          } else {
-            uniqueId = aIds.getUniqueId();
-          }
-
-        } else {
-          throw new AuthenticationRequiredException(
-              LocalizedStrings.HandShake_NO_SECURITY_PROPERTIES_ARE_PROVIDED.toLocalizedString());
-        }
-      } catch (AuthenticationRequiredException are) {
-        throw are;
-      } catch (Exception ex) {
-        throw new AuthenticationRequiredException(
-            LocalizedStrings.HandShake_NO_SECURITY_PROPERTIES_ARE_PROVIDED.toLocalizedString());
-      }
+      throw new AuthenticationRequiredException(
+          LocalizedStrings.HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED.toLocalizedString());
     }
     return uniqueId;
   }
 
+  private boolean isGatewayConnection() {
+    return getCommunicationMode() == Acceptor.GATEWAY_TO_GATEWAY;
+  }
+
   public AuthorizeRequest getAuthzRequest() throws AuthenticationRequiredException, IOException {
     // look client version and return authzrequest
     // for backward client it will be store in member variable userAuthId
@@ -1862,4 +1821,12 @@ public class ServerConnection implements Runnable {
   public void setClientDisconnectedException(Throwable e) {
     this.clientDisconnectedException = e;
   }
+
+  public void setMessageIdExtractor(MessageIdExtractor messageIdExtractor) {
+    this.messageIdExtractor = messageIdExtractor;
+  }
+
+  public MessageIdExtractor getMessageIdExtractor() {
+    return this.messageIdExtractor;
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/main/java/org/apache/geode/internal/i18n/LocalizedStrings.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/i18n/LocalizedStrings.java b/geode-core/src/main/java/org/apache/geode/internal/i18n/LocalizedStrings.java
index 38f7397..48b8a14 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/i18n/LocalizedStrings.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/i18n/LocalizedStrings.java
@@ -5350,8 +5350,8 @@ public class LocalizedStrings {
       new StringId(4192, "Server expecting SSL connection");
   public static final StringId HandShake_FAILED_TO_ACQUIRE_AUTHINITIALIZE_METHOD_0 =
       new StringId(4194, "Failed to acquire AuthInitialize method {0}");
-  public static final StringId HandShake_NO_SECURITY_PROPERTIES_ARE_PROVIDED =
-      new StringId(4195, "No security-* properties are provided");
+  public static final StringId HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED =
+      new StringId(4195, "No security credentials are provided");
   public static final StringId HandShake_FAILURE_IN_READING_CREDENTIALS =
       new StringId(4196, "Failure in reading credentials");
   public static final StringId HandShake_FAILED_TO_ACQUIRE_AUTHENTICATOR_OBJECT =

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/test/java/org/apache/geode/internal/VersionJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/VersionJUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/VersionJUnitTest.java
index 0bc6822..8cd4d81 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/VersionJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/VersionJUnitTest.java
@@ -14,6 +14,7 @@
  */
 package org.apache.geode.internal;
 
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
 import org.junit.Test;
@@ -45,4 +46,11 @@ public class VersionJUnitTest {
     assertTrue(later.compareTo(later.ordinal()) == 0);
     assertTrue(earlier.compareTo(later.ordinal()) < 0);
   }
+
+  @Test
+  public void testIsPre65() {
+    assertTrue(Version.GFE_61.isPre65());
+    assertFalse(Version.GFE_65.isPre65());
+    assertFalse(Version.GFE_70.isPre65());
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/HandShakeTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/HandShakeTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/HandShakeTest.java
new file mode 100644
index 0000000..2850500
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/HandShakeTest.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.internal.cache.tier.sockets;
+
+import static org.apache.geode.internal.i18n.LocalizedStrings.HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.apache.geode.security.AuthenticationRequiredException;
+import org.apache.geode.test.junit.categories.UnitTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+@Category(UnitTest.class)
+public class HandShakeTest {
+
+  @Test
+  public void authRequiredHasCredentials() throws Exception {
+    HandShake.throwIfMissingRequiredCredentials(true, true);
+  }
+
+  @Test
+  public void authRequiredHasNoCredentials() throws Exception {
+    assertThatThrownBy(() -> HandShake.throwIfMissingRequiredCredentials(true, false))
+        .isExactlyInstanceOf(AuthenticationRequiredException.class)
+        .hasMessage(HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED.toLocalizedString());
+  }
+
+  @Test
+  public void authNotRequiredHasCredentials() throws Exception {
+    HandShake.throwIfMissingRequiredCredentials(false, true);
+  }
+
+  @Test
+  public void authNotRequiredHasNoCredentials() throws Exception {
+    HandShake.throwIfMissingRequiredCredentials(false, false);
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/MessageIdExtractorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/MessageIdExtractorTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/MessageIdExtractorTest.java
new file mode 100644
index 0000000..0bc6381
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/MessageIdExtractorTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.cache.tier.sockets;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
+import org.apache.commons.io.output.ByteArrayOutputStream;
+import org.apache.geode.security.AuthenticationRequiredException;
+import org.apache.geode.test.junit.categories.UnitTest;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+@Category(UnitTest.class)
+public class MessageIdExtractorTest {
+  @Mock
+  Message requestMessage;
+
+  @Mock
+  HandShake handshake;
+
+  private MessageIdExtractor messageIdExtractor;
+
+  private Long connectionId = 123L;
+  private Long uniqueId = 234L;
+  private byte[] decryptedBytes;
+
+  @Before
+  public void before() throws Exception {
+    this.messageIdExtractor = new MessageIdExtractor();
+    decryptedBytes = byteArrayFromIds(connectionId, uniqueId);
+
+    MockitoAnnotations.initMocks(this);
+
+    when(handshake.decryptBytes(any())).thenReturn(decryptedBytes);
+  }
+
+  @Test
+  public void getUniqueIdFromMessage() throws Exception {
+    assertThat(messageIdExtractor.getUniqueIdFromMessage(requestMessage, handshake, connectionId))
+        .isEqualTo(uniqueId);
+  }
+
+  @Test
+  public void throwsWhenConnectionIdsDoNotMatch() throws Exception {
+    long otherConnectionId = 789L;
+
+    assertThatThrownBy(() -> messageIdExtractor.getUniqueIdFromMessage(requestMessage, handshake,
+        otherConnectionId)).isInstanceOf(AuthenticationRequiredException.class);
+  }
+
+  private byte[] byteArrayFromIds(Long connectionId, Long uniqueId) throws IOException {
+    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+    DataOutputStream dis = new DataOutputStream(byteArrayOutputStream);
+    dis.writeLong(connectionId);
+    dis.writeLong(uniqueId);
+    dis.flush();
+    return byteArrayOutputStream.toByteArray();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/80525b7e/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionTest.java
new file mode 100644
index 0000000..153e77b
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionTest.java
@@ -0,0 +1,124 @@
+/*
+ * 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.cache.tier.sockets;
+
+
+import static org.apache.geode.internal.i18n.LocalizedStrings.HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.internal.Version;
+import org.apache.geode.internal.cache.tier.Acceptor;
+import org.apache.geode.security.AuthenticationRequiredException;
+import org.apache.geode.test.junit.categories.UnitTest;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.net.InetAddress;
+import java.net.Socket;
+
+@Category(UnitTest.class)
+public class ServerConnectionTest {
+  @Mock
+  private Message requestMsg;
+
+  @Mock
+  private HandShake handshake;
+
+  @Mock
+  private MessageIdExtractor messageIdExtractor;
+
+  @InjectMocks
+  private ServerConnection serverConnection;
+
+  @Before
+  public void setUp() {
+    AcceptorImpl acceptor = mock(AcceptorImpl.class);
+
+    InetAddress inetAddress = mock(InetAddress.class);
+    when(inetAddress.getHostAddress()).thenReturn("localhost");
+
+    Socket socket = mock(Socket.class);
+    when(socket.getInetAddress()).thenReturn(inetAddress);
+
+    Cache cache = mock(Cache.class);
+
+    serverConnection = new ServerConnection(socket, cache, null, null, 0, 0, null,
+        Acceptor.PRIMARY_SERVER_TO_CLIENT, acceptor);
+    MockitoAnnotations.initMocks(this);
+  }
+
+
+  @Test
+  public void pre65SecureShouldReturnUserAuthId() {
+    long userAuthId = 12345L;
+    serverConnection.setUserAuthId(userAuthId);
+
+    when(handshake.getVersion()).thenReturn(Version.GFE_61);
+    when(requestMsg.isSecureMode()).thenReturn(true);
+
+    assertThat(serverConnection.getUniqueId()).isEqualTo(userAuthId);
+  }
+
+  @Test
+  public void pre65NonSecureShouldReturnUserAuthId() {
+    long userAuthId = 12345L;
+    serverConnection.setUserAuthId(userAuthId);
+
+    when(handshake.getVersion()).thenReturn(Version.GFE_61);
+    when(requestMsg.isSecureMode()).thenReturn(false);
+
+    assertThat(serverConnection.getUniqueId()).isEqualTo(userAuthId);
+  }
+
+
+  @Test
+  public void post65SecureShouldUseUniqueIdFromMessage() {
+    long uniqueIdFromMessage = 23456L;
+    when(handshake.getVersion()).thenReturn(Version.GFE_82);
+    serverConnection.setRequestMsg(requestMsg);
+
+    assertThat(serverConnection.getRequestMessage()).isSameAs(requestMsg);
+    when(requestMsg.isSecureMode()).thenReturn(true);
+
+    when(messageIdExtractor.getUniqueIdFromMessage(any(Message.class), any(HandShake.class),
+        anyLong())).thenReturn(uniqueIdFromMessage);
+    serverConnection.setMessageIdExtractor(messageIdExtractor);
+
+    assertThat(serverConnection.getUniqueId()).isEqualTo(uniqueIdFromMessage);
+  }
+
+  @Test
+  public void post65NonSecureShouldThrow() {
+    when(handshake.getVersion()).thenReturn(Version.GFE_82);
+    when(requestMsg.isSecureMode()).thenReturn(false);
+
+    assertThatThrownBy(serverConnection::getUniqueId)
+        .isExactlyInstanceOf(AuthenticationRequiredException.class)
+        .hasMessage(HandShake_NO_SECURITY_CREDENTIALS_ARE_PROVIDED.getRawText());
+  }
+
+}


[20/50] [abbrv] geode git commit: GEODE-1984: Fix Issue Make GatewaySender destroy a public API

Posted by kl...@apache.org.
GEODE-1984: Fix Issue Make GatewaySender destroy a public API

    1. Making destory API public
    2. Added a new gfsh WAN command destroyGatewaySender
    3. Impleted GatewaySenderDestroyFunction, which first stop gatewaysender
       and then call destroy on the same.
    4. Added a WAN Rest Controller for destroy gatewaysender
    5. Removed the need of explicit casting of sender to AbstractGatewaySender for calling
       destroy API
    6. Renamed Test WanCommandCreateGatewaySenderDUnitTest to WanCommandCreateDestroyGatewaySenderDUnitTest
    7. Each applicable test now also calls destroy gfsh command and verfies the result
    8. Minor changes in the logging for each tests


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

Branch: refs/heads/feature/GEODE-1930
Commit: 0eb952a6e5524c66c8520c9e0d8cf09780ef8624
Parents: 1d951e3
Author: adongre <ad...@apache.org>
Authored: Sat Dec 3 19:38:39 2016 +0530
Committer: adongre <ad...@apache.org>
Committed: Fri Dec 9 05:08:36 2016 +0530

----------------------------------------------------------------------
 .../internal/AsyncEventQueueImpl.java           |   2 +-
 .../apache/geode/cache/wan/GatewaySender.java   |  15 +
 .../cache/wan/AbstractGatewaySender.java        |   1 +
 .../internal/cli/commands/WanCommands.java      |  59 +-
 .../functions/GatewaySenderDestroyFunction.java |  90 ++
 .../GatewaySenderDestroyFunctionArgs.java       |  33 +
 .../internal/cli/i18n/CliStrings.java           |  18 +
 .../controllers/ShellCommandsController.java    |   2 +
 .../web/controllers/WanCommandsController.java  |  24 +
 .../codeAnalysis/sanctionedSerializables.txt    |   2 +
 .../cli/commands/golden-help-offline.properties |  21 +
 .../cli/commands/golden-help-online.properties  |   6 +
 .../geode/internal/cache/wan/WANTestBase.java   |   2 +-
 .../wan/wancommand/WANCommandTestBase.java      |  35 +
 ...mandCreateDestroyGatewaySenderDUnitTest.java | 921 +++++++++++++++++++
 .../WanCommandCreateGatewaySenderDUnitTest.java | 663 -------------
 16 files changed, 1223 insertions(+), 671 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/cache/asyncqueue/internal/AsyncEventQueueImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/cache/asyncqueue/internal/AsyncEventQueueImpl.java b/geode-core/src/main/java/org/apache/geode/cache/asyncqueue/internal/AsyncEventQueueImpl.java
index a5f0497..2eb53be 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/asyncqueue/internal/AsyncEventQueueImpl.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/asyncqueue/internal/AsyncEventQueueImpl.java
@@ -191,7 +191,7 @@ public class AsyncEventQueueImpl implements AsyncEventQueue {
   }
 
   public void destroy() {
-    ((AbstractGatewaySender) this.sender).destroy();
+    this.sender.destroy();
   }
 
   public boolean isBucketSorted() {

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java b/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java
index d950ef3..f9f8f91 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/wan/GatewaySender.java
@@ -400,4 +400,19 @@ public interface GatewaySender {
 
   public int getMaxParallelismForReplicatedRegion();
 
+
+  /**
+   * Destroys the GatewaySender. Before destroying the sender, caller needs to to ensure that the
+   * sender is stopped so that all the resources (threads, connection pool etc.) will be released
+   * properly. Stopping the sender is not handled in the destroy. Destroy is carried out in
+   * following steps: 1. Take the lifeCycleLock. 2. If the sender is attached to any application
+   * region, throw an exception. 3. Close the GatewaySenderAdvisor. 4. Remove the sender from the
+   * cache. 5. Destroy the region underlying the GatewaySender.
+   * <p>
+   * In case of ParallelGatewaySender, the destroy operation does distributed destroy of the QPR. In
+   * case of SerialGatewaySender, the queue region is destroyed locally.
+   */
+  public void destroy();
+
+
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/internal/cache/wan/AbstractGatewaySender.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/wan/AbstractGatewaySender.java b/geode-core/src/main/java/org/apache/geode/internal/cache/wan/AbstractGatewaySender.java
index e1c9010..c4d503e 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/wan/AbstractGatewaySender.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/wan/AbstractGatewaySender.java
@@ -510,6 +510,7 @@ public abstract class AbstractGatewaySender implements GatewaySender, Distributi
    * In case of ParallelGatewaySender, the destroy operation does distributed destroy of the QPR. In
    * case of SerialGatewaySender, the queue region is destroyed locally.
    */
+  @Override
   public void destroy() {
     try {
       this.getLifeCycleLock().writeLock().lock();

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java
index db1087d..dd6a327 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java
@@ -44,11 +44,7 @@ import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.management.internal.cli.CliUtil;
 import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.GatewayReceiverCreateFunction;
-import org.apache.geode.management.internal.cli.functions.GatewayReceiverFunctionArgs;
-import org.apache.geode.management.internal.cli.functions.GatewaySenderCreateFunction;
-import org.apache.geode.management.internal.cli.functions.GatewaySenderFunctionArgs;
+import org.apache.geode.management.internal.cli.functions.*;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.result.CommandResultException;
 import org.apache.geode.management.internal.cli.result.CompositeResultData;
@@ -1071,6 +1067,57 @@ public class WanCommands implements CommandMarker {
     return result;
   }
 
+
+  @CliCommand(value = CliStrings.DESTROY_GATEWAYSENDER,
+      help = CliStrings.DESTROY_GATEWAYSENDER__HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN, writesToSharedConfiguration = true)
+  @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+  public Result destroyGatewaySender(
+      @CliOption(key = CliStrings.DESTROY_GATEWAYSENDER__GROUP,
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.DESTROY_GATEWAYSENDER__GROUP__HELP) @CliMetaData(
+              valueSeparator = ",") String[] onGroups,
+      @CliOption(key = CliStrings.DESTROY_GATEWAYSENDER__MEMBER,
+          optionContext = ConverterHint.MEMBERIDNAME,
+          unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
+          help = CliStrings.DESTROY_GATEWAYSENDER__MEMBER__HELP) @CliMetaData(
+              valueSeparator = ",") String onMember,
+      @CliOption(key = CliStrings.DESTROY_GATEWAYSENDER__ID, mandatory = true,
+          optionContext = ConverterHint.GATEWAY_SENDER_ID,
+          help = CliStrings.DESTROY_GATEWAYSENDER__ID__HELP) String id) {
+    Result result = null;
+    try {
+      GatewaySenderDestroyFunctionArgs gatewaySenderDestroyFunctionArgs =
+          new GatewaySenderDestroyFunctionArgs(id);
+
+      Set<DistributedMember> membersToDestroyGatewaySenderOn =
+          CliUtil.findAllMatchingMembers(onGroups, onMember == null ? null : onMember.split(","));
+
+      ResultCollector<?, ?> resultCollector =
+          CliUtil.executeFunction(GatewaySenderDestroyFunction.INSTANCE,
+              gatewaySenderDestroyFunctionArgs, membersToDestroyGatewaySenderOn);
+      @SuppressWarnings("unchecked")
+      List<CliFunctionResult> gatewaySenderDestroyResults =
+          (List<CliFunctionResult>) resultCollector.getResult();
+
+      TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
+      final String errorPrefix = "ERROR: ";
+      for (CliFunctionResult gatewaySenderDestroyResult : gatewaySenderDestroyResults) {
+        boolean success = gatewaySenderDestroyResult.isSuccessful();
+        tabularResultData.accumulate("Member", gatewaySenderDestroyResult.getMemberIdOrName());
+        tabularResultData.accumulate("Status",
+            (success ? "" : errorPrefix) + gatewaySenderDestroyResult.getMessage());
+      }
+      result = ResultBuilder.buildResult(tabularResultData);
+    } catch (IllegalArgumentException e) {
+      LogWrapper.getInstance().info(e.getMessage());
+      result = ResultBuilder.createUserErrorResult(e.getMessage());
+    } catch (CommandResultException crex) {
+      result = handleCommandResultException(crex);
+    }
+    return result;
+  }
+
   private TabularResultData buildReceiverStatus(String memberId, GatewayReceiverMXBean bean,
       TabularResultData resultData) {
     resultData.accumulate(CliStrings.RESULT_HOST_MEMBER, memberId);
@@ -1179,7 +1226,7 @@ public class WanCommands implements CommandMarker {
       CliStrings.STOP_GATEWAYSENDER, CliStrings.CREATE_GATEWAYRECEIVER,
       CliStrings.START_GATEWAYRECEIVER, CliStrings.STOP_GATEWAYRECEIVER, CliStrings.LIST_GATEWAY,
       CliStrings.STATUS_GATEWAYSENDER, CliStrings.STATUS_GATEWAYRECEIVER,
-      CliStrings.LOAD_BALANCE_GATEWAYSENDER})
+      CliStrings.LOAD_BALANCE_GATEWAYSENDER, CliStrings.DESTROY_GATEWAYSENDER})
   public boolean isWanCommandsAvailable() {
     boolean isAvailable = true; // always available on server
     if (CliUtil.isGfshVM()) {

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java
new file mode 100644
index 0000000..ba393fe
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction.java
@@ -0,0 +1,90 @@
+/*
+ * 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.internal.cli.functions;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.execute.FunctionAdapter;
+import org.apache.geode.cache.execute.FunctionContext;
+import org.apache.geode.cache.execute.ResultSender;
+import org.apache.geode.cache.wan.GatewaySender;
+import org.apache.geode.internal.InternalEntity;
+import org.apache.geode.internal.cache.wan.GatewaySenderException;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.logging.log4j.Logger;
+
+public class GatewaySenderDestroyFunction extends FunctionAdapter implements InternalEntity {
+  private static final long serialVersionUID = 1459761440357690134L;
+
+  private static final Logger logger = LogService.getLogger();
+  private static final String ID = GatewaySenderDestroyFunction.class.getName();
+  public static GatewaySenderDestroyFunction INSTANCE = new GatewaySenderDestroyFunction();
+
+  @Override
+  public void execute(FunctionContext context) {
+    ResultSender<Object> resultSender = context.getResultSender();
+
+    Cache cache = CacheFactory.getAnyInstance();
+    String memberNameOrId =
+        CliUtil.getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());
+
+    GatewaySenderDestroyFunctionArgs gatewaySenderDestroyFunctionArgs =
+        (GatewaySenderDestroyFunctionArgs) context.getArguments();
+
+    try {
+      GatewaySender gatewaySender =
+          cache.getGatewaySender(gatewaySenderDestroyFunctionArgs.getId());
+      if (gatewaySender != null) {
+        gatewaySender.stop();
+        gatewaySender.destroy();
+      } else {
+        throw new GatewaySenderException(
+            "GateWaySender with Id  " + gatewaySenderDestroyFunctionArgs.getId() + " not found");
+      }
+      resultSender.lastResult(new CliFunctionResult(memberNameOrId, true,
+          CliStrings.format(CliStrings.DESTROY_GATEWAYSENDER__MSG__GATEWAYSENDER_0_DESTROYED_ON_1,
+              new Object[] {gatewaySenderDestroyFunctionArgs.getId(), memberNameOrId})));
+
+    } catch (GatewaySenderException gse) {
+      resultSender.lastResult(handleException(memberNameOrId, gse.getMessage(), gse));
+    } catch (Exception e) {
+      String exceptionMsg = e.getMessage();
+      if (exceptionMsg == null) {
+        exceptionMsg = CliUtil.stackTraceAsString(e);
+      }
+      resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, e));
+    }
+  }
+
+  private CliFunctionResult handleException(final String memberNameOrId, final String exceptionMsg,
+      final Exception e) {
+    if (e != null && logger.isDebugEnabled()) {
+      logger.debug(e.getMessage(), e);
+    }
+    if (exceptionMsg != null) {
+      return new CliFunctionResult(memberNameOrId, false, exceptionMsg);
+    }
+
+    return new CliFunctionResult(memberNameOrId);
+  }
+
+  @Override
+  public String getId() {
+    return ID;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunctionArgs.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunctionArgs.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunctionArgs.java
new file mode 100644
index 0000000..cf3fa24
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunctionArgs.java
@@ -0,0 +1,33 @@
+/*
+ * 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.internal.cli.functions;
+
+import java.io.Serializable;
+
+public class GatewaySenderDestroyFunctionArgs implements Serializable {
+
+  private static final long serialVersionUID = 3848480256348119530L;
+  private String id;
+
+
+  public GatewaySenderDestroyFunctionArgs(String id) {
+    this.id = id;
+  }
+
+  public String getId() {
+    return id;
+  }
+}
+

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
index 68dd438..c53b309 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
@@ -2235,6 +2235,24 @@ public class CliStrings {
   public static final String START_GATEWAYSENDER__MEMBER__HELP =
       "Name/Id of the member on which to start the Gateway Sender.";
 
+
+  /* destroy gateway-sender */
+  public static final String DESTROY_GATEWAYSENDER = "destroy gateway-sender";
+  public static final String DESTROY_GATEWAYSENDER__HELP =
+      "Destroy the Gateway Sender on a member or members.";
+  public static final String DESTROY_GATEWAYSENDER__GROUP = "group";
+  public static final String DESTROY_GATEWAYSENDER__GROUP__HELP =
+      "Group(s) of members on which to destroy the Gateway Sender.";
+  public static final String DESTROY_GATEWAYSENDER__MEMBER = "member";
+  public static final String DESTROY_GATEWAYSENDER__MEMBER__HELP =
+      "Name/Id of the member on which to destroy the Gateway Sender.";
+  public static final String DESTROY_GATEWAYSENDER__ID = "id";
+  public static final String DESTROY_GATEWAYSENDER__ID__HELP = "Id of the GatewaySender.";
+  public static final String DESTROY_GATEWAYSENDER__MSG__GATEWAYSENDER_0_DESTROYED_ON_1 =
+      "GatewaySender \"{0}\" destroyed on \"{1}\"";
+
+
+
   /* start gfmon command */
   public static final String START_PULSE = "start pulse";
   public static final String START_PULSE__ERROR =

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java
index 577aed6..0ecb77f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java
@@ -273,6 +273,8 @@ public class ShellCommandsController extends AbstractCommandsController {
             HttpMethod.POST))
         .add(new Link(CliStrings.CREATE_GATEWAYSENDER, toUri("/gateways/senders", scheme),
             HttpMethod.POST))
+        .add(new Link(CliStrings.DESTROY_GATEWAYSENDER, toUri("/gateways/senders/{id}", scheme),
+            HttpMethod.DELETE))
         .add(new Link(CliStrings.LOAD_BALANCE_GATEWAYSENDER,
             toUri("/gateways/senders/{id}?op=load-balance", scheme), HttpMethod.POST))
         .add(new Link(CliStrings.PAUSE_GATEWAYSENDER,

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/WanCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/WanCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/WanCommandsController.java
index 03dc5d0..fa5aa57 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/WanCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/WanCommandsController.java
@@ -268,6 +268,30 @@ public class WanCommandsController extends AbstractCommandsController {
     return processCommand(command.toString());
   }
 
+
+  @RequestMapping(method = RequestMethod.DELETE, value = "/gateways/senders/{id}")
+  @ResponseBody
+  public String destroyGatewaySender(@PathVariable("id") final String gatewaySenderId,
+      @RequestParam(value = CliStrings.DESTROY_GATEWAYSENDER__GROUP,
+          required = false) final String[] groups,
+      @RequestParam(value = CliStrings.DESTROY_GATEWAYSENDER__MEMBER,
+          required = false) final String[] members) {
+    CommandStringBuilder command = new CommandStringBuilder(CliStrings.DESTROY_GATEWAYSENDER);
+    command.addOption(CliStrings.CREATE_GATEWAYSENDER__ID, gatewaySenderId);
+
+    if (hasValue(groups)) {
+      command.addOption(CliStrings.CREATE_GATEWAYSENDER__GROUP,
+          StringUtils.concat(groups, StringUtils.COMMA_DELIMITER));
+    }
+
+    if (hasValue(members)) {
+      command.addOption(CliStrings.CREATE_GATEWAYSENDER__MEMBER,
+          StringUtils.concat(members, StringUtils.COMMA_DELIMITER));
+    }
+    return processCommand(command.toString());
+  }
+
+
   @RequestMapping(method = RequestMethod.POST, value = "/gateways/senders/{id}",
       params = "op=load-balance")
   @ResponseBody

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt b/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
index 3f92148..5ce46bf 100644
--- a/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
+++ b/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
@@ -569,6 +569,8 @@ org/apache/geode/management/internal/cli/functions/GarbageCollectionFunction,tru
 org/apache/geode/management/internal/cli/functions/GatewayReceiverCreateFunction,true,8746830191680509335
 org/apache/geode/management/internal/cli/functions/GatewayReceiverFunctionArgs,true,-5158224572470173267,bindAddress:java/lang/String,endPort:java/lang/Integer,gatewayTransportFilters:java/lang/String[],manualStart:java/lang/Boolean,maximumTimeBetweenPings:java/lang/Integer,socketBufferSize:java/lang/Integer,startPort:java/lang/Integer
 org/apache/geode/management/internal/cli/functions/GatewaySenderCreateFunction,true,8746830191680509335
+org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunction,true,1459761440357690134
+org/apache/geode/management/internal/cli/functions/GatewaySenderDestroyFunctionArgs,true,3848480256348119530,id:java/lang/String
 org/apache/geode/management/internal/cli/functions/GatewaySenderFunctionArgs,true,-5158224572470173267,alertThreshold:java/lang/Integer,batchSize:java/lang/Integer,batchTimeInterval:java/lang/Integer,diskStoreName:java/lang/String,diskSynchronous:java/lang/Boolean,dispatcherThreads:java/lang/Integer,enableBatchConflation:java/lang/Boolean,enablePersistence:java/lang/Boolean,gatewayEventFilters:java/lang/String[],gatewayTransportFilters:java/lang/String[],id:java/lang/String,manualStart:java/lang/Boolean,maxQueueMemory:java/lang/Integer,orderPolicy:java/lang/String,parallel:java/lang/Boolean,remoteDSId:java/lang/Integer,socketBufferSize:java/lang/Integer,socketReadTimeout:java/lang/Integer
 org/apache/geode/management/internal/cli/functions/GetMemberConfigInformationFunction,true,1
 org/apache/geode/management/internal/cli/functions/GetMemberInformationFunction,true,1

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties b/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties
index 786dd40..f352f3d 100644
--- a/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties
+++ b/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-offline.properties
@@ -835,6 +835,27 @@ PARAMETERS\n\
 \ \ \ \ \ \ \ \ The fully qualified class name of GatewayTransportFilter to be added to the GatewaySender. \n\
 \ \ \ \ \ \ \ \ Required: false\n\
 
+destroy-gateway-sender.help=\
+NAME\n\
+\ \ \ \ destroy gateway-sender\n\
+IS AVAILABLE\n\
+\ \ \ \ false\n\
+SYNOPSIS\n\
+\ \ \ \ Destroy the Gateway Sender on a member or members.\n\
+SYNTAX\n\
+\ \ \ \ destroy gateway-sender --id=value [--group=value(,value)*] [--member=value(,value)*]\n\
+PARAMETERS\n\
+\ \ \ \ group\n\
+\ \ \ \ \ \ \ \ Group(s) of members on which to destroy the Gateway Sender.\n\
+\ \ \ \ \ \ \ \ Required: false\n\
+\ \ \ \ member\n\
+\ \ \ \ \ \ \ \ Name/Id of the member on which to destroy the Gateway Sender.\n\
+\ \ \ \ \ \ \ \ Required: false\n\
+\ \ \ \ id\n\
+\ \ \ \ \ \ \ \ Id of the GatewaySender.\n\
+\ \ \ \ \ \ \ \ Required: true\n\
+
+
 create-index.help=\
 NAME\n\
 \ \ \ \ create index\n\

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-online.properties
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-online.properties b/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-online.properties
index 57f8f37..2b22650 100644
--- a/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-online.properties
+++ b/geode-core/src/test/resources/org/apache/geode/management/internal/cli/commands/golden-help-online.properties
@@ -140,6 +140,12 @@ NAME\n\
 IS AVAILABLE\n\
 \ \ \ \ true\n\
 
+destroy-gateway-sender.help=\
+NAME\n\
+\ \ \ \ destroy gateway-sender\n\
+IS AVAILABLE\n\
+\ \ \ \ true\n\
+
 create-index.help=\
 NAME\n\
 \ \ \ \ create index\n\

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/WANTestBase.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/WANTestBase.java b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/WANTestBase.java
index 9b9ef2b..b0cece0 100644
--- a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/WANTestBase.java
+++ b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/WANTestBase.java
@@ -3418,7 +3418,7 @@ public class WANTestBase extends JUnit4DistributedTestCase {
         break;
       }
     }
-    ((AbstractGatewaySender) sender).destroy();
+    sender.destroy();
   }
 
   public static void verifySenderDestroyed(String senderId, boolean isParallel) {

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java
index caa235e..f364ba3 100644
--- a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java
+++ b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WANCommandTestBase.java
@@ -25,7 +25,10 @@ import org.apache.geode.distributed.Locator;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.internal.AvailablePort;
 import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.internal.cache.LocalRegion;
 import org.apache.geode.internal.cache.wan.AbstractGatewaySender;
+import org.apache.geode.internal.cache.wan.parallel.ParallelGatewaySenderQueue;
 import org.apache.geode.management.ManagementService;
 import org.apache.geode.management.internal.cli.commands.CliCommandTestBase;
 import org.apache.geode.test.dunit.*;
@@ -41,6 +44,7 @@ import java.util.Set;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static org.apache.geode.test.dunit.Assert.assertEquals;
 import static org.apache.geode.test.dunit.Assert.fail;
+import static org.junit.Assert.assertNull;
 
 public abstract class WANCommandTestBase extends CliCommandTestBase {
 
@@ -448,6 +452,37 @@ public abstract class WANCommandTestBase extends CliCommandTestBase {
     }
   }
 
+  // Added for gateway destroy command
+  // Copied from WANTestBase.java
+
+  public static void verifySenderDestroyed(String senderId, boolean isParallel) {
+    Set<GatewaySender> senders = cache.getGatewaySenders();
+    AbstractGatewaySender sender = null;
+    for (GatewaySender s : senders) {
+      if (s.getId().equals(senderId)) {
+        sender = (AbstractGatewaySender) s;
+        break;
+      }
+    }
+    assertNull(sender);
+
+    String queueRegionNameSuffix = null;
+    if (isParallel) {
+      queueRegionNameSuffix = ParallelGatewaySenderQueue.QSTRING;
+    } else {
+      queueRegionNameSuffix = "_SERIAL_GATEWAY_SENDER_QUEUE";
+    }
+
+    Set<LocalRegion> allRegions = ((GemFireCacheImpl) cache).getAllRegions();
+    for (LocalRegion region : allRegions) {
+      if (region.getName().indexOf(senderId + queueRegionNameSuffix) != -1) {
+        fail("Region underlying the sender is not destroyed.");
+      }
+    }
+  }
+
+
+
   @Override
   public final void postTearDownCacheTestCase() throws Exception {
     closeCacheAndDisconnect();

http://git-wip-us.apache.org/repos/asf/geode/blob/0eb952a6/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java
new file mode 100644
index 0000000..d095764
--- /dev/null
+++ b/geode-wan/src/test/java/org/apache/geode/internal/cache/wan/wancommand/WanCommandCreateDestroyGatewaySenderDUnitTest.java
@@ -0,0 +1,921 @@
+/*
+ * 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.cache.wan.wancommand;
+
+import org.apache.geode.cache.wan.GatewaySender;
+import org.apache.geode.cache.wan.GatewaySender.OrderPolicy;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.wan.GatewaySenderException;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CommandResult;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.test.dunit.IgnoredException;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Assert.*;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+
+@Category(DistributedTest.class)
+public class WanCommandCreateDestroyGatewaySenderDUnitTest extends WANCommandTestBase {
+
+  private static final long serialVersionUID = 1L;
+
+  private CommandResult executeCommandWithIgnoredExceptions(String command) {
+    final IgnoredException exln = IgnoredException.addIgnoredException("Could not connect");
+    try {
+      CommandResult commandResult = executeCommand(command);
+      return commandResult;
+    } finally {
+      exln.remove();
+    }
+  }
+
+
+  /**
+   * GatewaySender with all default attributes
+   */
+  @Test
+  public void testCreateDestroyGatewaySenderWithDefault() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info(
+          "testCreateDestroyGatewaySenderWithDefault stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySenderWithDefault failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderState("ln", true, false));
+    vm4.invoke(() -> verifySenderState("ln", true, false));
+    vm5.invoke(() -> verifySenderState("ln", true, false));
+
+    // Test Destroy Command.
+    command =
+        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
+    cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info(
+          "testCreateDestroyGatewaySenderWithDefault stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+
+    } else {
+      fail("testCreateDestroyGatewaySenderWithDefault failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderDestroyed("ln", false));
+    vm4.invoke(() -> verifySenderDestroyed("ln", false));
+    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+  }
+
+  /**
+   * + * GatewaySender with given attribute values +
+   */
+  @Test
+  public void testCreateDestroyGatewaySender() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info("testCreateDestroyGatewaySender stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySender failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderState("ln", false, false));
+    vm4.invoke(() -> verifySenderState("ln", false, false));
+    vm5.invoke(() -> verifySenderState("ln", false, false));
+
+    vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
+    vm4.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
+    vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
+
+    // Test Destroy Command.
+    command =
+        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
+    cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info("testCreateDestroyGatewaySender stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySender failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderDestroyed("ln", false));
+    vm4.invoke(() -> verifySenderDestroyed("ln", false));
+    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+  }
+
+  /**
+   * GatewaySender with given attribute values. Error scenario where dispatcher threads is set to
+   * more than 1 and no order policy provided.
+   */
+  @Test
+  public void testCreateGatewaySender_Error() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info("testCreateDestroyGatewaySender stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation should fail", status.get(i).indexOf("ERROR:") != -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySender failed as did not get CommandResult");
+    }
+
+  }
+
+  /**
+   * GatewaySender with given attribute values and event filters.
+   */
+  @Test
+  public void testCreateDestroyGatewaySenderWithGatewayEventFilters() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__GATEWAYEVENTFILTER
+        + "=org.apache.geode.cache30.MyGatewayEventFilter1,org.apache.geode.cache30.MyGatewayEventFilter2";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info("testCreateDestroyGatewaySenderWithGatewayEventFilters stringResult : "
+          + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail(
+          "testCreateDestroyGatewaySenderWithGatewayEventFilters failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderState("ln", false, false));
+    vm4.invoke(() -> verifySenderState("ln", false, false));
+    vm5.invoke(() -> verifySenderState("ln", false, false));
+
+    List<String> eventFilters = new ArrayList<String>();
+    eventFilters.add("org.apache.geode.cache30.MyGatewayEventFilter1");
+    eventFilters.add("org.apache.geode.cache30.MyGatewayEventFilter2");
+    vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, eventFilters, null));
+    vm4.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, eventFilters, null));
+    vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, eventFilters, null));
+
+    // Test Destroy Command.
+    command =
+        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
+    cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info("testCreateDestroyGatewaySenderWithGatewayEventFilters stringResult : "
+          + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail(
+          "testCreateDestroyGatewaySenderWithGatewayEventFilters failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderDestroyed("ln", false));
+    vm4.invoke(() -> verifySenderDestroyed("ln", false));
+    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+
+  }
+
+  /**
+   * GatewaySender with given attribute values and transport filters.
+   */
+  @Test
+  public void testCreateDestroyGatewaySenderWithGatewayTransportFilters() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__GATEWAYTRANSPORTFILTER
+        + "=org.apache.geode.cache30.MyGatewayTransportFilter1";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter()
+          .info("testCreateDestroyGatewaySenderWithGatewayTransportFilters stringResult : "
+              + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail(
+          "testCreateDestroyGatewaySenderWithGatewayTransportFilters failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderState("ln", false, false));
+    vm4.invoke(() -> verifySenderState("ln", false, false));
+    vm5.invoke(() -> verifySenderState("ln", false, false));
+
+    List<String> transportFilters = new ArrayList<String>();
+    transportFilters.add("org.apache.geode.cache30.MyGatewayTransportFilter1");
+    vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, transportFilters));
+    vm4.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, transportFilters));
+    vm5.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, transportFilters));
+
+    // Test Destroy Command.
+    command =
+        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
+    cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter()
+          .info("testCreateDestroyGatewaySenderWithGatewayTransportFilters stringResult : "
+              + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+
+    } else {
+      fail(
+          "testCreateDestroyGatewaySenderWithGatewayTransportFilters failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderDestroyed("ln", false));
+    vm4.invoke(() -> verifySenderDestroyed("ln", false));
+    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+  }
+
+  /**
+   * GatewaySender with given attribute values on given member.
+   */
+  @Test
+  public void testCreateDestroyGatewaySender_OnMember() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    final DistributedMember vm3Member = (DistributedMember) vm3.invoke(() -> getMember());
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__MEMBER + "=" + vm3Member.getId() + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter()
+          .info("testCreateDestroyGatewaySender_OnMember stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(1, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySender_OnMember failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderState("ln", false, false));
+
+    vm3.invoke(() -> verifySenderAttributes("ln", 2, false, true, 1000, socketReadTimeout, true,
+        1000, 5000, true, false, 1000, 100, 2, OrderPolicy.THREAD, null, null));
+
+    // Test Destroy Command.
+    command = CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__MEMBER + "=" + vm3Member.getId();
+    cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter()
+          .info("testCreateDestroyGatewaySender_OnMember stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(1, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+
+    } else {
+      fail("testCreateDestroyGatewaySender_OnMember failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderDestroyed("ln", false));
+  }
+
+  /**
+   * GatewaySender with given attribute values on given group
+   */
+  @Test
+  public void testCreateDestroyGatewaySender_Group() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
+    vm4.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
+    vm5.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__GROUP + "=SenderGroup1" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter()
+          .info("testCreateDestroyGatewaySender_Group stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(3, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySender_Group failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderState("ln", true, false));
+    vm4.invoke(() -> verifySenderState("ln", true, false));
+    vm5.invoke(() -> verifySenderState("ln", true, false));
+
+    // Test Destroy Command
+    command = CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.DESTROY_GATEWAYSENDER__GROUP + "=SenderGroup1";
+
+    cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter()
+          .info("testCreateDestroyGatewaySender_Group stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(3, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySender_Group failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderDestroyed("ln", false));
+    vm4.invoke(() -> verifySenderDestroyed("ln", false));
+    vm5.invoke(() -> verifySenderDestroyed("ln", false));
+
+  }
+
+  /**
+   * GatewaySender with given attribute values on given group. Only 2 of 3 members are part of the
+   * group.
+   */
+  @Test
+  public void testCreateDestroyGatewaySender_Group_Scenario2() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
+    vm4.invoke(() -> createCacheWithGroups(punePort, "SenderGroup1"));
+    vm5.invoke(() -> createCacheWithGroups(punePort, "SenderGroup2"));
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__GROUP + "=SenderGroup1" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info(
+          "testCreateDestroyGatewaySender_Group_Scenario2 stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(2, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySender_Group_Scenario2 failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderState("ln", true, false));
+    vm4.invoke(() -> verifySenderState("ln", true, false));
+
+
+    // Test Destroy Command
+    command = CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.DESTROY_GATEWAYSENDER__GROUP + "=SenderGroup1";
+
+    cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info(
+          "testCreateDestroyGatewaySender_Group_Scenario2 stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(2, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyGatewaySender_Group_Scenario2 failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderDestroyed("ln", false));
+    vm4.invoke(() -> verifySenderDestroyed("ln", false));
+
+  }
+
+  /**
+   * + * Parallel GatewaySender with given attribute values +
+   */
+  @Test
+  public void testCreateDestroyParallelGatewaySender() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter()
+          .info("testCreateDestroyParallelGatewaySender stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender creation failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+    } else {
+      fail("testCreateDestroyParallelGatewaySender failed as did not get CommandResult");
+    }
+
+    vm3.invoke(() -> verifySenderState("ln", false, false));
+    vm4.invoke(() -> verifySenderState("ln", false, false));
+    vm5.invoke(() -> verifySenderState("ln", false, false));
+
+    vm3.invoke(
+        () -> verifySenderAttributes("ln", 2, true, true, 1000, socketReadTimeout, true, 1000, 5000,
+            true, false, 1000, 100, GatewaySender.DEFAULT_DISPATCHER_THREADS, null, null, null));
+    vm4.invoke(
+        () -> verifySenderAttributes("ln", 2, true, true, 1000, socketReadTimeout, true, 1000, 5000,
+            true, false, 1000, 100, GatewaySender.DEFAULT_DISPATCHER_THREADS, null, null, null));
+    vm5.invoke(
+        () -> verifySenderAttributes("ln", 2, true, true, 1000, socketReadTimeout, true, 1000, 5000,
+            true, false, 1000, 100, GatewaySender.DEFAULT_DISPATCHER_THREADS, null, null, null));
+
+    // Test Destroy Command
+    command =
+        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
+    cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter()
+          .info("testCreateDestroyParallelGatewaySender stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy failed with: " + status.get(i),
+            status.get(i).indexOf("ERROR:") == -1);
+      }
+
+    } else {
+      fail("testCreateDestroyParallelGatewaySender failed as did not get CommandResult");
+    }
+    vm3.invoke(() -> verifySenderDestroyed("ln", true));
+    vm4.invoke(() -> verifySenderDestroyed("ln", true));
+    vm5.invoke(() -> verifySenderDestroyed("ln", true));
+  }
+
+  /**
+   * Parallel GatewaySender with given attribute values. Provide dispatcherThreads as 2 which is not
+   * valid for Parallel sender.
+   */
+  @Test
+  public void testCreateParallelGatewaySender_Error() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    int socketReadTimeout = GatewaySender.MINIMUM_SOCKET_READ_TIMEOUT + 1000;
+    String command = CliStrings.CREATE_GATEWAYSENDER + " --" + CliStrings.CREATE_GATEWAYSENDER__ID
+        + "=ln" + " --" + CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__PARALLEL + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MANUALSTART + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETBUFFERSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__SOCKETREADTIMEOUT + "=" + socketReadTimeout + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEBATCHCONFLATION + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHSIZE + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__BATCHTIMEINTERVAL + "=5000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ENABLEPERSISTENCE + "=true" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISKSYNCHRONOUS + "=false" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__MAXQUEUEMEMORY + "=1000" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ALERTTHRESHOLD + "=100" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS + "=2" + " --"
+        + CliStrings.CREATE_GATEWAYSENDER__ORDERPOLICY + "=THREAD";
+    IgnoredException exp =
+        IgnoredException.addIgnoredException(GatewaySenderException.class.getName());
+    try {
+      CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+      if (cmdResult != null) {
+        String strCmdResult = commandResultToString(cmdResult);
+        getLogWriter()
+            .info("testCreateParallelGatewaySender_Error stringResult : " + strCmdResult + ">>>>");
+        assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+        TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+        List<String> status = resultData.retrieveAllValues("Status");
+        assertEquals(5, status.size());
+        for (int i = 0; i < status.size(); i++) {
+          assertTrue("GatewaySender creation should have failed",
+              status.get(i).indexOf("ERROR:") != -1);
+        }
+      } else {
+        fail("testCreateParallelGatewaySender_Error failed as did not get CommandResult");
+      }
+    } finally {
+      exp.remove();
+    }
+
+  }
+
+  @Test
+  public void testDestroyGatewaySender_NotCreatedSender() {
+
+    Integer punePort = (Integer) vm1.invoke(() -> createFirstLocatorWithDSId(1));
+
+    Properties props = getDistributedSystemProperties();
+    props.setProperty(MCAST_PORT, "0");
+    props.setProperty(DISTRIBUTED_SYSTEM_ID, "1");
+    props.setProperty(LOCATORS, "localhost[" + punePort + "]");
+    setUpJmxManagerOnVm0ThenConnect(props);
+
+    Integer nyPort = (Integer) vm2.invoke(() -> createFirstRemoteLocator(2, punePort));
+
+    vm3.invoke(() -> createCache(punePort));
+    vm4.invoke(() -> createCache(punePort));
+    vm5.invoke(() -> createCache(punePort));
+
+    // Test Destroy Command
+    String command =
+        CliStrings.DESTROY_GATEWAYSENDER + " --" + CliStrings.DESTROY_GATEWAYSENDER__ID + "=ln";
+    CommandResult cmdResult = executeCommandWithIgnoredExceptions(command);
+    if (cmdResult != null) {
+      String strCmdResult = commandResultToString(cmdResult);
+      getLogWriter().info(
+          "testDestroyGatewaySender_NotCreatedSender stringResult : " + strCmdResult + ">>>>");
+      assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+      TabularResultData resultData = (TabularResultData) cmdResult.getResultData();
+      List<String> status = resultData.retrieveAllValues("Status");
+      assertEquals(5, status.size());
+      for (int i = 0; i < status.size(); i++) {
+        assertTrue("GatewaySender destroy should fail", status.get(i).indexOf("ERROR:") != -1);
+      }
+
+    } else {
+      fail("testCreateDestroyParallelGatewaySender failed as did not get CommandResult");
+    }
+  }
+}


[24/50] [abbrv] geode git commit: GEODE-2186: Changing the gateway status to only looking running status

Posted by kl...@apache.org.
GEODE-2186: Changing the gateway status to only looking running status

Gateway senders may or may not be connected, depending on what is going
on with the underlying queue. If a sender is a secondary, it may be
disconnected because it doesn't need to send anything. Even primaries
may be disconnected for periods of time if the connection is lost when
there is nothing in the queue.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 09184881aec9250fdf2e96f4fced4dedaac0bda7
Parents: adfd41f
Author: Dan Smith <up...@apache.org>
Authored: Tue Dec 6 16:52:24 2016 -0800
Committer: Dan Smith <up...@apache.org>
Committed: Fri Dec 9 11:11:26 2016 -0800

----------------------------------------------------------------------
 .../internal/beans/DistributedSystemBridge.java     |  4 +---
 .../geode/management/WANManagementDUnitTest.java    | 16 +++++++---------
 2 files changed, 8 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/09184881/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemBridge.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemBridge.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemBridge.java
index 3016277..5b8c115 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemBridge.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemBridge.java
@@ -1566,10 +1566,8 @@ public class DistributedSystemBridge {
         GatewaySenderMXBean bean = it.next();
         Integer dsId = bean.getRemoteDSId();
         if (dsId != null) {
-          senderMap.put(dsId.toString(), bean.isConnected());
+          senderMap.merge(dsId.toString(), bean.isRunning(), Boolean::logicalAnd);
         }
-
-
       }
 
       return senderMap;

http://git-wip-us.apache.org/repos/asf/geode/blob/09184881/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java
index 3cc37eb..dc801be 100644
--- a/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java
+++ b/geode-wan/src/test/java/org/apache/geode/management/WANManagementDUnitTest.java
@@ -38,7 +38,6 @@ import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.cache.wan.WANTestBase;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.LogWriterUtils;
 import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 
@@ -54,9 +53,6 @@ public class WANManagementDUnitTest extends ManagementTestBase {
 
   private static final long serialVersionUID = 1L;
 
-
-  public static MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-
   public WANManagementDUnitTest() throws Exception {
     super();
   }
@@ -91,6 +87,7 @@ public class WANManagementDUnitTest extends ManagementTestBase {
     managing.invoke(() -> WANTestBase.createManagementCache(punePort));
     startManagingNode(managing);
 
+
     // keep a larger batch to minimize number of exception occurrences in the
     // log
     puneSender
@@ -104,6 +101,7 @@ public class WANManagementDUnitTest extends ManagementTestBase {
     managing.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "pn", 1,
         100, false));
 
+
     nyReceiver.invoke(() -> WANTestBase.createCache(nyPort));
     nyReceiver.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null,
         1, 100, false));
@@ -314,11 +312,11 @@ public class WANManagementDUnitTest extends ManagementTestBase {
 
         if (service.isManager()) {
           DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
-          Map<String, Boolean> dsMap = dsBean.viewRemoteClusterStatus();
-
-          LogWriterUtils.getLogWriter()
-              .info("<ExpectedString> Ds Map is: " + dsMap + "</ExpectedString> ");
-
+          Awaitility.await().atMost(1, TimeUnit.MINUTES).until(() -> {
+            Map<String, Boolean> dsMap = dsBean.viewRemoteClusterStatus();
+            dsMap.entrySet().stream()
+                .forEach(entry -> assertTrue("Should be true " + entry.getKey(), entry.getValue()));
+          });
         }
 
       }


[26/50] [abbrv] geode git commit: GEODE-2193 a member is kicked out immediately after joining

Posted by kl...@apache.org.
GEODE-2193 a member is kicked out immediately after joining

The problem is happening because we send a shutdown message, initiating
election of a new coordinator, but the old ViewCreator is allowed to
send out a view announcing a new member.  The new coordinator manages
to send out a new view before the old ViewCreator sends out the new
member's view.  Other members ignore the old ViewCreator's view
because its view ID is old.  Then the reject the new member because
it has an old view ID and it isn't in their membership view.

initial view ID is x

new coordinator prepares view x+10
old coordinator prepares view x+1
other members install x+10, reject view x+1
new member joins in view x+1 when it receives view-prepare message
new member is rejected by other members because x+1 < x+10


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

Branch: refs/heads/feature/GEODE-1930
Commit: ef86239f872c12c0aad38d5ae3044e22fd5e87af
Parents: ac3a822
Author: Bruce Schuchardt <bs...@pivotal.io>
Authored: Fri Dec 9 14:01:46 2016 -0800
Committer: Bruce Schuchardt <bs...@pivotal.io>
Committed: Fri Dec 9 14:01:46 2016 -0800

----------------------------------------------------------------------
 .../membership/gms/membership/GMSJoinLeave.java | 86 ++++++++++++--------
 .../gms/messages/JoinResponseMessage.java       |  7 ++
 .../geode/distributed/LocatorJUnitTest.java     |  3 +
 .../gms/membership/GMSJoinLeaveJUnitTest.java   | 67 +++++++++++++--
 4 files changed, 119 insertions(+), 44 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/ef86239f/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeave.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeave.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeave.java
index 6d782b1..4ee3011 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeave.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeave.java
@@ -803,13 +803,6 @@ public class GMSJoinLeave implements JoinLeave, MessageHandler {
     return newView;
   }
 
-  private void sendJoinResponses(NetView newView, List<InternalDistributedMember> newMbrs) {
-    for (InternalDistributedMember mbr : newMbrs) {
-      JoinResponseMessage response = new JoinResponseMessage(mbr, newView, 0);
-      services.getMessenger().send(response);
-    }
-  }
-
   private void sendRemoveMessages(List<InternalDistributedMember> removals, List<String> reasons,
       Set<InternalDistributedMember> oldIds) {
     Iterator<String> reason = reasons.iterator();
@@ -826,11 +819,19 @@ public class GMSJoinLeave implements JoinLeave, MessageHandler {
 
   boolean prepareView(NetView view, List<InternalDistributedMember> newMembers)
       throws InterruptedException {
+    if (services.getCancelCriterion().isCancelInProgress()
+        || services.getManager().shutdownInProgress()) {
+      throw new InterruptedException("shutting down");
+    }
     return sendView(view, true, this.prepareProcessor);
   }
 
   void sendView(NetView view, List<InternalDistributedMember> newMembers)
       throws InterruptedException {
+    if (services.getCancelCriterion().isCancelInProgress()
+        || services.getManager().shutdownInProgress()) {
+      throw new InterruptedException("shutting down");
+    }
     sendView(view, false, this.viewProcessor);
   }
 
@@ -1401,7 +1402,9 @@ public class GMSJoinLeave implements JoinLeave, MessageHandler {
           for (Iterator<DistributionMessage> it = viewRequests.iterator(); it.hasNext();) {
             DistributionMessage m = it.next();
             if (m instanceof JoinRequestMessage) {
-              it.remove();
+              if (currentView.contains(((JoinRequestMessage) m).getMemberID())) {
+                it.remove();
+              }
             } else if (m instanceof LeaveRequestMessage) {
               if (!currentView.contains(((LeaveRequestMessage) m).getMemberID())) {
                 it.remove();
@@ -1500,6 +1503,11 @@ public class GMSJoinLeave implements JoinLeave, MessageHandler {
     if (viewCreator != null && !viewCreator.isShutdown()) {
       logger.debug("Shutting down ViewCreator");
       viewCreator.shutdown();
+      try {
+        viewCreator.join(1000);
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+      }
     }
   }
 
@@ -1641,8 +1649,6 @@ public class GMSJoinLeave implements JoinLeave, MessageHandler {
     services.getMessenger().addHandler(ViewAckMessage.class, this);
     services.getMessenger().addHandler(LeaveRequestMessage.class, this);
     services.getMessenger().addHandler(RemoveMemberMessage.class, this);
-    services.getMessenger().addHandler(JoinRequestMessage.class, this);
-    services.getMessenger().addHandler(JoinResponseMessage.class, this);
     services.getMessenger().addHandler(FindCoordinatorRequest.class, this);
     services.getMessenger().addHandler(FindCoordinatorResponse.class, this);
     services.getMessenger().addHandler(NetworkPartitionMessage.class, this);
@@ -2133,40 +2139,48 @@ public class GMSJoinLeave implements JoinLeave, MessageHandler {
     }
 
     synchronized boolean informToPendingJoinRequests() {
-      boolean joinResponseSent = false;
+
       if (!shutdown) {
-        return joinResponseSent;
+        return false;
       }
-      ArrayList<DistributionMessage> requests = new ArrayList<>();
+      NetView v = currentView;
+      if (v.getCoordinator().equals(localAddress)) {
+        return false;
+      }
+
+      ArrayList<JoinRequestMessage> requests = new ArrayList<>();
       synchronized (viewRequests) {
-        if (viewRequests.size() > 0) {
-          requests.addAll(viewRequests);
-        } else {
-          return joinResponseSent;
+        if (viewRequests.isEmpty()) {
+          return false;
+        }
+        for (Iterator<DistributionMessage> iterator = viewRequests.iterator(); iterator
+            .hasNext();) {
+          DistributionMessage msg = iterator.next();
+          switch (msg.getDSFID()) {
+            case JOIN_REQUEST:
+              requests.add((JoinRequestMessage) msg);
+              // TODO [bruce] if the view creator is just spinning up I don't think we should do
+              // this remove
+              iterator.remove();
+              break;
+            default:
+              break;
+          }
         }
-        viewRequests.clear();
       }
 
-      NetView v = currentView;
-      for (DistributionMessage msg : requests) {
-        switch (msg.getDSFID()) {
-          case JOIN_REQUEST:
-            logger.debug("Informing to pending join requests {} myid {} coord {}", msg,
-                localAddress, v.getCoordinator());
-            if (!v.getCoordinator().equals(localAddress)) {
-              joinResponseSent = true;
-              // lets inform that coordinator has been changed
-              JoinResponseMessage jrm =
-                  new JoinResponseMessage(((JoinRequestMessage) msg).getMemberID(), v,
-                      ((JoinRequestMessage) msg).getRequestId());
-              services.getMessenger().send(jrm);
-            }
-          default:
-            break;
-        }
+      if (requests.isEmpty()) {
+        return false;
+      }
+
+      for (JoinRequestMessage msg : requests) {
+        logger.debug("Sending coordinator to pending join request from {} myid {} coord {}",
+            msg.getSender(), localAddress, v.getCoordinator());
+        JoinResponseMessage jrm = new JoinResponseMessage(msg.getMemberID(), v, msg.getRequestId());
+        services.getMessenger().send(jrm);
       }
 
-      return joinResponseSent;
+      return true;
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/geode/blob/ef86239f/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/messages/JoinResponseMessage.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/messages/JoinResponseMessage.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/messages/JoinResponseMessage.java
index 2a13a5e..4e0bcc8 100755
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/messages/JoinResponseMessage.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/messages/JoinResponseMessage.java
@@ -30,6 +30,13 @@ import org.apache.geode.distributed.internal.membership.NetView;
 import org.apache.geode.internal.InternalDataSerializer;
 import org.apache.geode.internal.Version;
 
+// TODO this class has been made unintelligible with different combinations of response values.
+// It needs to have an enum that indicates what type of response is in the message or it
+// needs to be broken into multiple message classes.
+// 1. a response saying the member has now joined
+// 2. a response indicating that the coordinator is now a different process
+// 3. a response containing the cluster encryption key
+
 public class JoinResponseMessage extends HighPriorityDistributionMessage {
 
   private NetView currentView;

http://git-wip-us.apache.org/repos/asf/geode/blob/ef86239f/geode-core/src/test/java/org/apache/geode/distributed/LocatorJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/LocatorJUnitTest.java b/geode-core/src/test/java/org/apache/geode/distributed/LocatorJUnitTest.java
index 368b037..8be0e7a 100644
--- a/geode-core/src/test/java/org/apache/geode/distributed/LocatorJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/LocatorJUnitTest.java
@@ -108,6 +108,7 @@ public class LocatorJUnitTest {
     dsprops.setProperty(JMX_MANAGER_START, "true");
     dsprops.setProperty(JMX_MANAGER_HTTP_PORT, "0");
     dsprops.setProperty(ENABLE_CLUSTER_CONFIGURATION, "false");
+    dsprops.setProperty(LOG_FILE, "");
     System.setProperty(DistributionConfig.GEMFIRE_PREFIX + "disableManagement", "false"); // not
                                                                                           // needed
     try {
@@ -159,6 +160,8 @@ public class LocatorJUnitTest {
         fail("expected " + threadCount + " threads or fewer but found " + Thread.activeCount()
             + ".  Check log file for a thread dump.");
       }
+    } finally {
+      JGroupsMessenger.THROW_EXCEPTION_ON_START_HOOK = false;
     }
   }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/ef86239f/geode-core/src/test/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeaveJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeaveJUnitTest.java b/geode-core/src/test/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeaveJUnitTest.java
index 453e894..14fedc6 100644
--- a/geode-core/src/test/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeaveJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/internal/membership/gms/membership/GMSJoinLeaveJUnitTest.java
@@ -14,6 +14,20 @@
  */
 package org.apache.geode.distributed.internal.membership.gms.membership;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.isA;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.jayway.awaitility.Awaitility;
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.internal.DistributionConfig;
 import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
@@ -32,10 +46,15 @@ import org.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLe
 import org.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLeave.TcpClientWrapper;
 import org.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLeave.ViewCreator;
 import org.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLeave.ViewReplyProcessor;
-import org.apache.geode.distributed.internal.membership.gms.messages.*;
+import org.apache.geode.distributed.internal.membership.gms.messages.InstallViewMessage;
+import org.apache.geode.distributed.internal.membership.gms.messages.JoinRequestMessage;
+import org.apache.geode.distributed.internal.membership.gms.messages.JoinResponseMessage;
+import org.apache.geode.distributed.internal.membership.gms.messages.LeaveRequestMessage;
+import org.apache.geode.distributed.internal.membership.gms.messages.NetworkPartitionMessage;
+import org.apache.geode.distributed.internal.membership.gms.messages.RemoveMemberMessage;
+import org.apache.geode.distributed.internal.membership.gms.messages.ViewAckMessage;
 import org.apache.geode.internal.Version;
 import org.apache.geode.security.AuthenticationFailedException;
-import org.apache.geode.test.junit.categories.FlakyTest;
 import org.apache.geode.test.junit.categories.IntegrationTest;
 import org.apache.geode.test.junit.categories.MembershipTest;
 import org.junit.After;
@@ -50,12 +69,16 @@ import org.mockito.verification.Timeout;
 import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.net.UnknownHostException;
-import java.util.*;
-
-import static org.junit.Assert.*;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.isA;
-import static org.mockito.Mockito.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.Timer;
+import java.util.concurrent.TimeUnit;
 
 @Category({IntegrationTest.class, MembershipTest.class})
 public class GMSJoinLeaveJUnitTest {
@@ -1062,6 +1085,34 @@ public class GMSJoinLeaveJUnitTest {
   }
 
   @Test
+  public void testViewNotSentWhenShuttingDown() throws Exception {
+    try {
+      initMocks(false);
+      System.setProperty(GMSJoinLeave.BYPASS_DISCOVERY_PROPERTY, "true");
+      gmsJoinLeave.join();
+      installView(1, gmsJoinLeaveMemberId, createMemberList(mockMembers[0], mockMembers[1],
+          mockMembers[2], gmsJoinLeaveMemberId, mockMembers[3]));
+
+      assertTrue(gmsJoinLeave.getViewCreator().isAlive());
+
+      when(manager.shutdownInProgress()).thenReturn(Boolean.TRUE);
+      for (int i = 1; i < 4; i++) {
+        RemoveMemberMessage msg =
+            new RemoveMemberMessage(gmsJoinLeaveMemberId, mockMembers[i], "crashed");
+        msg.setSender(gmsJoinLeaveMemberId);
+        gmsJoinLeave.processMessage(msg);
+      }
+
+      Awaitility.await("waiting for view creator to stop").atMost(5000, TimeUnit.MILLISECONDS)
+          .until(() -> !gmsJoinLeave.getViewCreator().isAlive());
+      assertEquals(1, gmsJoinLeave.getView().getViewId());
+
+    } finally {
+      System.getProperties().remove(GMSJoinLeave.BYPASS_DISCOVERY_PROPERTY);
+    }
+  }
+
+  @Test
   public void testPreparedViewFoundDuringBecomeCoordinator() throws Exception {
     initMocks(false);
     prepareAndInstallView(gmsJoinLeaveMemberId,


[28/50] [abbrv] geode git commit: GEODE-2201 Spotless fix

Posted by kl...@apache.org.
GEODE-2201 Spotless fix


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

Branch: refs/heads/feature/GEODE-1930
Commit: 0f8ef971b8f18bd144646e98468816df88d1d0c9
Parents: df8730d
Author: Jens Deppe <jd...@pivotal.io>
Authored: Sun Dec 11 21:11:08 2016 -0800
Committer: Jens Deppe <jd...@pivotal.io>
Committed: Sun Dec 11 21:11:08 2016 -0800

----------------------------------------------------------------------
 .../java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/0f8ef971/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java
index 076229e..ce91202 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java
@@ -63,7 +63,7 @@ public final class PulseTestUtils {
 
   public static WebElement waitForElement(By by) {
     WebElement element = (new WebDriverWait(driverProvider.get(), maxWaitTime))
-      .until((ExpectedCondition<WebElement>) d -> d.findElement(by));
+        .until((ExpectedCondition<WebElement>) d -> d.findElement(by));
     assertNotNull(element);
     return element;
   }


[38/50] [abbrv] geode git commit: GEODE-1975: add FlakyTest category to flaky test

Posted by kl...@apache.org.
GEODE-1975: add FlakyTest category to flaky test


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

Branch: refs/heads/feature/GEODE-1930
Commit: da00dbd280cdff33e2915af79e52548137eb346a
Parents: e81ad7c
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Dec 12 18:04:19 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 18:04:19 2016 -0800

----------------------------------------------------------------------
 .../org/apache/geode/security/SecurityClusterConfigDUnitTest.java   | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/da00dbd2/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
index 10b12e5..9ce8262 100644
--- a/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
@@ -105,6 +105,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
     assertTrue(secProps.containsKey("security-post-processor"));
   }
 
+  @Category(FlakyTest.class) // GEODE-1975
   @Test
   public void serverWithDifferentSecurityManagerShouldThrowException() {
     Properties props = new Properties();


[16/50] [abbrv] geode git commit: GEODE-2192 Fixed NPE in GMSLocator. Added null check for publickey

Posted by kl...@apache.org.
GEODE-2192 Fixed NPE in GMSLocator. Added null check for publickey


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

Branch: refs/heads/feature/GEODE-1930
Commit: f22809a448ba5ab177be0d1d790f0ec91801d0f0
Parents: 2075ee3
Author: Hitesh Khamesra <hk...@pivotal.io>
Authored: Thu Dec 8 13:40:34 2016 -0800
Committer: Hitesh Khamesra <hk...@pivotal.io>
Committed: Thu Dec 8 13:40:34 2016 -0800

----------------------------------------------------------------------
 .../internal/membership/gms/locator/GMSLocator.java         | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/f22809a4/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/locator/GMSLocator.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/locator/GMSLocator.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/locator/GMSLocator.java
index 25cb50f..dd73492 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/locator/GMSLocator.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/membership/gms/locator/GMSLocator.java
@@ -188,9 +188,12 @@ public class GMSLocator implements Locator, NetLocator {
         services.getMessenger().setPublicKey(findRequest.getMyPublicKey(),
             findRequest.getMemberID());
       } else {
-        // GMSEncrypt.registerMember(findRequest.getMyPublicKey(), findRequest.getMemberID());
-        registerMbrVsPK.put(new InternalDistributedMemberWrapper(findRequest.getMemberID()),
-            findRequest.getMyPublicKey());
+        // GMSEncrypt.registerMember(findRequest.getMyPublicKey(),
+        // findRequest.getMemberID());
+        if (findRequest.getMyPublicKey() != null) {
+          registerMbrVsPK.put(new InternalDistributedMemberWrapper(findRequest.getMemberID()),
+              findRequest.getMyPublicKey());
+        }
       }
       if (findRequest.getMemberID() != null) {
         InternalDistributedMember coord = null;


[04/50] [abbrv] geode git commit: GEODE-2182: try-catch around size estimation for index look ups

Posted by kl...@apache.org.
GEODE-2182: try-catch around size estimation for index look ups

* Fix possible race condition where entry is destroyed


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

Branch: refs/heads/feature/GEODE-1930
Commit: c2b1c8b1c172073824a8e5c48c45a4285f15e6b1
Parents: ef96dba
Author: Jason Huynh <hu...@gmail.com>
Authored: Mon Dec 5 13:53:22 2016 -0800
Committer: Jason Huynh <hu...@gmail.com>
Committed: Wed Dec 7 09:28:38 2016 -0800

----------------------------------------------------------------------
 .../query/internal/index/CompactRangeIndex.java |  2 +
 .../query/internal/index/MemoryIndexStore.java  | 12 ++-
 .../functional/IndexOnEntrySetJUnitTest.java    | 89 ++++++++++++++------
 3 files changed, 68 insertions(+), 35 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/c2b1c8b1/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/CompactRangeIndex.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/CompactRangeIndex.java b/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/CompactRangeIndex.java
index a8a38bd..80568f5 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/CompactRangeIndex.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/CompactRangeIndex.java
@@ -437,6 +437,8 @@ public class CompactRangeIndex extends AbstractIndex {
           }
           break;
       }
+    } catch (EntryDestroyedException e) {
+      return Integer.MAX_VALUE;
     } finally {
       updateIndexUseEndStats(start, false);
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/c2b1c8b1/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/MemoryIndexStore.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/MemoryIndexStore.java b/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/MemoryIndexStore.java
index 3635897..e9cd070 100644
--- a/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/MemoryIndexStore.java
+++ b/geode-core/src/main/java/org/apache/geode/cache/query/internal/index/MemoryIndexStore.java
@@ -247,10 +247,7 @@ public class MemoryIndexStore implements IndexStore {
    * Find the old key by traversing the forward map in case of in-place update modification If not
    * found it means the value object was modified with same value. So oldKey is same as newKey.
    * 
-   * @param newKey
-   * @param entry
    * @return oldKey
-   * @throws TypeMismatchException
    */
   private Object getOldKey(Object newKey, RegionEntry entry) throws TypeMismatchException {
     for (Object mapEntry : valueToEntriesMap.entrySet()) {
@@ -406,7 +403,6 @@ public class MemoryIndexStore implements IndexStore {
    * RegionEntry) { return Collections.singleton(regionEntries); } return (Collection)
    * regionEntries; }
    */
-
   @Override
   public CloseableIterator<IndexStoreEntry> get(Object indexKey) {
     return new MemoryIndexStoreIterator(
@@ -574,7 +570,6 @@ public class MemoryIndexStore implements IndexStore {
   /**
    * A bi-directional iterator over the CSL. Iterates over the entries of CSL where entry is a
    * mapping (value -> Collection) as well as over the Collection.
-   * 
    */
   private class MemoryIndexStoreIterator implements CloseableIterator<IndexStoreEntry> {
     final Map map;
@@ -662,8 +657,9 @@ public class MemoryIndexStore implements IndexStore {
       }
 
       RegionEntry re = (RegionEntry) valuesIterator.next();
-      if (re == null)
+      if (re == null) {
         throw new NoSuchElementException();
+      }
 
       currentEntry.setMemoryIndexStoreEntry(currKey, re);
       return currentEntry;
@@ -718,7 +714,6 @@ public class MemoryIndexStore implements IndexStore {
 
   /**
    * A wrapper over the entry in the CSL index map. It maps IndexKey -> RegionEntry
-   * 
    */
   class MemoryIndexStoreEntry implements IndexStoreEntry {
     private Object deserializedIndexKey;
@@ -771,6 +766,9 @@ public class MemoryIndexStore implements IndexStore {
     private Object key, value;
 
     public CachedEntryWrapper(LocalRegion.NonTXEntry entry) {
+      if (IndexManager.testHook != null) {
+        IndexManager.testHook.hook(201);
+      }
       this.key = entry.getKey();
       this.value = entry.getValue();
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/c2b1c8b1/geode-core/src/test/java/org/apache/geode/cache/query/functional/IndexOnEntrySetJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache/query/functional/IndexOnEntrySetJUnitTest.java b/geode-core/src/test/java/org/apache/geode/cache/query/functional/IndexOnEntrySetJUnitTest.java
index 6034d53..f659836 100644
--- a/geode-core/src/test/java/org/apache/geode/cache/query/functional/IndexOnEntrySetJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/cache/query/functional/IndexOnEntrySetJUnitTest.java
@@ -14,6 +14,10 @@
  */
 package org.apache.geode.cache.query.functional;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
 import org.apache.geode.cache.*;
 import org.apache.geode.cache.query.*;
 import org.apache.geode.cache.query.internal.QueryObserverAdapter;
@@ -91,7 +95,15 @@ public class IndexOnEntrySetJUnitTest {
   public void testQueriesOnReplicatedRegion() throws Exception {
     testRegion = createReplicatedRegion(testRegionName);
     String regionPath = "/" + testRegionName + ".entrySet entry";
-    executeQueryTest(getQueriesOnRegion(testRegionName), "entry.key.Index", regionPath);
+    executeQueryTest(getQueriesOnRegion(testRegionName), "entry.key.Index", regionPath, 200);
+  }
+
+  @Test
+  public void testEntryDestroyedRaceWithSizeEstimateReplicatedRegion() throws Exception {
+    testRegion = createReplicatedRegion(testRegionName);
+    String regionPath = "/" + testRegionName + ".entrySet entry";
+    executeQueryTestDestroyDuringSizeEstimation(getQueriesOnRegion(testRegionName),
+        "entry.key.Index", regionPath, 201);
   }
 
   /**
@@ -102,7 +114,7 @@ public class IndexOnEntrySetJUnitTest {
   public void testQueriesOnPartitionedRegion() throws Exception {
     testRegion = createPartitionedRegion(testRegionName);
     String regionPath = "/" + testRegionName + ".entrySet entry";
-    executeQueryTest(getQueriesOnRegion(testRegionName), "entry.key.Index", regionPath);
+    executeQueryTest(getQueriesOnRegion(testRegionName), "entry.key.Index", regionPath, 200);
   }
 
   private Region createReplicatedRegion(String regionName) throws ParseException {
@@ -140,24 +152,26 @@ public class IndexOnEntrySetJUnitTest {
     }
   }
 
-  /**** Query Execution Helpers ****/
+  /****
+   * Query Execution Helpers
+   ****/
 
-  private void executeQueryTest(String[] queries, String indexedExpression, String regionPath)
-      throws Exception {
+  private void executeQueryTest(String[] queries, String indexedExpression, String regionPath,
+      int testHookSpot) throws Exception {
     Cache cache = CacheUtils.getCache();
     boolean[] booleanVals = {true, false};
     for (String query : queries) {
       for (boolean isDestroy : booleanVals) {
         clearData(testRegion);
         populateRegion(testRegion);
-        Assert.assertNotNull(cache.getRegion(testRegionName));
-        Assert.assertEquals(numElem, cache.getRegion(testRegionName).size());
+        assertNotNull(cache.getRegion(testRegionName));
+        assertEquals(numElem, cache.getRegion(testRegionName).size());
         if (isDestroy) {
           helpTestFunctionalIndexForQuery(query, indexedExpression, regionPath,
-              new DestroyEntryTestHook(testRegion));
+              new DestroyEntryTestHook(testRegion, testHookSpot), 1);
         } else {
           helpTestFunctionalIndexForQuery(query, indexedExpression, regionPath,
-              new InvalidateEntryTestHook(testRegion));
+              new InvalidateEntryTestHook(testRegion, testHookSpot), 1);
         }
       }
     }
@@ -166,22 +180,18 @@ public class IndexOnEntrySetJUnitTest {
     for (String query : queries) {
       clearData(testRegion);
       populateRegion(testRegion);
-      Assert.assertNotNull(cache.getRegion(testRegionName));
-      Assert.assertEquals(numElem, cache.getRegion(testRegionName).size());
+      assertNotNull(cache.getRegion(testRegionName));
+      assertEquals(numElem, cache.getRegion(testRegionName).size());
       helpTestFunctionalIndexForQuery(query, indexedExpression, regionPath,
-          new PutEntryTestHook(testRegion));
+          new PutEntryTestHook(testRegion, testHookSpot), 1);
     }
   }
 
   /**
    * helper method to test against a functional index make sure there is no UNDEFINED result
-   * 
-   * @param query
-   * 
-   * @throws Exception
    */
   private SelectResults helpTestFunctionalIndexForQuery(String query, String indexedExpression,
-      String regionPath, AbstractTestHook testHook) throws Exception {
+      String regionPath, AbstractTestHook testHook, int expectedSize) throws Exception {
     MyQueryObserverAdapter observer = new MyQueryObserverAdapter();
     QueryObserverHolder.setInstance(observer);
     IndexManager.testHook = testHook;
@@ -194,27 +204,40 @@ public class IndexOnEntrySetJUnitTest {
       if (row instanceof Struct) {
         Object[] fields = ((Struct) row).getFieldValues();
         for (Object field : fields) {
-          Assert.assertTrue(field != QueryService.UNDEFINED);
+          assertTrue(field != QueryService.UNDEFINED);
           if (field instanceof String) {
-            Assert.assertTrue(((String) field).compareTo(newValue) != 0);
+            assertTrue(((String) field).compareTo(newValue) != 0);
           }
         }
       } else {
-        Assert.assertTrue(row != QueryService.UNDEFINED);
+        assertTrue(row != QueryService.UNDEFINED);
         if (row instanceof String) {
-          Assert.assertTrue(((String) row).compareTo(newValue) != 0);
+          assertTrue(((String) row).compareTo(newValue) != 0);
         }
       }
     }
-    Assert.assertTrue(indexedResults.size() > 0);
-    Assert.assertTrue(observer.indexUsed);
-    Assert.assertTrue(((AbstractTestHook) IndexManager.testHook).isTestHookCalled());
+    assertTrue(indexedResults.size() >= expectedSize);
+    assertTrue(observer.indexUsed);
+    assertTrue(((AbstractTestHook) IndexManager.testHook).isTestHookCalled());
     ((AbstractTestHook) IndexManager.testHook).reset();
     qs.removeIndex(index);
 
     return indexedResults;
   }
 
+  private void executeQueryTestDestroyDuringSizeEstimation(String[] queries,
+      String indexedExpression, String regionPath, int testHookSpot) throws Exception {
+    Cache cache = CacheUtils.getCache();
+    for (String query : queries) {
+      clearData(testRegion);
+      populateRegion(testRegion);
+      assertNotNull(cache.getRegion(testRegionName));
+      assertEquals(numElem, cache.getRegion(testRegionName).size());
+      helpTestFunctionalIndexForQuery(query, indexedExpression, regionPath,
+          new DestroyEntryTestHook(testRegion, testHookSpot), 0);
+    }
+  }
+
   class MyQueryObserverAdapter extends QueryObserverAdapter {
     public boolean indexUsed = false;
 
@@ -255,6 +278,12 @@ public class IndexOnEntrySetJUnitTest {
     Object waitObj = new Object();
     Region r;
 
+    private int testHookSpot;
+
+    public AbstractTestHook(int testHookSpot) {
+      this.testHookSpot = testHookSpot;
+    }
+
     public void reset() {
       isTestHookCalled = false;
     }
@@ -270,7 +299,7 @@ public class IndexOnEntrySetJUnitTest {
 
     @Override
     public void hook(int spot) throws RuntimeException {
-      if (spot == 200) {
+      if (spot == testHookSpot) {
         if (!isTestHookCalled) {
           isTestHookCalled = true;
           try {
@@ -297,7 +326,9 @@ public class IndexOnEntrySetJUnitTest {
 
   class DestroyEntryTestHook extends AbstractTestHook {
 
-    DestroyEntryTestHook(Region r) {
+    DestroyEntryTestHook(Region r, int testHookSpot) {
+
+      super(testHookSpot);
       this.r = r;
     }
 
@@ -312,7 +343,8 @@ public class IndexOnEntrySetJUnitTest {
 
   class InvalidateEntryTestHook extends AbstractTestHook {
 
-    InvalidateEntryTestHook(Region r) {
+    InvalidateEntryTestHook(Region r, int testHookSpot) {
+      super(testHookSpot);
       this.r = r;
     }
 
@@ -327,7 +359,8 @@ public class IndexOnEntrySetJUnitTest {
 
   class PutEntryTestHook extends AbstractTestHook {
 
-    PutEntryTestHook(Region r) {
+    PutEntryTestHook(Region r, int testHookSpot) {
+      super(testHookSpot);
       this.r = r;
     }
 


[47/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 336a6b1..a574815 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
@@ -14,54 +14,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);
   }
 
   /**
@@ -69,46 +97,54 @@ 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();
   }
 
   /**
@@ -116,262 +152,204 @@ 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);
-
-    Host host = Host.getHost(0);
-    String host0 = getServerHostName(host);
+    startLocator(this.locatorVM, true, this.port);
 
     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") {
+  private int startLocator(final VM locatorVM, final boolean isPeer, final int port) {
+    return locatorVM.invoke("startLocator", () -> {
+      assertThat(InternalLocator.hasLocator()).isFalse();
 
-      public Object call() throws Exception {
+      Properties properties = new Properties();
+      properties.setProperty(MCAST_PORT, "0");
+      properties.setProperty(LOCATORS, "");
 
-        assertFalse(InternalLocator.hasLocator());
+      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);
 
-        Properties props = new Properties();
-        props.setProperty(MCAST_PORT, "0");
+      assertThat(InternalLocator.hasLocator()).isTrue();
 
-        props.setProperty(LOCATORS, "");
-        props.setProperty(LOG_LEVEL, LogWriterUtils.getDUnitLogLevel());
-
-        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);
-        }
-
-        assertTrue(InternalLocator.hasLocator());
-        return locator.getPort();
-      }
+      return locator.getPort();
     });
   }
 
-  /**
-   * Creates a persistent region
-   * 
-   * @param vm reference to VM
-   */
-  protected String stopLocator(VM vm) {
+  private void stopLocator(final VM locatorVM) {
+    locatorVM.invoke("stopLocator", () -> {
+      assertThat(InternalLocator.hasLocator()).isTrue();
+      InternalLocator.getLocator().stop();
+    });
+  }
 
-    return (String) vm.invoke(new SerializableCallable("Stop Locator In 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();
 
-      public Object call() throws Exception {
+      LocatorMXBean locatorMXBean = service.getLocalLocatorMXBean();
+      assertThat(locatorMXBean).isNotNull();
+      assertThat(locatorMXBean.getPort()).isEqualTo(port);
 
-        assertTrue(InternalLocator.hasLocator());
-        InternalLocator.getLocator().stop();
-        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 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;
-      }
+      assertThat(locatorMXBean.isPeerLocator()).isEqualTo(isPeer);
     });
   }
 
-  /**
-   * 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();
   }
-
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 85d42ee..ef1c4fa 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
@@ -17,15 +17,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;
@@ -35,39 +37,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
@@ -79,23 +74,14 @@ 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 {
@@ -119,16 +105,14 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
   protected void postSetUpManagementTestBase() throws Exception {}
 
   @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();
   }
 
@@ -136,99 +120,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");
@@ -238,68 +172,48 @@ 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) {
-
     Wait.waitForCriterion(new WaitCriterion() {
+      @Override
       public String description() {
         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) {
@@ -308,205 +222,55 @@ 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()) {
@@ -519,169 +283,103 @@ 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);
+    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()
+          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) {
@@ -694,12 +392,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();
@@ -709,4 +405,14 @@ 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/geode/blob/914cbfdc/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..e97a652
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java
@@ -0,0 +1,437 @@
+/*
+ * 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.cache.client.ClientCache;
+import org.apache.geode.cache.client.ClientCacheFactory;
+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 ClientCache getClientCache() {
+    return this.helper.getClientCache(new ClientCacheFactory());
+  }
+
+  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/geode/blob/914cbfdc/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..ce6c6a6
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/Manager.java
@@ -0,0 +1,29 @@
+/*
+ * 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/geode/blob/914cbfdc/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..84a80e5
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/Member.java
@@ -0,0 +1,29 @@
+/*
+ * 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 "";
+}


[35/50] [abbrv] geode git commit: GEODE-1333: add FlakyTest category to flaky test

Posted by kl...@apache.org.
GEODE-1333: add FlakyTest category to flaky test


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

Branch: refs/heads/feature/GEODE-1930
Commit: c10a788b104b6f4184881219088693b3ebb1d1f9
Parents: 92ef732
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Dec 12 17:31:55 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 17:31:55 2016 -0800

----------------------------------------------------------------------
 .../internal/configuration/ClusterConfigurationDUnitTest.java       | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/c10a788b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
index 0d48f5b..f73a393 100644
--- a/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
+++ b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
@@ -344,6 +344,7 @@ public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
    * 
    * @since GemFire 8.1
    */
+  @Category(FlakyTest.class) // GEODE-1333
   @Test
   public void testDestroyExtensions() throws Exception {
     Object[] result = setup();


[50/50] [abbrv] 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/geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/geode/commit/914cbfdc
Tree: http://git-wip-us.apache.org/repos/asf/geode/tree/914cbfdc
Diff: http://git-wip-us.apache.org/repos/asf/geode/diff/914cbfdc

Branch: refs/heads/feature/GEODE-1930
Commit: 914cbfdc525fe15b0d1c6a1c40cc0d6654da0ff6
Parents: 80525b7
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Oct 31 13:45:28 2016 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Tue Dec 13 12:29:16 2016 -0800

----------------------------------------------------------------------
 .../RestAPIsAndInterOpsDUnitTest.java           |   46 +-
 geode-core/build.gradle                         |    1 +
 .../org/apache/geode/management/JVMMetrics.java |    3 +-
 .../org/apache/geode/management/OSMetrics.java  |    3 +-
 .../internal/SystemManagementService.java       |    3 +-
 .../DistributedLockServiceDUnitTest.java        |    2 +-
 .../cache/ConnectDisconnectDUnitTest.java       |    2 +-
 ...gionBucketCreationDistributionDUnitTest.java |    4 +-
 .../cache/locks/TXLockServiceDUnitTest.java     |    4 +-
 .../management/CacheManagementDUnitTest.java    | 1001 +++++-----
 .../management/ClientHealthStatsDUnitTest.java  |  574 +++---
 .../management/CompositeTypeTestDUnitTest.java  |  191 +-
 .../management/DLockManagementDUnitTest.java    |  543 ++----
 .../management/DiskManagementDUnitTest.java     |  787 +++-----
 .../management/DistributedSystemDUnitTest.java  |  993 ++++------
 .../geode/management/JMXMBeanDUnitTest.java     |    2 +-
 .../management/LocatorManagementDUnitTest.java  |  416 ++--
 .../geode/management/ManagementTestBase.java    |  544 ++----
 .../geode/management/ManagementTestRule.java    |  437 +++++
 .../org/apache/geode/management/Manager.java    |   29 +
 .../org/apache/geode/management/Member.java     |   29 +
 .../management/OffHeapManagementDUnitTest.java  |  347 ++--
 .../geode/management/QueryDataDUnitTest.java    | 1320 ++++++-------
 .../management/RegionManagementDUnitTest.java   | 1839 ++++++++----------
 .../stats/DistributedSystemStatsDUnitTest.java  |  118 +-
 .../QueryDataFunctionApplyLimitClauseTest.java  |    1 -
 .../internal/pulse/TestClientIdsDUnitTest.java  |  315 +--
 .../pulse/TestSubscriptionsDUnitTest.java       |  288 +--
 .../geode/test/dunit/AsyncInvocation.java       |   56 +-
 .../org/apache/geode/test/dunit/Invoke.java     |    6 +-
 .../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 |   66 +
 .../test/dunit/rules/DistributedRunRules.java   |   76 +
 .../test/dunit/rules/DistributedStatement.java  |   75 +
 .../test/dunit/rules/DistributedTestRule.java   |  200 ++
 .../DistributedUseJacksonForJsonPathRule.java   |   50 +
 .../dunit/rules/DistributedWrapperRule.java     |   51 +
 .../geode/test/dunit/rules/RemoteInvoker.java   |   16 +-
 .../apache/geode/test/dunit/rules/WhichVMs.java |   59 +
 .../rules/tests/DistributedTestRuleTest.java    |   52 +
 .../test/dunit/standalone/DUnitLauncher.java    |   63 +-
 geode-junit/build.gradle                        |    1 +
 .../junit/rules/UseJacksonForJsonPathRule.java  |  128 ++
 .../SerializableExternalResource.java           |   22 +
 .../serializable/SerializableStatement.java     |   25 +
 .../management/LuceneManagementDUnitTest.java   |   23 +-
 gradle/dependency-versions.properties           |    3 +-
 52 files changed, 5106 insertions(+), 5734 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 c90a7a4..1802140 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
@@ -65,7 +65,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;
@@ -78,28 +77,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 =
@@ -161,23 +146,12 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
       + " \"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,
@@ -828,14 +802,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/geode/blob/914cbfdc/geode-core/build.gradle
----------------------------------------------------------------------
diff --git a/geode-core/build.gradle b/geode-core/build.gradle
index 067bafc..383e071 100755
--- a/geode-core/build.gradle
+++ b/geode-core/build.gradle
@@ -114,6 +114,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/geode/blob/914cbfdc/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 127592a..388c8f6 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
@@ -15,6 +15,7 @@
 package org.apache.geode.management;
 
 import java.beans.ConstructorProperties;
+import java.io.Serializable;
 
 import org.apache.geode.cache.Region;
 
@@ -25,7 +26,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/geode/blob/914cbfdc/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 d90c8be..c9de92f 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
@@ -15,6 +15,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 a member of the
@@ -23,7 +24,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/geode/blob/914cbfdc/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 cb75591..fe0f59f 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
@@ -350,7 +350,8 @@ 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/geode/blob/914cbfdc/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 277c604..9a889ca 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
@@ -98,7 +98,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/geode/blob/914cbfdc/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 de63433..5213ebc 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
@@ -40,7 +40,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/geode/blob/914cbfdc/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 ed23f2a..82498df 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
@@ -443,9 +443,7 @@ public class PartitionedRegionBucketCreationDistributionDUnitTest
       }
     });
 
-    // final int bucketPerHost = (int) Math.ceil(((double) maxBuckets / Host.getHostCount()));
-
-    // invokeInEveryVM(new SerializableRunnable("") {
+    // invokeInEveryVMAndController(new SerializableRunnable("") {
     //
     // }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 14267a4..054ab3b 100644
--- 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
@@ -89,7 +89,7 @@ public class TXLockServiceDUnitTest extends JUnit4DistributedTestCase {
 
   @Override
   public final void preTearDown() throws Exception {
-    // invokeInEveryVM(TXLockServiceDUnitTest.class,
+    // invokeInEveryVMAndController(TXLockServiceDUnitTest.class,
     // "remoteDumpAllDLockServices");
 
     Invoke.invokeInEveryVM(TXLockServiceDUnitTest.class, "destroyServices");
@@ -114,7 +114,7 @@ public class TXLockServiceDUnitTest extends JUnit4DistributedTestCase {
   public void testGetAndDestroy() {
     forEachVMInvoke("checkGetAndDestroy", new Object[] {});
     /*
-     * invokeInEveryVM(TXLockServiceDUnitTest.class, "destroyServices");
+     * invokeInEveryVMAndController(TXLockServiceDUnitTest.class, "destroyServices");
      * forEachVMInvoke("checkGetAndDestroy", new Object[] {});
      */
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 680579d..62d0b9b 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
@@ -14,11 +14,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;
@@ -26,13 +29,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;
 
@@ -43,57 +49,72 @@ 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>
+ * <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<>();
 
-  private final String VERIFY_CONFIG_METHOD = "verifyConfigData";
+  @Manager
+  private VM managerVM;
 
-  private final String VERIFY_REMOTE_CONFIG_METHOD = "verifyConfigDataRemote";
+  @Member
+  private VM[] memberVMs;
 
-  static final List<Notification> notifList = new ArrayList<Notification>();
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-  // 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;
+  @Rule
+  public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @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> configMap = new HashMap<>();
+    for (VM memberVM : this.memberVMs) {
       Map<DistributedMember, DistributionConfig> configMapMember =
-          (Map<DistributedMember, DistributionConfig>) vm.invoke(CacheManagementDUnitTest.class,
-              VERIFY_CONFIG_METHOD);
+          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));
   }
 
   /**
@@ -101,30 +122,35 @@ 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));
   }
 
   /**
@@ -132,270 +158,259 @@ 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. Multiple Managers
+   * 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. Multiple Managers
+   * 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();
+  @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]);
 
-        Set<DistributedMember> otherMembers =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+    // 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);
 
-        Set<ObjectName> superSet = new HashSet<ObjectName>();
+    // Step : 3 : Verify Notification count, notification region sizes
+    verifyNotificationsAndRegionSize(this.memberVMs[0], this.memberVMs[1], this.memberVMs[2],
+        this.managerVM);
+  }
 
-        for (DistributedMember member : otherMembers) {
+  @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);
 
-          ObjectName memberMBeanName = managementService.getMemberMBeanName(member);
+    attachListenerToDistributedSystemMXBean(this.managerVM);
 
-          waitForProxy(memberMBeanName, MemberMXBean.class);
-          Set<ObjectName> names = managementService.queryMBeanNames(member);
-          superSet.addAll(names);
-          assertTrue(names.contains(memberMBeanName));
+    // 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);
+  }
 
-        Set<ObjectName> names =
-            managementService.queryMBeanNames(cache.getDistributedSystem().getDistributedMember());
-        assertTrue(!superSet.contains(names));
-      }
-    };
-    vm.invoke(validateServiceResource);
+  @Test
+  public void testRedundancyZone() throws Exception {
+    String redundancyZone = "ARMY_ZONE";
+
+    Properties props = new Properties();
+    props.setProperty(REDUNDANCY_ZONE, redundancyZone);
+
+    this.managementTestRule.createMember(this.memberVMs[0], props);
 
+    this.memberVMs[0].invoke("verifyRedundancyZone", () -> {
+      ManagementService service = this.managementTestRule.getExistingManagementService();
+      MemberMXBean memberMXBean = service.getMemberMXBean();
+      assertThat(memberMXBean.getRedundancyZone()).isEqualTo(redundancyZone);
+    });
   }
 
-  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();
+  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<>();
+
+      for (DistributedMember member : otherMembers) {
+        ObjectName memberMBeanName = service.getMemberMBeanName(member);
 
-        for (DistributedMember member : otherMembers) {
+        awaitMemberMXBeanProxy(member);
 
-          ObjectName memberMBeanName = managementService.getMemberMBeanName(member);
+        Set<ObjectName> objectNames = service.queryMBeanNames(member);
+        superSet.addAll(objectNames);
+        assertThat(objectNames.contains(memberMBeanName)).isTrue();
+      }
 
-          waitForProxy(memberMBeanName, MemberMXBean.class);
+      Set<ObjectName> names =
+          service.queryMBeanNames(this.managementTestRule.getDistributedMember());
+      ObjectName[] arrayOfNames = names.toArray(new ObjectName[names.size()]);
 
-          MemberMXBean bean =
-              managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
-          assertNotNull(bean);
-        }
+      assertThat(superSet).doesNotContain(arrayOfNames); // TODO: what value does this method have?
+    });
+  }
+
+  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);
 
-        DistributedMember thisMember = cache.getDistributedSystem().getDistributedMember();
-        ObjectName memberMBeanName = managementService.getMemberMBeanName(thisMember);
-        MemberMXBean bean = managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
-        assertNotNull(bean);
+        awaitMemberMXBeanProxy(member);
 
+        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();
+    });
   }
 
-  protected void validateServiceResource(final VM vm) {
-    SerializableRunnable validateServiceResource =
-        new SerializableRunnable("Valideate Management Service Resource") {
-          public void run() {
+  private void verifyManagerStarted(final VM managerVM, final DistributedMember otherMember) {
+    managerVM.invoke("verifyManagerStarted", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+      assertThat(service.isManager()).isTrue();
 
-            GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            assertNull(cache);
-            assertFalse(managementService.isManager());
+      assertThat(service.getLocalManager().isRunning()).isTrue();
 
-            SystemManagementService service = (SystemManagementService) managementService;
-            assertNull(service.getLocalManager());
-          }
-        };
-    vm.invoke(validateServiceResource);
-  }
+      assertThat(service.getLocalManager().getFederationSheduler().isShutdown()).isFalse();
 
-  /**
-   * 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();
+      ObjectName memberMBeanName = service.getMemberMBeanName(otherMember);
 
-        assertTrue(t2 > t1);
+      await().until(
+          () -> assertThat(service.getMBeanProxy(memberMBeanName, MemberMXBean.class)).isNotNull());
+      MemberMXBean memberMXBean = service.getMBeanProxy(memberMBeanName, MemberMXBean.class);
 
-      }
-    };
-    return vm.invokeAsync(createRegion);
+      // 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;
   }
 
@@ -403,398 +418,276 @@ 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)
+  private void verifyConfigDataRemote(final Map<DistributedMember, DistributionConfig> configMap)
       throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    Set<DistributedMember> otherMemberSet =
-        cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+    Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
 
-    for (DistributedMember member : otherMemberSet) {
-      MemberMXBean bean = MBeanUtil.getMemberMbeanProxy(member);
-      GemFireProperties data = bean.listGemFireProperties();
+    for (DistributedMember member : otherMembers) {
+      MemberMXBean memberMXBean = awaitMemberMXBeanProxy(member);
+
+      GemFireProperties data = memberMXBean.listGemFireProperties();
       DistributionConfig config = configMap.get(member);
-      assertConfigEquals(config, data);
+      verifyGemFirePropertiesData(config, data);
     }
   }
 
   /**
    * 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.");
-      }
-    }
-    ManagerMXBean mngrBean = getManagementService().getManagerMXBean();
-    try {
-      mngrBean.start();
-    } catch (JMException e) {
-      fail("Could not start Manager " + e);
+  private void startManager() throws JMException {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    if (memberMXBean.isManagerCreated()) {
+      return;
     }
-    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;
-  }
+    // 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.
 
-  public static void fetchJVMMetrics() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    JVMMetrics metrics = bean.showJVMMetrics();
+    assertThat(memberMXBean.createManager()).isTrue();
+    assertThat(memberMXBean.isManagerCreated()).isTrue();
 
-    LogWriterUtils.getLogWriter()
-        .info("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
-  }
+    ManagerMXBean managerMXBean = service.getManagerMXBean();
+    managerMXBean.start();
 
-  public static void fetchOSMetrics() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    OSMetrics metrics = bean.showOSMetrics();
+    assertThat(managerMXBean.isRunning()).isTrue();
+    assertThat(memberMXBean.isManager()).isTrue();
+    assertThat(service.isManager()).isTrue();
+  }
 
-    LogWriterUtils.getLogWriter()
-        .info("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
+  private String fetchLog(final int numberOfLines) {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    return memberMXBean.showLog(numberOfLines);
   }
 
-  public static void shutDownMember() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    bean.shutDownMember();
+  private JVMMetrics fetchJVMMetrics() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    JVMMetrics metrics = memberMXBean.showJVMMetrics();
+    return metrics;
   }
 
-  public static void assertExpectedMembers(int expectedMemberCount) {
-    Wait.waitForCriterion(new WaitCriterion() {
-      public String description() {
-        return "Waiting all nodes to shutDown";
-      }
+  private OSMetrics fetchOSMetrics() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    OSMetrics metrics = memberMXBean.showOSMetrics();
+    return metrics;
+  }
 
-      public boolean done() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> setOfOtherMembers =
-            cache.getDistributedSystem().getAllOtherMembers();
-        boolean done = (setOfOtherMembers != null && setOfOtherMembers.size() == 1);
-        return done;
-      }
+  private void shutDownMember() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    memberMXBean.shutDownMember();
+  }
 
-    }, MAX_WAIT, 500, true);
+  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));
   }
 
-  public static void invokeRemoteOps() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    Set<DistributedMember> otherMemberSet =
-        cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+  private void invokeRemoteMemberMXBeanOps() 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);
-      JVMMetrics metrics = bean.showJVMMetrics();
+      JVMMetrics metrics = memberMXBean.showJVMMetrics();
 
-      LogWriterUtils.getLogWriter()
-          .info("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
-      LogWriterUtils.getLogWriter()
-          .info("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
+      String value = metrics.toString();
+      boolean isManager = memberMXBean.isManager();
 
-      LogWriterUtils.getLogWriter()
-          .info("<ExpectedString> Boolean Data Check " + bean.isManager() + "</ExpectedString> ");
+      // TODO: need assertions
+
+      // ("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
+      // ("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
+      // ("<ExpectedString> Boolean Data Check " + bean.isManager() + "</ExpectedString> ");
     }
   }
 
-  @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();
+  private void attachListenerToDistributedSystemMXBean(final VM managerVM) {
+    managerVM.invoke("attachListenerToDistributedSystemMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      assertThat(service.isManager()).isTrue();
 
-    // 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);
+      NotificationListener listener = (final Notification notification, final Object handback) -> {
+        if (notification.getType().equals(JMXNotificationType.REGION_CREATED)) {
+          notifications.add(notification);
+        }
+      };
 
-    // Step : 3 : Verify Notification count, notification region sizes
-    countNotificationsAndCheckRegionSize(node1, node2, node3, managingNode);
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(
+          MBeanJMXAdapter.getDistributedSystemName(), listener, null, null);
+    });
   }
 
-  @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();
+  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);
 
-    // Step : 1 : Create Managing Node Cache, start manager, add a notification
-    // handler to DistributedSystemMXBean
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    attchListenerToDSMBean(managingNode);
+    String memberId1 = MBeanJMXAdapter.getUniqueIDForMember(member1);
+    String memberId2 = MBeanJMXAdapter.getUniqueIDForMember(member2);
+    String memberId3 = MBeanJMXAdapter.getUniqueIDForMember(member3);
 
-    // Step : 2 : Create Managed Node Caches
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
+    memberVM1.invoke("createNotificationRegion", () -> createNotificationRegion(memberId1));
+    memberVM2.invoke("createNotificationRegion", () -> createNotificationRegion(memberId2));
+    memberVM3.invoke("createNotificationRegion", () -> createNotificationRegion(memberId3));
 
-    // Step : 3 : Verify Notification count, notification region sizes
-    countNotificationsAndCheckRegionSize(node1, node2, node3, managingNode);
-  }
+    managerVM.invoke("verify notifications size", () -> {
+      await().until(() -> assertThat(notifications.size()).isEqualTo(45));
 
-  @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");
+      Cache cache = this.managementTestRule.getCache();
 
-    createCache(node1, props);
+      Region region1 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId1);
+      Region region2 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId2);
+      Region region3 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId3);
 
-    node1.invoke(new SerializableRunnable("Assert Redundancy Zone") {
+      // Even though we got 15 notification only 10 should be there due to
+      // eviction attributes set in notification region
 
-      public void run() {
-        ManagementService service = ManagementService.getExistingManagementService(getCache());
-        MemberMXBean bean = service.getMemberMXBean();
-        assertEquals("ARMY_ZONE", bean.getRedundancyZone());
-      }
+      await().until(() -> assertThat(region1).hasSize(10));
+      await().until(() -> assertThat(region2).hasSize(10));
+      await().until(() -> assertThat(region3).hasSize(10));
     });
   }
 
-  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);
-            }
-
-          }
-        };
-    vm.invoke(attchListenerToDSMBean);
-  }
-
-  public void waitForManagerToRegisterListener() {
-    SystemManagementService service = (SystemManagementService) getManagementService();
-    final Map<ObjectName, NotificationHubListener> hubMap =
+  private void createNotificationRegion(final String memberId) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    Map<ObjectName, NotificationHubListener> notificationHubListenerMap =
         service.getNotificationHub().getListenerObjectMap();
 
-    Wait.waitForCriterion(new WaitCriterion() {
-      public String description() {
-        return "Waiting for manager to register the listener";
-      }
+    await().until(() -> assertThat(notificationHubListenerMap.size()).isEqualTo(1));
 
-      public boolean done() {
-        boolean done = (1 == hubMap.size());
-        return done;
-      }
+    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);
 
-    }, MAX_WAIT, 500, true);
+    assertThat(region).isEmpty();
   }
 
-  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);
-
-    node1.invoke("Create Regions", () -> createNotifTestRegion(appender1));
-    node2.invoke("Create Regions", () -> createNotifTestRegion(appender2));
-    node3.invoke("Create Regions", () -> createNotifTestRegion(appender3));
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getMemberMBeanName(member);
 
-    managingNode.invoke(new SerializableRunnable("Validate Notification Count") {
-
-      public void run() {
-
-        Wait.waitForCriterion(new WaitCriterion() {
-          public String description() {
-            return "Waiting for all the RegionCreated notification to reach the manager "
-                + notifList.size();
-          }
-
-          public boolean done() {
-            boolean done = (45 == notifList.size());
-            return done;
-          }
-
-        }, MAX_WAIT, 500, true);
-
-        assertEquals(45, notifList.size());
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-
-        Region member1NotifRegion =
-            cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender1);
-        Region member2NotifRegion =
-            cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender2);
-        Region member3NotifRegion =
-            cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender3);
-
-        // Even though we got 15 notification only 10 should be there due to
-        // eviction attributes set in notification region
-
-        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));
-      }
-    });
+    String alias = "awaiting MemberMXBean proxy for " + member;
+    await(alias)
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
 
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
   }
 
-  private void createNotifTestRegion(final String appender1) {
-    Cache cache = getCache();
-
-    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);
-
-    assertEquals(0, member1NotifRegion.size());
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
   }
 
+  private ConditionFactory await(final String alias) {
+    return Awaitility.await(alias).atMost(2, MINUTES);
+  }
 }


[32/50] [abbrv] geode git commit: GEODE-2204: apply FlakyTest category to flaky test

Posted by kl...@apache.org.
GEODE-2204: apply FlakyTest category to flaky test


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

Branch: refs/heads/feature/GEODE-1930
Commit: 8eb09bde832fc48c7a42b73743f102198a4cb311
Parents: 0f28be9
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Dec 12 10:21:14 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 14:34:03 2016 -0800

----------------------------------------------------------------------
 .../java/org/apache/geode/security/PDXPostProcessorDUnitTest.java   | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/8eb09bde/geode-core/src/test/java/org/apache/geode/security/PDXPostProcessorDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/PDXPostProcessorDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/PDXPostProcessorDUnitTest.java
index 897db92..f6105e1 100644
--- a/geode-core/src/test/java/org/apache/geode/security/PDXPostProcessorDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/PDXPostProcessorDUnitTest.java
@@ -149,6 +149,7 @@ public class PDXPostProcessorDUnitTest extends AbstractSecureServerDUnitTest {
     assertEquals(pp.getCount(), 2);
   }
 
+  @Category(FlakyTest.class) // GEODE-2204
   @Test
   public void testRegisterInterest() {
     client1.invoke(() -> {


[45/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 1773a27..6fd7b98 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
@@ -14,895 +14,739 @@
  */
 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();
-  }
+@SuppressWarnings({"serial", "unused"})
+public class QueryDataDUnitTest implements Serializable {
+
+  private static final int NUM_OF_BUCKETS = 20;
+
+  // 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";
+
+  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";
+
+  private static final String LOCAL_REGION_NAME = "LOCAL_REGION_NAME";
+
+  private static final String BIG_COLLECTION_ELEMENT_ = "BIG_COLLECTION_ELEMENT_";
+  private static final String BIG_COLLECTION_ = "BIG_COLLECTION_";
+
+  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"};
+
+  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"};
+
+  private static final String[] QUERIES_FOR_LIMIT =
+      new String[] {"SELECT * FROM /" + REPLICATE_REGION_NAME4};
+
+  private DistributedMember member1;
+  private DistributedMember member2;
+  private DistributedMember member3;
+
+  @Manager
+  private VM managerVM;
+
+  @Member
+  private VM[] memberVMs;
+
+  @Rule
+  public DistributedUseJacksonForJsonPathRule useJacksonForJsonPathRule =
+      new DistributedUseJacksonForJsonPathRule();
+
+  @Rule
+  public ManagementTestRule managementTestRule =
+      ManagementTestRule.builder().managersFirst(false).start(true).build();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @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]);
 
-  @Override
-  protected final void postSetUpManagementTestBase() throws Exception {
-    initManagement(false);
-  }
-
-  private void initCommonRegions() {
     createRegionsInNodes();
-    fillValuesInRegions();
+    generateValuesInRegions();
   }
 
-  /**
-   * 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;
-  }
-
-  /**
-   * 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);
-
-      }
-    };
-    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);
-
-      }
-    };
-    return (CacheSerializableRunnable) bigPuts;
-  }
-
-  public void fillValuesInRegions() {
-    // Create common Portflios and NewPortfolios
-    final Portfolio[] portfolio = createPortfoliosAndPositions(cntDest);
-
-    // Fill local region
-    managedNode1
-        .invoke(getCacheSerializableRunnableForPRPuts(localRegionName, portfolio, cnt, cntDest));
-
-    // Fill replicated region
-    managedNode1
-        .invoke(getCacheSerializableRunnableForPRPuts(repRegionName, portfolio, cnt, cntDest));
-    managedNode2
-        .invoke(getCacheSerializableRunnableForPRPuts(repRegionName2, portfolio, cnt, cntDest));
-
-    // 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));
-
-    managedNode1.invoke(getCacheSerializableRunnableForPDXPuts(repRegionName3));
-
-  }
-
-  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);
-    }
-
-  }
-
-  private void createRegionsInNodes() {
-
-    // Create local Region on servers
-    managedNode1.invoke(() -> QueryUsingFunctionContextDUnitTest.createLocalRegion());
-
-    // 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());
-    }
-
-    // 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");
-            }
-          }
-        });
-
-  }
-
-  // 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();
 
+      String jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_REPLICATED[0], null, 10);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
 
-    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());
-        }
+      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();
+      byte[] bytes = distributedSystemMXBean.queryDataForCompressedResult(QUERIES_FOR_REPLICATED[0],
+          member1.getId() + "," + member2.getId(), 2);
+      String jsonString = BeanUtilFuncs.decompress(bytes);
 
-
-    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());
-        }
-      }
+      verifyJsonIsValid(jsonString);
     });
   }
 
-
-
   @Test
   public void testLimitForQuery() throws Exception {
+    this.memberVMs[0].invoke("putBigInstances", () -> putBigInstances(REPLICATE_REGION_NAME4));
 
-    initCommonRegions();
-    managedNode1.invoke(getCacheSerializableRunnableForBigCollPuts(repRegionName4));
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
 
-    managingNode.invoke(new SerializableRunnable("testLimitForQuery") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
+      // Query With Default values
+      assertThat(distributedSystemMXBean.getQueryCollectionsDepth())
+          .isEqualTo(TypedJson.DEFAULT_COLLECTION_ELEMENT_LIMIT);
+      assertThat(distributedSystemMXBean.getQueryResultSetLimit()).isEqualTo(DEFAULT_QUERY_LIMIT);
 
-        try {
+      String jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_LIMIT[0], null, 0);
 
-          // Query With Default values
-          assertEquals(TypedJson.DEFAULT_COLLECTION_ELEMENT_LIMIT, bean.getQueryCollectionsDepth());
-          assertEquals(ManagementConstants.DEFAULT_QUERY_LIMIT, bean.getQueryResultSetLimit());
+      verifyJsonIsValid(jsonString);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
+      assertThat(jsonString).contains(BIG_COLLECTION_ELEMENT_);
 
-          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
+      JSONObject jsonObject = new JSONObject(jsonString);
+      JSONArray jsonArray = jsonObject.getJSONArray("result");
+      assertThat(jsonArray.length()).isEqualTo(DEFAULT_QUERY_LIMIT);
 
-            JSONArray array1 = (JSONArray) arr.getJSONArray(0);
-            // Get the ObjectValue
+      // Get the first element
+      JSONArray jsonArray1 = jsonArray.getJSONArray(0);
 
-            JSONObject collectionObject = (JSONObject) array1.get(1);
-            assertEquals(100, collectionObject.length());
+      // Get the ObjectValue
+      JSONObject collectionObject = (JSONObject) jsonArray1.get(1);
+      assertThat(collectionObject.length()).isEqualTo(100);
 
-          } else {
-            fail("Query On Cluster should have result");
-          }
+      // Query With Override Values
+      int newQueryCollectionDepth = 150;
+      int newQueryResultSetLimit = 500;
 
-          // Query With Ovverride Values
+      distributedSystemMXBean.setQueryCollectionsDepth(newQueryCollectionDepth);
+      distributedSystemMXBean.setQueryResultSetLimit(newQueryResultSetLimit);
 
-          int newQueryCollectionDepth = 150;
-          int newQueryResultSetLimit = 500;
-          bean.setQueryCollectionsDepth(newQueryCollectionDepth);
-          bean.setQueryResultSetLimit(newQueryResultSetLimit);
+      assertThat(distributedSystemMXBean.getQueryCollectionsDepth())
+          .isEqualTo(newQueryCollectionDepth);
+      assertThat(distributedSystemMXBean.getQueryResultSetLimit())
+          .isEqualTo(newQueryResultSetLimit);
 
-          assertEquals(newQueryCollectionDepth, bean.getQueryCollectionsDepth());
-          assertEquals(newQueryResultSetLimit, bean.getQueryResultSetLimit());
+      jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_LIMIT[0], null, 0);
 
-          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
+      verifyJsonIsValid(jsonString);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
 
-            JSONArray array1 = (JSONArray) arr.getJSONArray(0);
-            // Get the ObjectValue
+      jsonObject = new JSONObject(jsonString);
+      assertThat(jsonString).contains(BIG_COLLECTION_ELEMENT_);
 
-            JSONObject collectionObject = (JSONObject) array1.get(1);
-            assertEquals(newQueryCollectionDepth, collectionObject.length());
+      jsonArray = jsonObject.getJSONArray("result");
+      assertThat(jsonArray.length()).isEqualTo(newQueryResultSetLimit);
 
-          } else {
-            fail("Query On Cluster should have result");
-          }
+      // Get the first element
+      jsonArray1 = jsonArray.getJSONArray(0);
 
-        } catch (JSONException e) {
-          fail(e.getMessage());
-        } catch (IOException e) {
-          fail(e.getMessage());
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
-
-      }
+      // 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());
-        }
-
-      }
+    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());
-        }
-
-      }
+    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"};
 
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
+    this.memberVMs[0].invoke(this.testName.getMethodName() + " Create Region", () -> {
+      PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
+      partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
 
-    final String PartitionedRegionName6 = "LocalDataSetTest";
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(1);
+      for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+        partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
+      }
+      partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
 
-    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 {
+      RegionFactory regionFactory =
+          this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+              .setPartitionAttributes(partitionAttributesFactory.create());
+      Region region = regionFactory.create(partitionedRegionName);
 
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
+      for (int i = 0; i < values1.length; i++) {
+        region.put(getDate(2013, 1, i + 5), values1[i]);
+      }
+    });
 
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
+    this.memberVMs[1].invoke(this.testName.getMethodName() + " Create Region", () -> {
+      PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
+      partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
 
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(1);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(2);
+      for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+        partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
+      }
+      partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
 
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION)
-              .setPartitionAttributes(paf.create());
+      RegionFactory regionFactory =
+          this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+              .setPartitionAttributes(partitionAttributesFactory.create());
+      Region region = regionFactory.create(partitionedRegionName);
 
-          Region r = rf.create(PartitionedRegionName6);
+      for (int i = 0; i < values2.length; i++) {
+        region.put(getDate(2013, 5, i + 5), values2[i]);
+      }
+    });
 
-          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());
-        }
+    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);
     });
 
-    this.managedNode2.invoke(new SerializableRunnable("testRegionsLocalDataSet: Create Region") {
-      public void run() {
-        try {
+    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));
 
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
+      DistributedRegionMXBean distributedRegionMXBean =
+          awaitDistributedRegionMXBean("/" + partitionedRegionName, 3);
 
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
+      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));
 
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(2);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+      String query = "Select * from /" + partitionedRegionName;
 
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION)
-              .setPartitionAttributes(paf.create());
+      String member1Result = distributedSystemMXBean.queryData(query, member1.getId(), 0);
+      verifyJsonIsValid(member1Result);
 
-          Region r = rf.create(PartitionedRegionName6);
+      String member2Result = distributedSystemMXBean.queryData(query, member2.getId(), 0);
+      verifyJsonIsValid(member2Result);
 
-          for (int i = 0; i < valArray2.length; i++) {
-            r.put(new Date(2013, 5, i + 5), valArray2[i]);
-          }
+      String member3Result = distributedSystemMXBean.queryData(query, member3.getId(), 0);
+      verifyJsonIsValid(member3Result);
 
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+      for (String val : member1RealData) {
+        assertThat(member1Result).contains(val);
+      }
 
+      for (String val : member2RealData) {
+        assertThat(member2Result).contains(val);
       }
+
+      assertThat(member3Result).contains("No Data Found");
     });
+  }
 
-    this.managedNode3.invoke(new SerializableRunnable("testRegionsLocalDataSet: Create Region") {
-      public void run() {
-        try {
+  private Date getDate(final int year, final int month, final int date) {
+    Calendar calendar = Calendar.getInstance();
+    calendar.set(year, month, date);
+    return calendar.getTime();
+  }
 
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
+  private void verifyJsonIsValid(final String jsonString) throws JSONException {
+    assertThat(jsonString, isJson());
+    assertThat(jsonString, hasJsonPath("$.result"));
+    assertThat(new JSONObject(jsonString)).isNotNull();
+  }
 
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
+  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]);
+    }
+  }
 
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(3);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+  private void generateValuesInRegions() {
+    int COUNT_DESTINATION = 30;
+    int COUNT_FROM = 0;
 
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION)
-              .setPartitionAttributes(paf.create());
+    // Create common Portfolios and NewPortfolios
+    final Portfolio[] portfolio = createPortfoliosAndPositions(COUNT_DESTINATION);
 
-          Region r = rf.create(PartitionedRegionName6);
+    // 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));
+  }
 
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+  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);
+    }
+  }
 
-    final List<String> member1RealData = (List<String>) managedNode1
-        .invoke(() -> QueryDataDUnitTest.getLocalDataSet(PartitionedRegionName6));
+  private void createLocalRegion() {
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.LOCAL)
+        .create(LOCAL_REGION_NAME);
+  }
 
-    final List<String> member2RealData = (List<String>) managedNode2
-        .invoke(() -> QueryDataDUnitTest.getLocalDataSet(PartitionedRegionName6));
+  private void createReplicatedRegion() {
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE)
+        .create(REPLICATE_REGION_NAME1);
+  }
 
-    final List<String> member3RealData = (List<String>) managedNode3
-        .invoke(() -> QueryDataDUnitTest.getLocalDataSet(PartitionedRegionName6));
+  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());
 
-    this.managingNode.invoke(new SerializableRunnable("testRegionsLocalDataSet") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
+    // 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);
+    });
+  }
 
-        try {
-          String query = "Select * from /" + PartitionedRegionName6;
+  private List<String> getLocalDataSet(final String region) {
+    PartitionedRegion partitionedRegion =
+        PartitionedRegionHelper.getPartitionedRegion(region, this.managementTestRule.getCache());
+    Set<BucketRegion> localPrimaryBucketRegions =
+        partitionedRegion.getDataStore().getAllLocalPrimaryBucketRegions();
 
-          try {
-            final DistributedRegionMXBean regionMBean =
-                MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName6, 3);
+    List<String> allPrimaryValues = new ArrayList<>();
 
-            Wait.waitForCriterion(new WaitCriterion() {
+    for (BucketRegion bucketRegion : localPrimaryBucketRegions) {
+      for (Object value : bucketRegion.values()) {
+        allPrimaryValues.add((String) value);
+      }
+    }
 
-              public String description() {
-                return "Waiting for all entries to get reflected at managing node";
-              }
+    return allPrimaryValues;
+  }
 
-              public boolean done() {
+  private List<FixedPartitionAttributes> createFixedPartitionList(final int primaryIndex) {
+    List<FixedPartitionAttributes> fixedPartitionAttributesList = new ArrayList<>();
+    if (primaryIndex == 1) {
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", true, 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", 3));
+    }
+    if (primaryIndex == 2) {
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", true, 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", 3));
+    }
+    if (primaryIndex == 3) {
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", true, 3));
+    }
+    return fixedPartitionAttributesList;
+  }
 
-                boolean done = (regionMBean
-                    .getSystemRegionEntryCount() == (valArray1.length + valArray2.length));
-                return done;
-              }
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getMemberMBeanName(member);
+    String alias = "awaiting MemberMXBean proxy for " + member;
 
-            }, MAX_WAIT, 1000, true);
+    await(alias)
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
 
-            LogWriterUtils.getLogWriter().info("member1RealData  is = " + member1RealData);
-            LogWriterUtils.getLogWriter().info("member2RealData  is = " + member2RealData);
-            LogWriterUtils.getLogWriter().info("member3RealData  is = " + member3RealData);
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
+  }
 
-            String member1Result = bean.queryData(query, member1.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member1Result " + query + " is = " + member1Result);
+  private DistributedSystemMXBean awaitDistributedSystemMXBean() {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
+    await().until(() -> assertThat(service.getDistributedSystemMXBean()).isNotNull());
 
-            String member2Result = bean.queryData(query, member2.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member2Result " + query + " is = " + member2Result);
+    return service.getDistributedSystemMXBean();
+  }
 
-            String member3Result = bean.queryData(query, member3.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member3Result " + query + " is = " + member3Result);
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-            for (String val : member1RealData) {
-              assertTrue(member1Result.contains(val));
-            }
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
 
-            for (String val : member2RealData) {
-              assertTrue(member2Result.contains(val));
-            }
+    return service.getDistributedRegionMXBean(name);
+  }
 
-            assertTrue(member3Result.contains("No Data Found"));
-          } catch (Exception e) {
-            fail(e.getMessage());
-          }
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name,
+      final int memberCount) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+    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 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 ConditionFactory await(final String alias) {
+    return Awaitility.await(alias).atMost(2, MINUTES);
+  }
 
-    }
+  private static class TestPartitionResolver implements PartitionResolver {
 
-    return allPrimaryVals;
-  }
+    @Override
+    public void close() {}
 
-  /**
-   * 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>();
-    if (primaryIndex == 1) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
+    @Override
+    public Serializable getRoutingObject(EntryOperation opDetails) {
+      return (((Integer) opDetails.getKey()).intValue() % NUM_OF_BUCKETS);
     }
-    if (primaryIndex == 2) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", true, 3));
-      fpaList.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));
+
+    @Override
+    public String getName() {
+      return getClass().getName();
     }
-    return fpaList;
   }
 }


[31/50] [abbrv] geode git commit: Removed a misplaced occurrence of "Pivotal" from the docs.

Posted by kl...@apache.org.
Removed a misplaced occurrence of "Pivotal" from the docs.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 0f28be98f07e3fc5c6c982fcd3f5cd2c72252c1a
Parents: 5d2f0f6
Author: Dave Barnes <db...@pivotal.io>
Authored: Mon Dec 12 10:20:36 2016 -0800
Committer: Dave Barnes <db...@pivotal.io>
Committed: Mon Dec 12 10:20:36 2016 -0800

----------------------------------------------------------------------
 .../http_session_mgmt/tomcat_installing_the_module.html.md.erb     | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/0f28be98/geode-docs/tools_modules/http_session_mgmt/tomcat_installing_the_module.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/tools_modules/http_session_mgmt/tomcat_installing_the_module.html.md.erb b/geode-docs/tools_modules/http_session_mgmt/tomcat_installing_the_module.html.md.erb
index 9840024..b96a254 100644
--- a/geode-docs/tools_modules/http_session_mgmt/tomcat_installing_the_module.html.md.erb
+++ b/geode-docs/tools_modules/http_session_mgmt/tomcat_installing_the_module.html.md.erb
@@ -22,7 +22,7 @@ limitations under the License.
 This topic describes how to install the HTTP session management module for Tomcat.
 
 1.  If you do not already have Tomcat installed, download the desired version from the [Apache Website](http://tomcat.apache.org/).
-2.  The HTTP Session Management Module for Tomcat is included in the Pivotal Geode installation package. After you install Apache Geode, you will find the module in the `tools/Modules` directory of the installation.
+2.  The HTTP Session Management Module for Tomcat is included in the Geode installation package. After you install Apache Geode, you will find the module in the `tools/Modules` directory of the installation.
 
 3.  Unzip the module into the `$CATALINA_HOME` directory or wherever you installed the application server.
 4.  Copy the following jar files to the `lib` directory of your Tomcat server (`$CATALINA_HOME/lib`):


[48/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/914cbfdc/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 bcfadde..50533d3 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
@@ -14,24 +14,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;
@@ -40,674 +41,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;
-
-  // 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;
+@SuppressWarnings({"serial", "unused"})
+public class DiskManagementDUnitTest implements Serializable {
 
-  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();
+  @Member
+  private VM[] memberVMs;
 
-    diskDir = new File("diskDir-" + getName()).getAbsoluteFile();
-    org.apache.geode.internal.FileUtil.delete(diskDir);
-    diskDir.mkdir();
-    diskDir.deleteOnExit();
-  }
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().start(true).build();
 
-  @Override
-  protected final void postSetUpManagementTestBase() throws Exception {
-    failureCause = "";
-    testFailed = false;
-  }
+  @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 disks which belong to
-   * the cache should be compacted.
-   * 
-   * @throws Exception
+   * Tests Disk Compaction from a MemberMXBean which is at cache level. All the disks which belong
+   * to the cache should be compacted.
    */
-
   @Test
-  public void testDiskCompact() throws Throwable {
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
+  public void testDiskCompact() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
     }
 
-    for (VM vm : getManagedNodeList()) {
-      compactAllDiskStores(vm);
+    for (VM memberVM : this.memberVMs) {
+      compactAllDiskStores(memberVM);
     }
-
   }
 
   /**
-   * Tests Disk Compaction from a MemberMbean which is at cache level. All the disks which belong to
-   * the cache should be compacted.
-   * 
-   * @throws Exception
+   * Tests Disk Compaction from a MemberMXBean which is at cache level. All the disks which belong
+   * to the cache should be compacted.
    */
-
   @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 interfaces
-   * 
-   * @throws Throwable
+   * Checks the test case of missing disks and revoking them through MemberMXBean interfaces
    */
-  @SuppressWarnings("serial")
   @Test
-  public void testMissingMembers() throws Throwable {
+  public void testMissingMembers() throws Exception {
+    VM memberVM1 = this.memberVMs[0];
+    VM memberVM2 = this.memberVMs[1];
 
-    initManagement(false);
-    VM vm0 = getManagedNodeList().get(0);
-    VM vm1 = getManagedNodeList().get(1);
-    VM vm2 = getManagedNodeList().get(2);
+    createPersistentRegion(memberVM1);
+    createPersistentRegion(memberVM2);
 
-    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(memberVM1);
 
-    putAnEntry(vm0);
+    this.managerVM.invoke("checkForMissingDiskStores", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      PersistentMemberDetails[] missingDiskStores = distributedSystemMXBean.listMissingDiskStores();
 
+      assertThat(missingDiskStores).isNull();
+    });
 
-    managingNode.invoke(new SerializableRunnable("Check for waiting regions") {
+    closeRegion(memberVM1);
 
-      public void run() {
-        Cache cache = getCache();
-        ManagementService service = getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        PersistentMemberDetails[] missingDiskStores = bean.listMissingDiskStores();
+    updateTheEntry(memberVM2, "C");
 
-        assertNull(missingDiskStores);
-      }
-    });
+    closeRegion(memberVM2);
 
-    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);
-          }
-        }
-      }
-    });
+    AsyncInvocation creatingPersistentRegionAsync = createPersistentRegionAsync(memberVM1);
 
-    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);
+    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();
 
-  protected void checkNavigation(final VM vm, final DistributedMember diskMember,
-      final String diskStoreName) {
-    SerializableRunnable checkNavigation = new SerializableRunnable("Check Navigation") {
-      public void run() {
+    this.managerVM.invoke("revokeMissingDiskStore", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
+      PersistentMemberDetails[] missingDiskStores = bean.listMissingDiskStores();
 
-        final ManagementService service = getManagementService();
+      assertThat(missingDiskStores).isNotNull().hasSize(1);
 
-        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);
-        }
+      assertThat(bean.revokeMissingDiskStores(missingDiskStores[0].getDiskStoreId())).isTrue();
+    });
 
+    await(creatingPersistentRegionAsync);
 
-      }
-    };
-    vm.invoke(checkNavigation);
-  }
+    verifyRecoveryStats(memberVM1, true);
 
-  /**
-   * get Distributed member for a given vm
-   */
-  @SuppressWarnings("serial")
-  protected static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
+    // 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 {
+  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");
 
-    managingVM.invoke(new SerializableCallable("Backup All Disk Stores") {
+      DiskBackupStatus status = bean.backupAllMembers(backupDir.getAbsolutePath(), null);
 
-      public Object call() throws Exception {
-        ManagementService service = getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        DiskBackupStatus status =
-            bean.backupAllMembers(getBackupDir("test_backupAllMembers").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();
 
-  }
-
-  /**
-   * 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");
-      }
-    }
+      for (DistributedMember member : otherMemberSet) {
+        MemberMXBean memberMXBean = awaitMemberMXBeanProxy(member);
 
-  }
+        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/geode/blob/914cbfdc/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 4eaba67..79a4ce4 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
@@ -14,23 +14,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;
@@ -39,11 +35,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;
@@ -57,428 +58,277 @@ 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 String WARNING_LEVEL_MESSAGE = "Warning Level Alert Message";
+  private static final String SEVERE_LEVEL_MESSAGE = "Severe Level Alert Message";
 
-  private static final int MAX_WAIT = 10 * 1000;
+  private static List<Notification> notifications;
+  private static Map<ObjectName, NotificationListener> notificationListenerMap;
 
-  private static MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
+  @Manager
+  private VM managerVM;
 
-  static List<Notification> notifList = new ArrayList<>();
+  @Member
+  private VM[] memberVMs;
 
-  static Map<ObjectName, NotificationListener> notificationListenerMap =
-      new HashMap<ObjectName, NotificationListener>();
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-  static final String WARNING_LEVEL_MESSAGE = "Warninglevel Alert Message";
-
-  static final String SEVERE_LEVEL_MESSAGE = "Severelevel Alert Message";
+  @Before
+  public void before() throws Exception {
+    notifications = new ArrayList<>();
+    notificationListenerMap = new HashMap<>();
 
+    invokeInEveryVM(() -> notifications = new ArrayList<>());
+    invokeInEveryVM(() -> notificationListenerMap = new HashMap<>());
+  }
 
-  public DistributedSystemDUnitTest() {
-    super();
+  @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();
-
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    addAlertListener(managingNode);
-    checkAlertCount(managingNode, 0, 0);
+    this.managementTestRule.createManager(this.managerVM);
+    addAlertListener(this.managerVM);
+    verifyAlertCount(this.managerVM, 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);
+    verifyAlertCount(this.managerVM, 3, 3);
+    resetAlertCounts(this.managerVM);
 
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.SEVERE));
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.SEVERE));
 
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.SEVERE);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.SEVERE);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    checkAlertCount(managingNode, 3, 0);
-    resetAlertCounts(managingNode);
-
-    for (VM vm : getManagedNodeList()) {
-      closeCache(vm);
-    }
-
-    closeCache(managingNode);
-  }
-
-  @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;
-        }
-      });
-
-    }
+    verifyAlertCount(this.managerVM, 3, 0);
   }
 
   /**
    * 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 {
+    this.managementTestRule.createManager(this.managerVM);
 
-    final Host host = Host.getHost(0);
-
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-
-    for (VM vm : managedNodeList) {
-      createCache(vm);
+    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();
+
+      await().until(() -> assertThat(distributedSystemMXBean.listMemberObjectNames()).hasSize(5));
+
+      for (ObjectName objectName : distributedSystemMXBean.listMemberObjectNames()) {
+        NotificationHubTestListener listener = new NotificationHubTestListener();
+        ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener,
+            null, null);
+        notificationListenerMap.put(objectName, listener);
       }
     });
 
     // Check in all VMS
 
-    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());
-
-          NotificationHubListener listener = listenerObjectMap.get(memberMBeanName);
-
-          /*
-           * 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());
-
-          // Raise some notifications
-
-          NotificationBroadcasterSupport memberLevelNotifEmitter =
-              (MemberMBean) service.getMemberMXBean();
-
-          String memberSource = MBeanJMXAdapter
-              .getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());
-
-          // 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);
-
-        }
+    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);
+
+        ObjectName memberMBeanName =
+            MBeanJMXAdapter.getMemberMBeanName(this.managementTestRule.getDistributedMember());
+        NotificationHubListener listener = listenerMap.get(memberMBeanName);
+
+        /*
+         * 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);
+
+        // Raise some notifications
+
+        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();
+    this.managerVM.invoke("checkNotificationsAndRemoveListeners", () -> {
+      await().until(() -> assertThat(notifications).hasSize(3));
 
-        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);
-          }
-        }
+      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);
         }
       });
     }
@@ -486,404 +336,229 @@ public class DistributedSystemDUnitTest extends ManagementTestBase {
 
   /**
    * 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);
-
-
+    this.managementTestRule.createManager(this.managerVM);
+    addAlertListener(this.managerVM);
+    resetAlertCounts(this.managerVM);
 
-    warnLevelAlert(managingNode);
-    severeLevelAlert(managingNode);
-    checkAlertCount(managingNode, 1, 0);
-    resetAlertCounts(managingNode);
+    DistributedMember managerDistributedMember =
+        this.managementTestRule.getDistributedMember(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
+    generateWarningAlert(this.managerVM);
+    generateSevereAlert(this.managerVM);
+    verifyAlertCount(this.managerVM, 1, 0);
+    resetAlertCounts(this.managerVM);
 
-      createCache(vm);
-      // Default is severe ,So only Severe level alert is expected
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
 
-      ensureLoggerState(vm, managingMember, Alert.SEVERE);
-
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.SEVERE);
 
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
-    checkAlertCount(managingNode, 3, 0);
-    resetAlertCounts(managingNode);
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.WARNING));
 
+    verifyAlertCount(this.managerVM, 3, 0);
+    resetAlertCounts(this.managerVM);
+    setAlertLevel(this.managerVM, 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);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.WARNING);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    checkAlertCount(managingNode, 3, 3);
-
-    resetAlertCounts(managingNode);
+    verifyAlertCount(this.managerVM, 3, 3);
 
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.OFF));
+    resetAlertCounts(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.OFF);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
-    }
-    checkAlertCount(managingNode, 0, 0);
-    resetAlertCounts(managingNode);
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.OFF));
 
-    for (VM vm : getManagedNodeList()) {
-      closeCache(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.OFF);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    closeCache(managingNode);
-
+    verifyAlertCount(this.managerVM, 0, 0);
   }
 
-  @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;
-        }
-      });
-
-    }
+  private void verifyAlertAppender(final VM memberVM, final DistributedMember member,
+      final int alertLevel) {
+    memberVM.invoke("verifyAlertAppender",
+        () -> await().until(
+            () -> assertThat(AlertAppender.getInstance().hasAlertListener(member, alertLevel))
+                .isTrue()));
   }
 
+  private void verifyAlertCount(final VM managerVM, final int expectedSevereAlertCount,
+      final int expectedWarningAlertCount) {
+    managerVM.invoke("verifyAlertCount", () -> {
+      AlertNotificationListener listener = AlertNotificationListener.getInstance();
 
-
-  @SuppressWarnings("serial")
-  public void setAlertLevel(VM vm1, final String alertLevel) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Set Alert level") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(bean);
-          bean.changeAlertLevel(alertLevel);
-
-          return null;
-        }
-      });
-
-    }
+      await().until(
+          () -> assertThat(listener.getSevereAlertCount()).isEqualTo(expectedSevereAlertCount));
+      await().until(
+          () -> assertThat(listener.getWarningAlertCount()).isEqualTo(expectedWarningAlertCount));
+    });
   }
 
-  @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 setAlertLevel(final VM managerVM, final String alertLevel) {
+    managerVM.invoke("setAlertLevel", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      distributedSystemMXBean.changeAlertLevel(alertLevel);
+    });
   }
 
-
-  @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 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 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 resetAlertCounts(final VM managerVM) {
+    managerVM.invoke("resetAlertCounts", () -> {
+      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);
-            }
-
-          };
+  private void generateSevereAlert(final VM anyVM) {
+    anyVM.invoke("generateSevereAlert", () -> {
+      IgnoredException ignoredException =
+          IgnoredException.addIgnoredException(SEVERE_LEVEL_MESSAGE);
+      logger.fatal(SEVERE_LEVEL_MESSAGE);
+      ignoredException.remove();
+    });
+  }
 
-          mbeanServer.addNotificationListener(MBeanJMXAdapter.getDistributedSystemName(), nt,
-              notificationFilter, null);
+  private void addAlertListener(final VM managerVM) {
+    managerVM.invoke("addAlertListener", () -> {
+      AlertNotificationListener listener = AlertNotificationListener.getInstance();
+      listener.resetCount();
 
-          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);
-
-
+  private void verifyDistributedSystemMXBean(final VM managerVM) {
+    managerVM.invoke("verifyDistributedSystemMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
 
-          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()));
-          }
+      await().until(() -> assertThat(distributedSystemMXBean.getMemberCount()).isEqualTo(5));
 
-          return null;
-        }
-      });
-
-    }
+      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);
+    });
   }
 
+  private void shutDownAll(final VM managerVM) {
+    managerVM.invoke("shutDownAll", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      distributedSystemMXBean.shutDownAllMembers();
 
-
-  @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;
-        }
-      });
-
-    }
+      await().until(() -> assertThat(this.managementTestRule.getOtherNormalMembers()).hasSize(0));
+    });
   }
 
+  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));
 
-  @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;
-        }
-      });
-
-    }
+      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 class AlertNotificationListener implements NotificationListener {
+
+    private static AlertNotificationListener listener = new AlertNotificationListener();
+
+    private int warningAlertCount = 0;
 
-    private static AlertNotifListener listener = new AlertNotifListener();
+    private int severeAlertCount = 0;
 
-    public static AlertNotifListener getInstance() {
+    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/geode/blob/914cbfdc/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 0feb4c2..0096f0d 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
@@ -49,7 +49,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;


[37/50] [abbrv] geode git commit: GEODE-1977: add FlakyTest category to flaky test

Posted by kl...@apache.org.
GEODE-1977: add FlakyTest category to flaky test


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

Branch: refs/heads/feature/GEODE-1930
Commit: e81ad7c64a16fef1800dfa9b96adc013a2e44797
Parents: c48a350
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Dec 12 18:02:47 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 18:02:47 2016 -0800

----------------------------------------------------------------------
 .../org/apache/geode/security/SecurityClusterConfigDUnitTest.java  | 2 ++
 1 file changed, 2 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/e81ad7c6/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java b/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
index cd6518e..10b12e5 100644
--- a/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/security/SecurityClusterConfigDUnitTest.java
@@ -32,6 +32,7 @@ import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
 import org.apache.geode.test.dunit.rules.ServerStarterRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
 import org.apache.geode.test.junit.categories.SecurityTest;
 import org.junit.Before;
 import org.junit.Ignore;
@@ -62,6 +63,7 @@ public class SecurityClusterConfigDUnitTest extends JUnit4DistributedTestCase {
     lsRule.startLocatorVM(0, props);
   }
 
+  @Category(FlakyTest.class) // GEODE-1977
   @Test
   public void testStartServerWithClusterConfig() throws Exception {
     Properties props = new Properties();


[40/50] [abbrv] geode git commit: GEODE-2099: reduce scope of method and vars to prevent spaghetti

Posted by kl...@apache.org.
GEODE-2099: reduce scope of method and vars to prevent spaghetti

If you leave vars and methods public or protected, some day
someone is going to make another test call them (I've seen
it happen repeatedly) so please make them private.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 70800f5268382a3aca1b35b4c52ba5a70787e469
Parents: 079542b
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Dec 12 18:17:24 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Mon Dec 12 18:17:24 2016 -0800

----------------------------------------------------------------------
 .../geode/management/ConnectToLocatorSSLDUnitTest.java    | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/70800f52/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java
index 142ce17..457bd2e 100644
--- a/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/ConnectToLocatorSSLDUnitTest.java
@@ -12,7 +12,6 @@
  * 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.CLUSTER_SSL_ENABLED;
@@ -58,7 +57,6 @@ import java.io.OutputStream;
 import java.util.Properties;
 
 @Category(DistributedTest.class)
-
 public class ConnectToLocatorSSLDUnitTest extends JUnit4DistributedTestCase {
 
   @Rule
@@ -66,9 +64,9 @@ public class ConnectToLocatorSSLDUnitTest extends JUnit4DistributedTestCase {
   @Rule
   public LocatorServerStartupRule lsRule = new LocatorServerStartupRule();
 
-  protected File jks = null;
-  protected File securityPropsFile = null;
-  protected Properties securityProps;
+  private File jks = null;
+  private File securityPropsFile = null;
+  private Properties securityProps;
 
   @Before
   public void before() throws Exception {
@@ -82,7 +80,7 @@ public class ConnectToLocatorSSLDUnitTest extends JUnit4DistributedTestCase {
     securityPropsFile.delete();
   }
 
-  public void setUpLocatorAndConnect(Properties securityProps) throws Exception {
+  private void setUpLocatorAndConnect(Properties securityProps) throws Exception {
     lsRule.startLocatorVM(0, securityProps);
 
     // saving the securityProps to a file


[17/50] [abbrv] geode git commit: GEODE-2175: wait for results from other members is not needed in result collector. It's already handled by Function framework.

Posted by kl...@apache.org.
GEODE-2175: wait for results from other members is not needed in result collector. It's already handled by Function framework.


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

Branch: refs/heads/feature/GEODE-1930
Commit: 1d951e334334393c2052307988a21c1cd1f11985
Parents: f22809a
Author: zhouxh <gz...@pivotal.io>
Authored: Thu Dec 8 14:47:56 2016 -0800
Committer: zhouxh <gz...@pivotal.io>
Committed: Thu Dec 8 14:47:56 2016 -0800

----------------------------------------------------------------------
 .../TopEntriesFunctionCollector.java            |  43 +-----
 .../TopEntriesFunctionCollectorJUnitTest.java   | 137 +------------------
 2 files changed, 4 insertions(+), 176 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/1d951e33/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollector.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollector.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollector.java
index d4a7008..66c4c0a 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollector.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollector.java
@@ -47,9 +47,6 @@ public class TopEntriesFunctionCollector
   // Use this instance to perform reduce operation
   final CollectorManager<TopEntriesCollector> manager;
 
-  // latch to wait till all results are collected
-  private final CountDownLatch waitForResults = new CountDownLatch(1);
-
   final String id;
 
   // Instance of gemfire cache to check status and other utility methods
@@ -83,36 +80,11 @@ public class TopEntriesFunctionCollector
 
   @Override
   public TopEntries getResult() throws FunctionException {
-    try {
-      waitForResults.await();
-    } catch (InterruptedException e) {
-      logger.debug("Interrupted while waiting for result collection", e);
-      Thread.currentThread().interrupt();
-      if (cache != null) {
-        cache.getCancelCriterion().checkCancelInProgress(e);
-      }
-      throw new FunctionException(e);
-    }
-
     return aggregateResults();
   }
 
   @Override
   public TopEntries getResult(long timeout, TimeUnit unit) throws FunctionException {
-    try {
-      boolean result = waitForResults.await(timeout, unit);
-      if (!result) {
-        throw new FunctionException("Did not receive results from all members within wait time");
-      }
-    } catch (InterruptedException e) {
-      logger.debug("Interrupted while waiting for result collection", e);
-      Thread.currentThread().interrupt();
-      if (cache != null) {
-        cache.getCancelCriterion().checkCancelInProgress(e);
-      }
-      throw new FunctionException(e);
-    }
-
     return aggregateResults();
   }
 
@@ -128,20 +100,11 @@ public class TopEntriesFunctionCollector
   }
 
   @Override
-  public void endResults() {
-    synchronized (subResults) {
-      waitForResults.countDown();
-    }
-  }
+  public void endResults() {}
 
   @Override
   public void clearResults() {
     synchronized (subResults) {
-      if (waitForResults.getCount() == 0) {
-        throw new IllegalStateException(
-            "This collector is closed and cannot accept anymore results");
-      }
-
       subResults.clear();
     }
   }
@@ -149,10 +112,6 @@ public class TopEntriesFunctionCollector
   @Override
   public void addResult(DistributedMember memberID, TopEntriesCollector resultOfSingleExecution) {
     synchronized (subResults) {
-      if (waitForResults.getCount() == 0) {
-        throw new IllegalStateException(
-            "This collector is closed and cannot accept anymore results");
-      }
       subResults.add(resultOfSingleExecution);
     }
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/1d951e33/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollectorJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollectorJUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollectorJUnitTest.java
index af868e2..bf08877 100644
--- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollectorJUnitTest.java
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesFunctionCollectorJUnitTest.java
@@ -63,25 +63,8 @@ public class TopEntriesFunctionCollectorJUnitTest {
   @Test
   public void testGetResultsBlocksTillEnd() throws Exception {
     final TopEntriesFunctionCollector collector = new TopEntriesFunctionCollector();
-    final CountDownLatch insideThread = new CountDownLatch(1);
-    final CountDownLatch resultReceived = new CountDownLatch(1);
-    Thread resultClient = new Thread(new Runnable() {
-      @Override
-      public void run() {
-        insideThread.countDown();
-        collector.getResult();
-        resultReceived.countDown();
-      }
-    });
-    resultClient.start();
-
-    insideThread.await(1, TimeUnit.SECONDS);
-    assertEquals(0, insideThread.getCount());
-    assertEquals(1, resultReceived.getCount());
-
-    collector.endResults();
-    resultReceived.await(1, TimeUnit.SECONDS);
-    assertEquals(0, resultReceived.getCount());
+    TopEntries merged = collector.getResult();
+    assertEquals(0, merged.size());
   }
 
   @Test
@@ -94,111 +77,11 @@ public class TopEntriesFunctionCollectorJUnitTest {
     final CountDownLatch resultReceived = new CountDownLatch(1);
 
     final AtomicReference<TopEntries> result = new AtomicReference<>();
-
-    Thread resultClient = new Thread(new Runnable() {
-      @Override
-      public void run() {
-        insideThread.countDown();
-        result.set(collector.getResult(1, TimeUnit.SECONDS));
-        resultReceived.countDown();
-      }
-    });
-    resultClient.start();
-
-    insideThread.await(1, TimeUnit.SECONDS);
-    assertEquals(0, insideThread.getCount());
-    assertEquals(1, resultReceived.getCount());
-
-    collector.endResults();
-
-    resultReceived.await(1, TimeUnit.SECONDS);
-    assertEquals(0, resultReceived.getCount());
-
-    TopEntries merged = result.get();
+    TopEntries merged = collector.getResult(1, TimeUnit.SECONDS);
     assertEquals(4, merged.size());
     TopEntriesJUnitTest.verifyResultOrder(merged.getHits(), r1_1, r2_1, r1_2, r2_2);
   }
 
-  @Test(expected = FunctionException.class)
-  public void testGetResultsWaitInterrupted() throws Exception {
-    interruptWhileWaiting(false);
-  }
-
-  @Test(expected = FunctionException.class)
-  public void testGetResultsTimedWaitInterrupted() throws Exception {
-    interruptWhileWaiting(false);
-  }
-
-  private void interruptWhileWaiting(final boolean timedWait)
-      throws InterruptedException, Exception {
-    GemFireCacheImpl mockCache = mock(GemFireCacheImpl.class);
-    final TopEntriesFunctionCollector collector = new TopEntriesFunctionCollector(null, mockCache);
-
-    final CountDownLatch insideThread = new CountDownLatch(1);
-    final CountDownLatch endGetResult = new CountDownLatch(1);
-    final AtomicReference<Exception> exception = new AtomicReference<>();
-
-    Thread resultClient = new Thread(new Runnable() {
-      @Override
-      public void run() {
-        insideThread.countDown();
-        try {
-          if (timedWait) {
-            collector.getResult(1, TimeUnit.SECONDS);
-          } else {
-            collector.getResult();
-          }
-        } catch (FunctionException e) {
-          exception.set(e);
-          endGetResult.countDown();
-        }
-      }
-    });
-    resultClient.start();
-
-    insideThread.await(1, TimeUnit.SECONDS);
-    assertEquals(0, insideThread.getCount());
-    assertEquals(1, endGetResult.getCount());
-
-    CancelCriterion mockCriterion = mock(CancelCriterion.class);
-    when(mockCache.getCancelCriterion()).thenReturn(mockCriterion);
-    resultClient.interrupt();
-    endGetResult.await(1, TimeUnit.SECONDS);
-    assertEquals(0, endGetResult.getCount());
-    throw exception.get();
-  }
-
-  @Test(expected = FunctionException.class)
-  public void expectErrorAfterWaitTime() throws Exception {
-    final TopEntriesFunctionCollector collector = new TopEntriesFunctionCollector(null);
-
-    final CountDownLatch insideThread = new CountDownLatch(1);
-    final CountDownLatch endGetResult = new CountDownLatch(1);
-    final AtomicReference<Exception> exception = new AtomicReference<>();
-
-    Thread resultClient = new Thread(new Runnable() {
-      @Override
-      public void run() {
-        insideThread.countDown();
-        try {
-          collector.getResult(10, TimeUnit.MILLISECONDS);
-        } catch (FunctionException e) {
-          exception.set(e);
-          endGetResult.countDown();
-        }
-      }
-    });
-    resultClient.start();
-
-    insideThread.await(1, TimeUnit.SECONDS);
-    assertEquals(0, insideThread.getCount());
-    assertEquals(1, endGetResult.getCount());
-
-    endGetResult.await(1, TimeUnit.SECONDS);
-    assertEquals(0, endGetResult.getCount());
-    throw exception.get();
-  }
-
   @Test
   public void mergeShardAndLimitResults() throws Exception {
     LuceneFunctionContext<TopEntriesCollector> context =
@@ -299,20 +182,6 @@ public class TopEntriesFunctionCollectorJUnitTest {
     collector.getResult();
   }
 
-  @Test(expected = IllegalStateException.class)
-  public void addResultDisallowedAfterEndResult() {
-    TopEntriesFunctionCollector collector = new TopEntriesFunctionCollector();
-    collector.endResults();
-    collector.addResult(null, new TopEntriesCollector(null));
-  }
-
-  @Test(expected = IllegalStateException.class)
-  public void clearResultDisallowedAfterEndResult() {
-    TopEntriesFunctionCollector collector = new TopEntriesFunctionCollector();
-    collector.endResults();
-    collector.clearResults();
-  }
-
   @Test
   public void testCollectorName() {
     GemFireCacheImpl mockCache = mock(GemFireCacheImpl.class);


[22/50] [abbrv] geode git commit: GEODE-2201 Make UITests a bit more resilient

Posted by kl...@apache.org.
GEODE-2201 Make UITests a bit more resilient

- Increase some timeouts
- Avoid StaleElementReferenceExceptions by retrying the element
  retrieval.


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

Branch: refs/heads/feature/GEODE-1930
Commit: d4276136337d2c9bee7336bafa281f2301af2a40
Parents: 1d951e3
Author: Jens Deppe <jd...@pivotal.io>
Authored: Thu Dec 8 20:56:44 2016 -0800
Committer: Jens Deppe <jd...@pivotal.io>
Committed: Thu Dec 8 20:56:44 2016 -0800

----------------------------------------------------------------------
 .../tests/rules/ScreenshotOnFailureRule.java    |  2 +-
 .../tools/pulse/tests/rules/WebDriverRule.java  |  4 +-
 .../tools/pulse/tests/ui/PulseTestUtils.java    | 54 +++++++++++---------
 3 files changed, 33 insertions(+), 27 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/d4276136/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java
index 91465f0..3728015 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java
@@ -47,7 +47,7 @@ public class ScreenshotOnFailureRule extends TestWatcher {
       try {
         File screenshot = new File("build/screenshots/" + screenshotName + ".png");
         FileUtils.copyFile(tempFile, screenshot);
-        System.out.println("Screenshot saved to: " + screenshot.getCanonicalPath());
+        System.err.println("Screenshot saved to: " + screenshot.getCanonicalPath());
       } catch (IOException e) {
         throw new Error(e);
       }

http://git-wip-us.apache.org/repos/asf/geode/blob/d4276136/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java
index e273557..8a4e7f4 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java
@@ -98,8 +98,8 @@ public class WebDriverRule extends ExternalResource {
 
     driver = new PhantomJSDriver(capabilities);
     driver.manage().window().maximize();
-    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
-    driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
+    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
+    driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
   }
 
   public WebElement waitForElementById(final String id) {

http://git-wip-us.apache.org/repos/asf/geode/blob/d4276136/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java
index c6ed3ff..076229e 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseTestUtils.java
@@ -25,7 +25,9 @@ import java.util.TreeMap;
 import java.util.function.Supplier;
 
 import org.openqa.selenium.By;
+import org.openqa.selenium.StaleElementReferenceException;
 import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebDriverException;
 import org.openqa.selenium.WebElement;
 import org.openqa.selenium.interactions.Actions;
 import org.openqa.selenium.support.ui.ExpectedCondition;
@@ -56,38 +58,42 @@ public final class PulseTestUtils {
   public static int maxWaitTime = 30;
 
   public static WebElement waitForElementWithId(String id) {
+    return waitForElement(By.id(id));
+  }
+
+  public static WebElement waitForElement(By by) {
     WebElement element = (new WebDriverWait(driverProvider.get(), maxWaitTime))
-        .until(new ExpectedCondition<WebElement>() {
-          @Override
-          public WebElement apply(WebDriver d) {
-            return d.findElement(By.id(id));
-          }
-        });
+      .until((ExpectedCondition<WebElement>) d -> d.findElement(by));
     assertNotNull(element);
     return element;
   }
 
-
-  public static WebElement findElementUsingXpath(String xpath) {
-    return getDriver().findElement(By.xpath(xpath));
-  }
-
   public static void clickElementUsingId(String id) {
-    waitForElementWithId(id).click();
+    WebDriverException lastException = null;
+    int attempts = 3;
+    while (attempts > 0) {
+      try {
+        waitForElementWithId(id).click();
+        return;
+      } catch (StaleElementReferenceException sere) {
+        lastException = sere;
+      }
+      attempts++;
+    }
+
+    throw lastException;
   }
 
   public static void clickElementUsingXpath(String xpath) {
-    findElementUsingXpath(xpath).click();
+    findElementByXpath(xpath).click();
   }
 
-
   public static void sendKeysUsingId(String Id, String textToEnter) {
     waitForElementWithId(Id).sendKeys(textToEnter);
   }
 
-
   public static WebElement findElementByXpath(String xpath) {
-    return getDriver().findElement(By.xpath(xpath));
+    return waitForElement(By.xpath(xpath));
   }
 
   public static String getTextUsingXpath(String xpath) {
@@ -99,25 +105,25 @@ public final class PulseTestUtils {
   }
 
   public static String getPersistanceEnabled(Region r) {
-    String persitance = null;
+    String persistence = null;
 
     if (r.getPersistentEnabled()) {
-      persitance = "ON";
+      persistence = "ON";
     } else if (!r.getPersistentEnabled()) {
-      persitance = "OFF";
+      persistence = "OFF";
     }
-    return persitance;
+    return persistence;
   }
 
   public static String getPersistanceEnabled(String trueOrFalse) {
-    String persitance = null;
+    String persistence = null;
 
     if (trueOrFalse.contains("true")) {
-      persitance = "ON";
+      persistence = "ON";
     } else if (trueOrFalse.contains("false")) {
-      persitance = "OFF";
+      persistence = "OFF";
     }
-    return persitance;
+    return persistence;
   }
 
   public static void validateServerGroupGridData() {


[11/50] [abbrv] geode git commit: GEODE-2112: UITests actually take screenshots on failure

Posted by kl...@apache.org.
GEODE-2112: UITests actually take screenshots on failure

This closes #301


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

Branch: refs/heads/feature/GEODE-1930
Commit: 67dafd8e81738a32e2fbf0140f310c9936346a20
Parents: 0494b31
Author: Jared Stewart <js...@pivotal.io>
Authored: Thu Dec 1 11:01:09 2016 -0800
Committer: Kirk Lund <kl...@apache.org>
Committed: Wed Dec 7 15:37:15 2016 -0800

----------------------------------------------------------------------
 .../tests/rules/ScreenshotOnFailureRule.java    |  2 +-
 .../tools/pulse/tests/rules/WebDriverRule.java  |  5 ----
 .../pulse/tests/ui/PulseAnonymousUserTest.java  | 28 +++++---------------
 .../tools/pulse/tests/ui/PulseAuthTest.java     |  6 ++++-
 .../pulse/tests/ui/PulseAutomatedTest.java      |  5 ++++
 .../tools/pulse/tests/ui/PulseNoAuthTest.java   |  6 ++++-
 6 files changed, 23 insertions(+), 29 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/67dafd8e/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java
index 3728015..91465f0 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/ScreenshotOnFailureRule.java
@@ -47,7 +47,7 @@ public class ScreenshotOnFailureRule extends TestWatcher {
       try {
         File screenshot = new File("build/screenshots/" + screenshotName + ".png");
         FileUtils.copyFile(tempFile, screenshot);
-        System.err.println("Screenshot saved to: " + screenshot.getCanonicalPath());
+        System.out.println("Screenshot saved to: " + screenshot.getCanonicalPath());
       } catch (IOException e) {
         throw new Error(e);
       }

http://git-wip-us.apache.org/repos/asf/geode/blob/67dafd8e/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java
index 03d91ab..e273557 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/rules/WebDriverRule.java
@@ -52,15 +52,10 @@ public class WebDriverRule extends ExternalResource {
     return this.driver;
   }
 
-  @Rule
-  public ScreenshotOnFailureRule screenshotOnFailureRule =
-      new ScreenshotOnFailureRule(() -> driver);
-
   public String getPulseURL() {
     return pulseUrl;
   }
 
-
   @Override
   protected void before() throws Throwable {
     setUpWebDriver();

http://git-wip-us.apache.org/repos/asf/geode/blob/67dafd8e/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAnonymousUserTest.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAnonymousUserTest.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAnonymousUserTest.java
index 4d255c8..680b11f 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAnonymousUserTest.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAnonymousUserTest.java
@@ -16,18 +16,13 @@
 
 package org.apache.geode.tools.pulse.tests.ui;
 
-import static org.assertj.core.api.Assertions.*;
+import static org.assertj.core.api.Assertions.assertThat;
 
-import java.io.InputStream;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-
-import com.jayway.awaitility.Awaitility;
+import org.apache.geode.test.junit.categories.UITest;
+import org.apache.geode.tools.pulse.tests.rules.ScreenshotOnFailureRule;
 import org.apache.geode.tools.pulse.tests.rules.ServerRule;
 import org.apache.geode.tools.pulse.tests.rules.WebDriverRule;
-import org.junit.AfterClass;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.FixMethodOrder;
 import org.junit.Rule;
@@ -35,18 +30,7 @@ import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.junit.runners.MethodSorters;
 import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
-import org.openqa.selenium.phantomjs.PhantomJSDriver;
-import org.openqa.selenium.remote.DesiredCapabilities;
-import org.openqa.selenium.support.ui.ExpectedCondition;
-import org.openqa.selenium.support.ui.WebDriverWait;
-
-import org.apache.geode.internal.admin.SSLConfig;
-import org.apache.geode.management.internal.JettyHelper;
-import org.apache.geode.test.junit.categories.UITest;
-import org.apache.geode.tools.pulse.tests.PulseTestLocators;
-import org.apache.geode.tools.pulse.tests.Server;
 
 @Category(UITest.class)
 @FixMethodOrder(MethodSorters.JVM)
@@ -58,6 +42,10 @@ public class PulseAnonymousUserTest {
   @Rule
   public WebDriverRule webDriverRule = new WebDriverRule(serverRule.getPulseURL());
 
+  @Rule
+  public ScreenshotOnFailureRule screenshotOnFailureRule =
+      new ScreenshotOnFailureRule(() -> webDriverRule.getDriver());
+
   @Before
   public void setup() {
     webDriverRule.getDriver().get(serverRule.getPulseURL() + "/clusterDetail.html");
@@ -66,8 +54,6 @@ public class PulseAnonymousUserTest {
   @Test
   public void userCanGetToPulseLoginPage() {
     webDriverRule.getDriver().get(serverRule.getPulseURL() + "/Login.html");
-    System.err.println("Pulse url: " + serverRule.getPulseURL());
-    System.err.println(webDriverRule.getDriver().getPageSource().toString());
 
     WebElement userNameElement = webDriverRule.getDriver().findElement(By.id("user_name"));
     WebElement passwordElement = webDriverRule.getDriver().findElement(By.id("user_password"));

http://git-wip-us.apache.org/repos/asf/geode/blob/67dafd8e/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAuthTest.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAuthTest.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAuthTest.java
index fc9719d..4a82d1b 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAuthTest.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAuthTest.java
@@ -16,10 +16,10 @@
 package org.apache.geode.tools.pulse.tests.ui;
 
 import org.apache.geode.test.junit.categories.UITest;
+import org.apache.geode.tools.pulse.tests.rules.ScreenshotOnFailureRule;
 import org.apache.geode.tools.pulse.tests.rules.ServerRule;
 import org.apache.geode.tools.pulse.tests.rules.WebDriverRule;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.FixMethodOrder;
 import org.junit.Rule;
@@ -38,6 +38,10 @@ public class PulseAuthTest extends PulseBase {
   public WebDriverRule webDriverRule =
       new WebDriverRule("pulseUser", "12345", serverRule.getPulseURL());
 
+  @Rule
+  public ScreenshotOnFailureRule screenshotOnFailureRule =
+      new ScreenshotOnFailureRule(this::getWebDriver);
+
   @Override
   public WebDriver getWebDriver() {
     return webDriverRule.getDriver();

http://git-wip-us.apache.org/repos/asf/geode/blob/67dafd8e/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAutomatedTest.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAutomatedTest.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAutomatedTest.java
index 8df0543..7c42e44 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAutomatedTest.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseAutomatedTest.java
@@ -28,6 +28,7 @@ import java.text.SimpleDateFormat;
 import java.util.List;
 
 import org.apache.geode.tools.pulse.tests.DataBrowserResultLoader;
+import org.apache.geode.tools.pulse.tests.rules.ScreenshotOnFailureRule;
 import org.apache.geode.tools.pulse.tests.rules.ServerRule;
 import org.apache.geode.tools.pulse.tests.rules.WebDriverRule;
 import org.junit.Assert;
@@ -56,6 +57,10 @@ public class PulseAutomatedTest extends PulseBase {
   public WebDriverRule webDriverRule =
       new WebDriverRule("pulseUser", "12345", serverRule.getPulseURL());
 
+  @Rule
+  public ScreenshotOnFailureRule screenshotOnFailureRule =
+      new ScreenshotOnFailureRule(this::getWebDriver);
+
   @Override
   public WebDriver getWebDriver() {
     return webDriverRule.getDriver();

http://git-wip-us.apache.org/repos/asf/geode/blob/67dafd8e/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseNoAuthTest.java
----------------------------------------------------------------------
diff --git a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseNoAuthTest.java b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseNoAuthTest.java
index adcb50f..03265ef 100644
--- a/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseNoAuthTest.java
+++ b/geode-pulse/src/test/java/org/apache/geode/tools/pulse/tests/ui/PulseNoAuthTest.java
@@ -16,10 +16,10 @@
 package org.apache.geode.tools.pulse.tests.ui;
 
 import org.apache.geode.test.junit.categories.UITest;
+import org.apache.geode.tools.pulse.tests.rules.ScreenshotOnFailureRule;
 import org.apache.geode.tools.pulse.tests.rules.ServerRule;
 import org.apache.geode.tools.pulse.tests.rules.WebDriverRule;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.FixMethodOrder;
 import org.junit.Rule;
@@ -38,6 +38,10 @@ public class PulseNoAuthTest extends PulseBase {
   public WebDriverRule webDriverRule =
       new WebDriverRule("admin", "admin", serverRule.getPulseURL());
 
+  @Rule
+  public ScreenshotOnFailureRule screenshotOnFailureRule =
+      new ScreenshotOnFailureRule(this::getWebDriver);
+
   @Override
   public WebDriver getWebDriver() {
     return webDriverRule.getDriver();