Return-Path: X-Original-To: archive-asf-public-internal@cust-asf2.ponee.io Delivered-To: archive-asf-public-internal@cust-asf2.ponee.io Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183]) by cust-asf2.ponee.io (Postfix) with ESMTP id BC199200C26 for ; Fri, 20 Jan 2017 23:53:04 +0100 (CET) Received: by cust-asf.ponee.io (Postfix) id BAC6A160B48; Fri, 20 Jan 2017 22:53:04 +0000 (UTC) Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by cust-asf.ponee.io (Postfix) with SMTP id C0EB8160B69 for ; Fri, 20 Jan 2017 23:53:01 +0100 (CET) Received: (qmail 15263 invoked by uid 500); 20 Jan 2017 22:52:59 -0000 Mailing-List: contact commits-help@geode.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@geode.apache.org Delivered-To: mailing list commits@geode.apache.org Received: (qmail 13997 invoked by uid 99); 20 Jan 2017 22:52:58 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Fri, 20 Jan 2017 22:52:58 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id D2DB5F171A; Fri, 20 Jan 2017 22:52:58 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: klund@apache.org To: commits@geode.apache.org Date: Fri, 20 Jan 2017 22:53:42 -0000 Message-Id: In-Reply-To: <62faa9e762fb4148835ed6a9eb2bd7b0@git.apache.org> References: <62faa9e762fb4148835ed6a9eb2bd7b0@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [46/50] [abbrv] geode git commit: Convert from ManagementTestCase to ManagementTestRule archived-at: Fri, 20 Jan 2017 22:53:04 -0000 http://git-wip-us.apache.org/repos/asf/geode/blob/17d2c64c/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 otherMemberSet = - existingCache.getDistributionManager().getOtherDistributionManagerIds(); - - Iterator 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 getManagedNodeList() { + protected static List 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 getMBeanProxy(final ObjectName objectName, Class interfaceClass) { + SystemManagementService service = + (SystemManagementService) ManagementService.getManagementService(getCache()); + return service.getMBeanProxy(objectName, interfaceClass); + } } http://git-wip-us.apache.org/repos/asf/geode/blob/17d2c64c/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 getOtherNormalMembers() { + Set allMembers = new HashSet<>(getAllNormalMembers()); + allMembers.remove(getDistributedMember()); + return allMembers; + } + + public Set 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/17d2c64c/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/17d2c64c/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 ""; +} http://git-wip-us.apache.org/repos/asf/geode/blob/17d2c64c/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 notificationList = Collections.synchronizedList(new ArrayList()); + List notificationList = + Collections.synchronizedList(new ArrayList()); - @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(); + } } }