geode-commits mailing list archives

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

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

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

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

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


Mime
View raw message