You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by ds...@apache.org on 2017/08/31 01:25:38 UTC

[01/47] geode git commit: GEODE-3277: Fix test failure caused by ServerState changes

Repository: geode
Updated Branches:
  refs/heads/feature/GEODE-3543 762f39a6e -> adfac332a


GEODE-3277: Fix test failure caused by ServerState changes


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

Branch: refs/heads/feature/GEODE-3543
Commit: 73a847a4b22239414db0ae9d973673f6a03fdcf0
Parents: ca2f20b
Author: Ken Howe <kh...@pivotal.io>
Authored: Mon Aug 28 15:51:47 2017 -0700
Committer: Ken Howe <kh...@pivotal.io>
Committed: Mon Aug 28 15:53:02 2017 -0700

----------------------------------------------------------------------
 .../java/org/apache/geode/distributed/ServerLauncherTest.java    | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/73a847a4/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java b/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java
index 696cc9b..61d0596 100755
--- a/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java
@@ -25,7 +25,6 @@ import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import java.net.InetAddress;
 import java.util.Collections;
 
 import org.junit.Before;
@@ -271,8 +270,7 @@ public class ServerLauncherTest {
 
     launcher.startCacheServer(cache);
 
-    // getServerBindAddress() returns the localhost address when set to null in the ServerState
-    verify(cacheServer, times(1)).setBindAddress(InetAddress.getLocalHost().getCanonicalHostName());
+    verify(cacheServer, times(1)).setBindAddress(anyString());
     verify(cacheServer, times(1)).setPort(eq(11235));
     verify(cacheServer, times(1)).start();
   }


[32/47] geode git commit: GEODE-3519 servers are not locking on some ops initiated by clients

Posted by ds...@apache.org.
GEODE-3519 servers are not locking on some ops initiated by clients

While investigating dlocktoken cleanup I discovered that a number of
operations coming from a client were not locking entries for Scope.GLOBAL
regions on servers.  Only put, putIfAbsent and variants of replace were
obtaining locks.


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

Branch: refs/heads/feature/GEODE-3543
Commit: 2637bd8794b76e048f2fb13007ad0a50842059d8
Parents: 4ac4600
Author: Bruce Schuchardt <bs...@pivotal.io>
Authored: Tue Aug 29 14:07:52 2017 -0700
Committer: Bruce Schuchardt <bs...@pivotal.io>
Committed: Tue Aug 29 14:08:53 2017 -0700

----------------------------------------------------------------------
 .../geode/internal/cache/DistributedRegion.java |  49 +++++++
 .../geode/cache30/ClientServerCCEDUnitTest.java | 129 +++++++++++++++++--
 2 files changed, 170 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/2637bd87/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java b/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java
index d9cf1ed..e882ed1 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRegion.java
@@ -48,6 +48,7 @@ import org.apache.geode.cache.CacheWriter;
 import org.apache.geode.cache.CacheWriterException;
 import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.DiskAccessException;
+import org.apache.geode.cache.EntryExistsException;
 import org.apache.geode.cache.EntryNotFoundException;
 import org.apache.geode.cache.LossAction;
 import org.apache.geode.cache.MembershipAttributes;
@@ -1500,6 +1501,54 @@ public class DistributedRegion extends LocalRegion implements CacheDistributionA
   }
 
   @Override
+  public void basicBridgeRemove(Object key, Object expectedOldValue, Object p_callbackArg,
+      ClientProxyMembershipID memberId, boolean fromClient, EntryEventImpl clientEvent)
+      throws TimeoutException, EntryNotFoundException, CacheWriterException {
+    Lock lock = getDistributedLockIfGlobal(key);
+    try {
+      super.basicBridgeRemove(key, expectedOldValue, p_callbackArg, memberId, fromClient,
+          clientEvent);
+    } finally {
+      if (lock != null) {
+        logger.debug("releasing distributed lock on {}", key);
+        lock.unlock();
+        getLockService().freeResources(key);
+      }
+    }
+  }
+
+  @Override
+  public void basicBridgeDestroy(Object key, Object p_callbackArg, ClientProxyMembershipID memberId,
+      boolean fromClient, EntryEventImpl clientEvent)
+      throws TimeoutException, EntryNotFoundException, CacheWriterException {
+    Lock lock = getDistributedLockIfGlobal(key);
+    try {
+      super.basicBridgeDestroy(key, p_callbackArg, memberId, fromClient, clientEvent);
+    } finally {
+      if (lock != null) {
+        logger.debug("releasing distributed lock on {}", key);
+        lock.unlock();
+        getLockService().freeResources(key);
+      }
+    }
+  }
+
+  @Override
+  public void basicBridgeInvalidate(Object key, Object p_callbackArg,
+      ClientProxyMembershipID memberId, boolean fromClient, EntryEventImpl clientEvent)
+      throws TimeoutException, EntryNotFoundException, CacheWriterException {
+    Lock lock = getDistributedLockIfGlobal(key);
+    try {
+      super.basicBridgeInvalidate(key, p_callbackArg, memberId, fromClient, clientEvent);
+    } finally {
+      if (lock != null) {
+        logger.debug("releasing distributed lock on {}", key);
+        lock.unlock();
+      }
+    }
+  }
+
+  @Override
   protected void basicDestroy(EntryEventImpl event, boolean cacheWrite, Object expectedOldValue)
       throws EntryNotFoundException, CacheWriterException, TimeoutException {
     // disallow local destruction for mirrored keysvalues regions

http://git-wip-us.apache.org/repos/asf/geode/blob/2637bd87/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java b/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java
index b4224e0..b9301dd 100644
--- a/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java
@@ -14,6 +14,7 @@
  */
 package org.apache.geode.cache30;
 
+import static java.util.concurrent.TimeUnit.SECONDS;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static org.junit.Assert.*;
 
@@ -27,23 +28,30 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 
 import org.apache.geode.cache.AttributesMutator;
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.ExpirationAction;
 import org.apache.geode.cache.ExpirationAttributes;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.Scope;
+import org.apache.geode.distributed.internal.locks.DLockService;
+import org.apache.geode.distributed.internal.locks.DistributedLockStats;
+import org.apache.geode.internal.cache.CachePerfStats;
+import org.apache.geode.internal.cache.DistributedRegion;
+import org.apache.geode.test.dunit.AsyncInvocation;
 import org.apache.geode.test.dunit.IgnoredException;
 import org.apache.geode.test.junit.categories.ClientServerTest;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.apache.geode.cache.AttributesFactory;
-import org.apache.geode.cache.CacheListener;
 import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.EntryEvent;
 import org.apache.geode.cache.InterestResultPolicy;
 import org.apache.geode.cache.PartitionAttributesFactory;
-import org.apache.geode.cache.Scope;
 import org.apache.geode.cache.client.ClientCache;
 import org.apache.geode.cache.client.ClientCacheFactory;
 import org.apache.geode.cache.client.ClientRegionFactory;
@@ -98,6 +106,106 @@ public class ClientServerCCEDUnitTest extends JUnit4CacheTestCase {
   }
 
 
+  /**
+   * GEODE-3519 servers are not locking on remove or invalidate ops initiated by clients
+   * <p>
+   * This test sets up two servers each with a client attached. The clients perform operations on
+   * the same key in a region which, in the servers, has Scope.GLOBAL. There should be no conflation
+   * and each operation should obtain a lock.
+   * 
+   * @throws Exception
+   */
+  @Test
+  public void testClientEventsAreNotConflatedByGlobalRegionOnServer() throws Exception {
+    VM[] serverVMs = new VM[] {Host.getHost(0).getVM(0), Host.getHost(0).getVM(1)};
+    VM[] clientVMs = new VM[] {Host.getHost(0).getVM(2), Host.getHost(0).getVM(3)};
+    final String name = this.getUniqueName() + "Region";
+
+    int serverPorts[] = new int[] {createServerRegion(serverVMs[0], name, true, Scope.GLOBAL),
+        createServerRegion(serverVMs[1], name, true, Scope.GLOBAL)};
+
+    for (int i = 0; i < clientVMs.length; i++) {
+      createClientRegion(clientVMs[i], name, serverPorts[i], false,
+          ClientRegionShortcut.CACHING_PROXY, false);
+    }
+
+    getBlackboard().initBlackboard();
+
+    final int numIterations = 500;
+
+    AsyncInvocation[] asyncInvocations = new AsyncInvocation[clientVMs.length];
+    for (int i = 0; i < clientVMs.length; i++) {
+      final String clientGateName = "client" + i + "Ready";
+      asyncInvocations[i] = clientVMs[i].invokeAsync("doOps Thread", () -> {
+        doOps(name, numIterations, clientGateName);
+      });
+      getBlackboard().waitForGate(clientGateName, 30, SECONDS);
+    }
+
+    getBlackboard().signalGate("proceed");
+
+    for (int i = 0; i < asyncInvocations.length; i++) {
+      asyncInvocations[i].join();
+    }
+
+    for (int i = 0; i < serverVMs.length; i++) {
+      serverVMs[i].invoke("verify thread", () -> {
+        verifyServerState(name, numIterations);
+      });
+    }
+  }
+
+  private void verifyServerState(String name, int numIterations) {
+    Cache cache = CacheFactory.getAnyInstance();
+    DistributedRegion region = (DistributedRegion) cache.getRegion(name);
+    CachePerfStats stats = region.getCachePerfStats();
+    assertEquals(0, stats.getConflatedEventsCount());
+
+    DLockService dLockService = (DLockService) region.getLockService();
+    DistributedLockStats distributedLockStats = dLockService.getStats();
+    assertEquals(numIterations, distributedLockStats.getLockReleasesCompleted());
+  }
+
+  private void doOps(String name, int numIterations, String clientGateName) {
+    ClientCache cache = ClientCacheFactory.getAnyInstance();
+    Region region = cache.getRegion(name);
+    getBlackboard().signalGate(clientGateName);
+    try {
+      getBlackboard().waitForGate("proceed", 30, SECONDS);
+    } catch (TimeoutException | InterruptedException e) {
+      throw new RuntimeException("failed to start", e);
+    }
+    String key = "lockingKey";
+    String value = "lockingValue";
+    for (int j = 0; j < numIterations; j++) {
+      int operation = j % 5;
+      switch (operation) {
+        case 0:
+          region.remove(key);
+          break;
+        case 1:
+          region.putIfAbsent(key, value);
+          break;
+        case 2:
+          region.invalidate(key);
+          break;
+        case 3:
+          region.replace(key, value);
+          break;
+        case 4:
+          region.replace(key, value, value);
+          break;
+//        case 5:
+//          remove(k,v) can't be included in this test as it checks the old value
+//          against what is in the local cache before sending the operation to the server
+//          region.remove(key, value);
+//          break;
+        default:
+          throw new RuntimeException("" + j + " % 5 == " + operation + "?");
+      }
+    }
+  }
+
   @Test
   public void testClientDoesNotExpireEntryPrematurely() throws Exception {
     Host host = Host.getHost(0);
@@ -144,8 +252,8 @@ public class ClientServerCCEDUnitTest extends JUnit4CacheTestCase {
 
         final long expirationTime = System.currentTimeMillis() + (expirationSeconds * 1000);
 
-        Awaitility.await("waiting for object to expire")
-            .atMost(expirationSeconds * 2, TimeUnit.SECONDS).until(() -> {
+        Awaitility.await("waiting for object to expire").atMost(expirationSeconds * 2, SECONDS)
+            .until(() -> {
               return expirationTimeMillis[0] != null;
             });
 
@@ -246,7 +354,7 @@ public class ClientServerCCEDUnitTest extends JUnit4CacheTestCase {
       vm1.invoke(() -> {
         PRTombstoneMessageObserver mo =
             (PRTombstoneMessageObserver) DistributionMessageObserver.getInstance();
-        Awaitility.await().atMost(60, TimeUnit.SECONDS).until(() -> {
+        Awaitility.await().atMost(60, SECONDS).until(() -> {
           return mo.tsMessageProcessed >= 1;
         });
         assertTrue("Tombstone GC message is not expected.", mo.thName.contains(
@@ -297,7 +405,7 @@ public class ClientServerCCEDUnitTest extends JUnit4CacheTestCase {
         PRTombstoneMessageObserver mo =
             (PRTombstoneMessageObserver) DistributionMessageObserver.getInstance();
         // Should receive tombstone message for each bucket.
-        Awaitility.await().atMost(60, TimeUnit.SECONDS).until(() -> {
+        Awaitility.await().atMost(60, SECONDS).until(() -> {
           return mo.prTsMessageProcessed >= 2;
         });
         assertEquals("Tombstone GC message is expected.", 2, mo.prTsMessageProcessed);
@@ -818,12 +926,17 @@ public class ClientServerCCEDUnitTest extends JUnit4CacheTestCase {
 
 
   private int createServerRegion(VM vm, final String regionName, final boolean replicatedRegion) {
+    return createServerRegion(vm, regionName, replicatedRegion, Scope.DISTRIBUTED_ACK);
+  }
+
+  private int createServerRegion(VM vm, final String regionName, final boolean replicatedRegion,
+                                 Scope regionScope) {
     SerializableCallable createRegion = new SerializableCallable() {
       public Object call() throws Exception {
         // TombstoneService.VERBOSE = true;
         AttributesFactory af = new AttributesFactory();
         if (replicatedRegion) {
-          af.setScope(Scope.DISTRIBUTED_ACK);
+          af.setScope(regionScope);
           af.setDataPolicy(DataPolicy.REPLICATE);
         } else {
           af.setDataPolicy(DataPolicy.PARTITION);


[10/47] geode git commit: GEODE-3436: Restore refactoring of CreateAlterDestroyRegionCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
new file mode 100644
index 0000000..e178d8c
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
@@ -0,0 +1,388 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION;
+import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER;
+import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_BIND_ADDRESS;
+import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_START;
+import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.awaitility.Awaitility.waitAtMost;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.text.MessageFormat;
+import java.util.Properties;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.Scope;
+import org.apache.geode.distributed.Locator;
+import org.apache.geode.distributed.internal.ClusterConfigurationService;
+import org.apache.geode.distributed.internal.InternalLocator;
+import org.apache.geode.internal.AvailablePort;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.MBeanJMXAdapter;
+import org.apache.geode.management.internal.ManagementConstants;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CommandResult;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+
+@Category(DistributedTest.class)
+public class DestroyRegionCommandDUnitTest extends CliCommandTestBase {
+  @Test
+  public void testDestroyDistributedRegion() {
+    setUpJmxManagerOnVm0ThenConnect(null);
+
+    for (int i = 1; i <= 2; i++) {
+      Host.getHost(0).getVM(i).invoke(() -> {
+        final Cache cache = getCache();
+
+        RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.PARTITION);
+        factory.create("Customer");
+
+        PartitionAttributesFactory paFactory = new PartitionAttributesFactory();
+        paFactory.setColocatedWith("Customer");
+        factory.setPartitionAttributes(paFactory.create());
+        factory.create("Order");
+      });
+    }
+
+    waitForRegionMBeanCreation("/Customer", 2);
+    waitForRegionMBeanCreation("/Order", 2);
+
+    // Test failure when region not found
+    String command = "destroy region --name=DOESNOTEXIST";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    CommandResult cmdResult = executeCommand(command);
+    String strr = commandResultToString(cmdResult);
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
+    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+    // Test unable to destroy with co-location
+    command = "destroy region --name=/Customer";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    cmdResult = executeCommand(command);
+    strr = commandResultToString(cmdResult);
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+    // Test success
+    command = "destroy region --name=/Order";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    cmdResult = executeCommand(command);
+    strr = commandResultToString(cmdResult);
+    assertTrue(stringContainsLine(strr, ".*Order.*destroyed successfully.*"));
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    command = "destroy region --name=/Customer";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    cmdResult = executeCommand(command);
+    strr = commandResultToString(cmdResult);
+    assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+  }
+
+  @Test
+  public void testDestroyLocalRegions() {
+    setUpJmxManagerOnVm0ThenConnect(null);
+
+    for (int i = 1; i <= 3; i++) {
+      Host.getHost(0).getVM(i).invoke(() -> {
+        final Cache cache = getCache();
+
+        RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+        factory.setScope(Scope.LOCAL);
+        factory.create("Customer");
+      });
+    }
+
+    waitForRegionMBeanCreation("/Customer", 3);
+
+    // Test failure when region not found
+    String command = "destroy region --name=DOESNOTEXIST";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    CommandResult cmdResult = executeCommand(command);
+    String strr = commandResultToString(cmdResult);
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
+    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+    command = "destroy region --name=/Customer";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    cmdResult = executeCommand(command);
+    strr = commandResultToString(cmdResult);
+    assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    for (int i = 1; i <= 3; i++) {
+      final int x = i;
+      Host.getHost(0).getVM(i).invoke(() -> {
+        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
+      });
+    }
+  }
+
+  @Test
+  public void testDestroyLocalAndDistributedRegions() {
+    setUpJmxManagerOnVm0ThenConnect(null);
+
+    for (int i = 1; i <= 2; i++) {
+      Host.getHost(0).getVM(i).invoke(() -> {
+        final Cache cache = getCache();
+        RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.PARTITION);
+        factory.create("Customer");
+        factory.create("Customer-2");
+        factory.create("Customer_3");
+      });
+    }
+
+    Host.getHost(0).getVM(3).invoke(() -> {
+      final Cache cache = getCache();
+      RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+      factory.setScope(Scope.LOCAL);
+      factory.create("Customer");
+      factory.create("Customer-2");
+      factory.create("Customer_3");
+    });
+
+    waitForRegionMBeanCreation("/Customer", 3);
+
+    // Test failure when region not found
+    String command = "destroy region --name=DOESNOTEXIST";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    CommandResult cmdResult = executeCommand(command);
+    String strr = commandResultToString(cmdResult);
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
+    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+    command = "destroy region --name=/Customer";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    cmdResult = executeCommand(command);
+    strr = commandResultToString(cmdResult);
+    assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    command = "destroy region --name=/Customer_3";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    cmdResult = executeCommand(command);
+    strr = commandResultToString(cmdResult);
+    assertTrue(stringContainsLine(strr, ".*Customer_3.*destroyed successfully.*"));
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    command = "destroy region --name=/Customer-2";
+    getLogWriter().info("testDestroyRegion command=" + command);
+    cmdResult = executeCommand(command);
+    strr = commandResultToString(cmdResult);
+    assertTrue(stringContainsLine(strr, ".*Customer-2.*destroyed successfully.*"));
+    getLogWriter().info("testDestroyRegion strr=" + strr);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    for (int i = 1; i <= 3; i++) {
+      final int x = i;
+      Host.getHost(0).getVM(i).invoke(() -> {
+        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
+        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer-2"));
+        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer_3"));
+      });
+    }
+  }
+
+  @Test
+  public void testDestroyRegionWithSharedConfig() {
+    disconnectAllFromDS();
+
+    final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
+    jmxPort = ports[0];
+    httpPort = ports[1];
+    try {
+      jmxHost = InetAddress.getLocalHost().getHostName();
+    } catch (UnknownHostException ignore) {
+      jmxHost = "localhost";
+    }
+
+
+    final String regionName = "testRegionSharedConfigRegion";
+    final String regionPath = "/" + regionName;
+    final String groupName = "testRegionSharedConfigGroup";
+
+    // Start the Locator and wait for shared configuration to be available
+    final int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+
+    final Properties locatorProps = new Properties();
+    locatorProps.setProperty(NAME, "Locator");
+    locatorProps.setProperty(MCAST_PORT, "0");
+    locatorProps.setProperty(LOG_LEVEL, "fine");
+    locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
+    locatorProps.setProperty(JMX_MANAGER, "true");
+    locatorProps.setProperty(JMX_MANAGER_START, "true");
+    locatorProps.setProperty(JMX_MANAGER_BIND_ADDRESS, String.valueOf(jmxHost));
+    locatorProps.setProperty(JMX_MANAGER_PORT, String.valueOf(jmxPort));
+    locatorProps.setProperty(HTTP_SERVICE_PORT, String.valueOf(httpPort));
+
+    Host.getHost(0).getVM(0).invoke(() -> {
+      final File locatorLogFile = new File("locator-" + locatorPort + ".log");
+      try {
+        final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locatorPort,
+            locatorLogFile, null, locatorProps);
+
+        waitAtMost(5, TimeUnit.SECONDS).until(locator::isSharedConfigurationRunning);
+      } catch (IOException ioex) {
+        fail("Unable to create a locator with a shared configuration");
+      }
+    });
+
+    connect(jmxHost, jmxPort, httpPort, getDefaultShell());
+
+    // Create a cache in VM 1
+    VM vm = Host.getHost(0).getVM(1);
+    vm.invoke(() -> {
+      Properties localProps = new Properties();
+      localProps.setProperty(MCAST_PORT, "0");
+      localProps.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
+      localProps.setProperty(GROUPS, groupName);
+      getSystem(localProps);
+      assertNotNull(getCache());
+    });
+
+    // Test creating the region
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, regionName);
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__STATISTICSENABLED, "true");
+    commandStringBuilder.addOption(CliStrings.GROUP, groupName);
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    // Make sure that the region has been registered with the Manager MXBean
+    waitForRegionMBeanCreation(regionPath, 1);
+
+    // Make sure the region exists in the shared config
+    Host.getHost(0).getVM(0).invoke(() -> {
+      ClusterConfigurationService sharedConfig =
+          ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
+      try {
+        assertTrue(
+            sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
+      } catch (Exception e) {
+        fail("Error occurred in cluster configuration service");
+      }
+    });
+
+    // Test destroying the region
+    commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
+    commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, regionName);
+    cmdResult = executeCommand(commandStringBuilder.toString());
+    getLogWriter().info("#SB" + commandResultToString(cmdResult));
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    // Make sure the region was removed from the shared config
+    Host.getHost(0).getVM(0).invoke(() -> {
+      ClusterConfigurationService sharedConfig =
+          ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
+      try {
+        assertFalse(
+            sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
+      } catch (Exception e) {
+        fail("Error occurred in cluster configuration service");
+      }
+    });
+
+
+    // Restart the data vm to make sure the region is not existing any more
+    vm = Host.getHost(0).getVM(1);
+    vm.invoke(() -> {
+      Cache cache = getCache();
+      assertNotNull(cache);
+      cache.close();
+      assertTrue(cache.isClosed());
+
+      Properties localProps = new Properties();
+      localProps.setProperty(MCAST_PORT, "0");
+      localProps.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
+      localProps.setProperty(GROUPS, groupName);
+      localProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
+      getSystem(localProps);
+      cache = getCache();
+      assertNotNull(cache);
+      Region region = cache.getRegion(regionName);
+      assertNull(region);
+
+      return null;
+    });
+  }
+
+  private void waitForRegionMBeanCreation(final String regionPath, final int mbeanCount) {
+    Host.getHost(0).getVM(0).invoke(() -> {
+      waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath, mbeanCount));
+    });
+  }
+
+  private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath, final int mbeanCount) {
+    return () -> {
+      try {
+        MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
+        String queryExp =
+            MessageFormat.format(ManagementConstants.OBJECTNAME__REGION_MXBEAN, regionPath, "*");
+        ObjectName queryExpON = new ObjectName(queryExp);
+        return mbeanServer.queryNames(null, queryExpON).size() == mbeanCount;
+      } catch (MalformedObjectNameException mone) {
+        getLogWriter().error(mone);
+        fail(mone.getMessage());
+        return false;
+      }
+    };
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index ac5058f..b19cfd0 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -128,7 +128,7 @@ public class TestCommand {
     createTestCommand("describe config --member=Member1", clusterRead);
     createTestCommand("export config --member=member1", clusterRead);
 
-    // CreateAlterDestroyRegionCommands
+    // CreateRegionCommand, AlterRegionCommand, DestroyRegionCommand
     createTestCommand("alter region --name=RegionA --eviction-max=5000", regionAManage);
     createTestCommand("create region --name=region12 --type=REPLICATE", dataManage);
     createTestCommand("create region --name=region123 --type=PARTITION_PERSISTENT", dataManage,


[40/47] geode git commit: GEODE-3472: Remove a great deal of commented-out code.

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/MemberGroupConverter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/MemberGroupConverter.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/MemberGroupConverter.java
index 96690e8..e961911 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/MemberGroupConverter.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/MemberGroupConverter.java
@@ -19,13 +19,13 @@ import java.util.List;
 import java.util.Set;
 import java.util.TreeSet;
 
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
-
 import org.springframework.shell.core.Completion;
 import org.springframework.shell.core.Converter;
 import org.springframework.shell.core.MethodTarget;
 
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
+
 /**
  * 
  * @since GemFire 7.0
@@ -34,20 +34,17 @@ public class MemberGroupConverter implements Converter<String> {
 
   @Override
   public boolean supports(Class<?> type, String optionContext) {
-    // System.out.println("MemberGroupConverter.supports("+type+","+optionContext+")");
     return String.class.equals(type) && ConverterHint.MEMBERGROUP.equals(optionContext);
   }
 
   @Override
   public String convertFromText(String value, Class<?> targetType, String optionContext) {
-    // System.out.println("MemberGroupConverter.convertFromText("+value+","+targetType+","+optionContext+")");
     return value;
   }
 
   @Override
   public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType,
       String existingData, String optionContext, MethodTarget target) {
-    // System.out.println("MemberGroupConverter.getAllPossibleValues("+existingData+","+targetType+","+optionContext+")");
     if (String.class.equals(targetType) && ConverterHint.MEMBERGROUP.equals(optionContext)) {
       String[] memberGroupNames = getMemberGroupNames();
 
@@ -60,7 +57,7 @@ public class MemberGroupConverter implements Converter<String> {
 
   public Set<String> getMemberGroups() {
     final Gfsh gfsh = Gfsh.getCurrentInstance();
-    final Set<String> memberGroups = new TreeSet<String>();
+    final Set<String> memberGroups = new TreeSet<>();
 
     if (gfsh != null && gfsh.isConnectedAndReady()) {
       final String[] memberGroupsArray =

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/DataCommandResult.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/DataCommandResult.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/DataCommandResult.java
index b682767..5ad88c3 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/DataCommandResult.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/DataCommandResult.java
@@ -44,9 +44,9 @@ import org.apache.geode.management.internal.cli.util.JsonUtil;
 
 
 /**
- * Domain object used for Data Commands Functions TODO : Implement DataSerializable
+ * Domain object used for Data Commands Functions
  */
-public class DataCommandResult implements /* Data */ Serializable {
+public class DataCommandResult implements Serializable {
   private static Logger logger = LogManager.getLogger();
 
   private static final long serialVersionUID = 1L;
@@ -260,7 +260,6 @@ public class DataCommandResult implements /* Data */ Serializable {
     DataCommandResult result = new DataCommandResult();
     result.command = CliStrings.QUERY;
     result.inputQuery = inputQuery;
-    // result.limit = limit;
     result.queryTraceString = queryTraceString;
     result.selectResult = value;
     result.error = error;
@@ -390,7 +389,6 @@ public class DataCommandResult implements /* Data */ Serializable {
     }
 
     if (errorString != null) {
-      // return ResultBuilder.createGemFireErrorResult(errorString);
       CompositeResultData data = ResultBuilder.createCompositeResultData();
       SectionResultData section = data.addSection();
       section.addData("Message", errorString);
@@ -415,8 +413,6 @@ public class DataCommandResult implements /* Data */ Serializable {
       toCommandResult_isPut(section, table);
     } else if (isRemove()) {
       toCommandResult_isRemove(section, table);
-    } else if (isSelect()) {
-      // its moved to its separate method
     }
     return ResultBuilder.buildResult(data);
   }
@@ -457,7 +453,6 @@ public class DataCommandResult implements /* Data */ Serializable {
         if (locations != null) {
           if (locations.size() == 1) {
             Object array[] = locations.get(0);
-            // String regionPath = (String)array[0];
             boolean found = (Boolean) array[1];
             if (found) {
               totalLocations++;
@@ -537,11 +532,10 @@ public class DataCommandResult implements /* Data */ Serializable {
    * This method returns result when flag interactive=false i.e. Command returns result in one go
    * and does not goes through steps waiting for user input. Method returns CompositeResultData
    * instead of Result as Command Step is required to add NEXT_STEP information to guide
-   * executionStragey to route it through final step.
+   * executionStrategy to route it through final step.
    */
   public CompositeResultData toSelectCommandResult() {
     if (errorString != null) {
-      // return ResultBuilder.createGemFireErrorResult(errorString);
       CompositeResultData data = ResultBuilder.createCompositeResultData();
       SectionResultData section = data.addSection();
       section.addData("Message", errorString);
@@ -613,7 +607,6 @@ public class DataCommandResult implements /* Data */ Serializable {
           try {
             tableRow.put(key, MISSING_VALUE);
           } catch (GfJsonException e) {
-            // TODO: Address this unlikely possibility.
             logger.warn("Ignored GfJsonException:", e);
           }
         }
@@ -816,7 +809,6 @@ public class DataCommandResult implements /* Data */ Serializable {
     if (result == null) {// self-transform result from single to aggregate when numMember==1
       if (this.locateEntryResult != null) {
         locateEntryLocations.add(locateEntryResult);
-        // TODO : Decide whether to show value or not this.getResult = locateEntryResult.getValue();
       }
       return;
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java
index 96f8815..82a7adf 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java
@@ -14,10 +14,8 @@
  */
 package org.apache.geode.management.internal.cli.functions;
 
-import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collections;
-import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -26,7 +24,6 @@ import java.util.concurrent.atomic.AtomicInteger;
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.logging.log4j.Logger;
-import org.apache.shiro.subject.Subject;
 import org.json.JSONArray;
 
 import org.apache.geode.cache.CacheFactory;
@@ -211,8 +208,6 @@ public class DataCommandFunction extends FunctionAdapter implements InternalEnti
 
     QueryService qs = cache.getQueryService();
 
-    // TODO : Find out if is this optimised use. Can you have something equivalent of parsed
-    // queries with names where name can be retrieved to avoid parsing every-time
     Query query = qs.newQuery(queryString);
     DefaultQuery tracedQuery = (DefaultQuery) query;
     WrappedIndexTrackingQueryObserver queryObserver = null;
@@ -385,7 +380,6 @@ public class DataCommandFunction extends FunctionAdapter implements InternalEnti
           if (logger.isDebugEnabled()) {
             logger.debug("Removed key {} successfully", key);
           }
-          // return DataCommandResult.createRemoveResult(key, value, null, null);
           Object array[] = getJSONForNonPrimitiveObject(value);
           DataCommandResult result =
               DataCommandResult.createRemoveResult(key, array[1], null, null, true);
@@ -450,8 +444,6 @@ public class DataCommandFunction extends FunctionAdapter implements InternalEnti
             "Error in converting JSON " + e.getMessage(), false);
       }
 
-      // TODO determine whether the following conditional logic (assigned to 'doGet') is safer or
-      // necessary
       boolean doGet = Boolean.TRUE.equals(loadOnCacheMiss);
 
       if (doGet || region.containsKey(keyObject)) {
@@ -465,7 +457,6 @@ public class DataCommandFunction extends FunctionAdapter implements InternalEnti
         if (logger.isDebugEnabled()) {
           logger.debug("Get for key {} value {}", key, value);
         }
-        // return DataCommandResult.createGetResult(key, value, null, null);
         Object array[] = getJSONForNonPrimitiveObject(value);
         if (value != null) {
           DataCommandResult result =
@@ -723,7 +714,6 @@ public class DataCommandFunction extends FunctionAdapter implements InternalEnti
           Object value = object.get(key);
           if (GfJsonObject.isJSONKind(value)) {
             GfJsonObject jsonVal = new GfJsonObject(value);
-            // System.out.println("Re-wrote inner object");
             try {
               if (jsonVal.has("type-class")) {
                 object.put(key, jsonVal.get("type-class"));

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
index 7562005..5e97976 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
@@ -350,10 +350,7 @@ public class CliStrings {
       "Fully qualified class name of a plug-in to be instantiated for receiving before-event notification of changes to the region and its entries. The plug-in may cancel the event. At most, one cache writer can be defined in each member for the region.";
   public static final String ALTER_REGION__ASYNCEVENTQUEUEID = "async-event-queue-id";
   public static final String ALTER_REGION__ASYNCEVENTQUEUEID__HELP =
-      "IDs of the Async Event Queues that will be used for write-behind operations."; // TODO -
-                                                                                      // Abhishek Is
-                                                                                      // this
-                                                                                      // correct?
+      "IDs of the Async Event Queues that will be used for write-behind operations.";
   public static final String ALTER_REGION__GATEWAYSENDERID = "gateway-sender-id";
   public static final String ALTER_REGION__GATEWAYSENDERID__HELP =
       "IDs of the Gateway Senders to which data will be routed.";
@@ -527,8 +524,8 @@ public class CliStrings {
       "This disk store is in use by other process. \"" + CliStrings.COMPACT_DISK_STORE
           + "\" can be used to compact disk store that is current in use.";
   public static final String COMPACT_OFFLINE_DISK_STORE__MSG__CANNOT_ACCESS_DISKSTORE_0_FROM_1_CHECK_GFSH_LOGS =
-      "Can not access disk store \"{0}\" from  \"{1}\". Check "
-          + org.apache.geode.management.internal.cli.shell.Gfsh.GFSH_APP_NAME + " logs for error.";
+      "Can not access disk store \"{0}\" from  \"{1}\". Check " + Gfsh.GFSH_APP_NAME
+          + " logs for error.";
   public static final String COMPACT_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2 =
       "While compacting disk store={0} {1}. Reason: {2}";
 
@@ -885,10 +882,7 @@ public class CliStrings {
       "Fully qualified class name of a plug-in to be instantiated for receiving before-event notification of changes to the region and its entries. The plug-in may cancel the event. At most, one cache writer can be defined in each member for the region.";
   public static final String CREATE_REGION__ASYNCEVENTQUEUEID = "async-event-queue-id";
   public static final String CREATE_REGION__ASYNCEVENTQUEUEID__HELP =
-      "IDs of the Async Event Queues that will be used for write-behind operations."; // TODO -
-                                                                                      // Abhishek Is
-                                                                                      // this
-                                                                                      // correct?
+      "IDs of the Async Event Queues that will be used for write-behind operations.";
   public static final String CREATE_REGION__GATEWAYSENDERID = "gateway-sender-id";
   public static final String CREATE_REGION__GATEWAYSENDERID__HELP =
       "IDs of the Gateway Senders to which data will be routed.";
@@ -985,14 +979,7 @@ public class CliStrings {
       "Could not access class \"{0}\" specified for \"{1}\".";
   public static final String CREATE_REGION__MSG__EXPIRATION_ACTION_0_IS_NOT_VALID =
       "Expiration action \"{0}\" is not valid.";
-  public static final String CREATE_REGION__MSG__ERROR_ON_MEMBER_0 = "Error on member: {0}. "; // leave
-                                                                                               // space
-                                                                                               // in
-                                                                                               // the
-                                                                                               // end
-                                                                                               // for
-                                                                                               // further
-                                                                                               // message
+  public static final String CREATE_REGION__MSG__ERROR_ON_MEMBER_0 = "Error on member: {0}. ";
   public static final String CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1 =
       "Could not retrieve region attributes for given path \"{0}\". Reason: {1}";
   public static final String CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS =
@@ -2333,12 +2320,7 @@ public class CliStrings {
   public static final String START_LOCATOR__PORT__HELP = "Port the Locator will listen on.";
   public static final String START_LOCATOR__PROPERTIES = "properties-file";
   public static final String START_LOCATOR__PROPERTIES__HELP =
-      "The gemfire.properties file for configuring the Locator's distributed system. The file's path can be absolute or relative to the gfsh working directory (--dir=)."; // TODO:GEODE-1466:
-                                                                                                                                                                           // update
-                                                                                                                                                                           // golden
-                                                                                                                                                                           // file
-                                                                                                                                                                           // to
-                                                                                                                                                                           // geode.properties
+      "The gemfire.properties file for configuring the Locator's distributed system. The file's path can be absolute or relative to the gfsh working directory (--dir=).";
   public static final String START_LOCATOR__SECURITY_PROPERTIES = "security-properties-file";
   public static final String START_LOCATOR__SECURITY_PROPERTIES__HELP =
       "The gfsecurity.properties file for configuring the Locator's security configuration in the distributed system. The file's path can be absolute or relative to gfsh directory (--dir=).";
@@ -2500,12 +2482,7 @@ public class CliStrings {
       "The total size of off-heap memory specified as off-heap-memory-size=<n>[g|m]. <n> is the size. [g|m] indicates whether the size should be interpreted as gigabytes or megabytes. A non-zero size causes that much memory to be allocated from the operating system and reserved for off-heap use.";
   public static final String START_SERVER__PROPERTIES = "properties-file";
   public static final String START_SERVER__PROPERTIES__HELP =
-      "The gemfire.properties file for configuring the Cache Server's distributed system. The file's path can be absolute or relative to the gfsh working directory."; // TODO:GEODE-1466:
-                                                                                                                                                                       // update
-                                                                                                                                                                       // golden
-                                                                                                                                                                       // file
-                                                                                                                                                                       // to
-                                                                                                                                                                       // geode.properties
+      "The gemfire.properties file for configuring the Cache Server's distributed system. The file's path can be absolute or relative to the gfsh working directory.";
   public static final String START_SERVER__REDIS_PORT = ConfigurationProperties.REDIS_PORT;
   public static final String START_SERVER__REDIS_PORT__HELP =
       "Sets the port that the Geode Redis service listens on for Redis clients.";
@@ -2515,8 +2492,7 @@ public class CliStrings {
       "Sets the IP address the Geode Redis service listens on for Redis clients. The default is to bind to the first non-loopback address for this machine.";
   public static final String START_SERVER__REDIS_PASSWORD = ConfigurationProperties.REDIS_PASSWORD;
   public static final String START_SERVER__REDIS_PASSWORD__HELP =
-      "Sets the authentication password for GeodeRedisServer"; // TODO:GEODE-1566: update golden
-                                                               // file to GeodeRedisServer
+      "Sets the authentication password for GeodeRedisServer";
   public static final String START_SERVER__SECURITY_PROPERTIES = "security-properties-file";
   public static final String START_SERVER__SECURITY_PROPERTIES__HELP =
       "The gfsecurity.properties file for configuring the Server's security configuration in the distributed system. The file's path can be absolute or relative to gfsh directory.";
@@ -2536,10 +2512,6 @@ public class CliStrings {
   public static final String START_SERVER__STATISTIC_ARCHIVE_FILE = STATISTIC_ARCHIVE_FILE;
   public static final String START_SERVER__STATISTIC_ARCHIVE_FILE__HELP =
       "The file that statistic samples are written to.  An empty string (default) disables statistic archival.";
-  // public static final String START_SERVER__START_LOCATOR = "start-locator";
-  // public static final String START_SERVER__START_LOCATOR__HELP =
-  // "To start embedded Locator with given endpoints in the format: host[port]. If no endpoints are
-  // given defaults (localhost[10334]) are assumed.";
   public static final String START_SERVER__USE_CLUSTER_CONFIGURATION = USE_CLUSTER_CONFIGURATION;
   public static final String START_SERVER__USE_CLUSTER_CONFIGURATION__HELP =
       "When set to true, the server requests the configuration from locator's cluster configuration service.";
@@ -2569,15 +2541,6 @@ public class CliStrings {
   public static final String START_SERVER__EVICTION_OFF_HEAP_PERCENTAGE__HELP =
       "Set the percentage of off-heap memory at or above which the eviction should begin on Regions configured for off-heap and HeapLRU eviction. Changing this value may cause eviction to begin immediately."
           + " Only one change to this attribute or critical off-heap percentage will be allowed at any given time and its effect will be fully realized before the next change is allowed.";
-  // cacheServer.setLoadPollInterval(loadPollInterval)
-  // cacheServer.setLoadProbe(loadProbe);
-  // cacheServer.setMaxConnections(maxCons);
-  // cacheServer.setMaximumMessageCount(maxMessageCount);
-  // cacheServer.setMaximumTimeBetweenPings(maximumTimeBetweenPings);
-  // cacheServer.setMaxThreads(maxThreads);
-  // cacheServer.setMessageTimeToLive(messageTimeToLive);
-  // cacheServer.setSocketBufferSize(socketBufferSize)
-  // cacheServer.setTcpNoDelay(noDelay)
   public static final String START_SERVER__HOSTNAME__FOR__CLIENTS = "hostname-for-clients";
   public static final String START_SERVER__HOSTNAME__FOR__CLIENTS__HELP =
       "Sets the ip address or host name that this cache server is to listen on for client connections."
@@ -3017,7 +2980,6 @@ public class CliStrings {
   /***
    * Cluster Configuration commands
    */
-  // TODO: Jared - clean up messages
   public static final String EXPORT_SHARED_CONFIG = "export cluster-configuration";
   public static final String EXPORT_SHARED_CONFIG__HELP =
       "Exports the cluster configuration artifacts as a zip file.";

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutionContext.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutionContext.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutionContext.java
index 42e3f08..fd4ebb7 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutionContext.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutionContext.java
@@ -27,10 +27,9 @@ import org.apache.geode.management.internal.cli.shell.Gfsh;
  */
 public class CommandExecutionContext {
   // ThreadLocal variables that can be uses by commands
-  private static final ThreadLocal<Map<String, String>> ENV =
-      new ThreadLocal<Map<String, String>>();
-  private static final ThreadLocal<Boolean> FROM_SHELL = new ThreadLocal<Boolean>();
-  private static final ThreadLocal<byte[][]> SHELL_BYTES_DATA = new ThreadLocal<byte[][]>();
+  private static final ThreadLocal<Map<String, String>> ENV = new ThreadLocal<>();
+  private static final ThreadLocal<Boolean> FROM_SHELL = new ThreadLocal<>();
+  private static final ThreadLocal<byte[][]> SHELL_BYTES_DATA = new ThreadLocal<>();
 
   private static final WrapperThreadLocal<CommandResponseWriter> WRITER_WRAPPER =
       new WrapperThreadLocal<CommandResponseWriter>() {
@@ -48,10 +47,6 @@ public class CommandExecutionContext {
     }
     return propertyValue != null ? propertyValue : defaultValue;
   }
-  // Enable when "use region" command is required. See #46110
-  // public static String getShellContextPath() {
-  // return getShellEnvProperty(CliConstants.ENV_APP_CONTEXT_PATH, null);
-  // }
 
   public static int getShellFetchSize() {
     int fetchSize = Gfsh.DEFAULT_APP_FETCH_SIZE;
@@ -75,8 +70,6 @@ public class CommandExecutionContext {
     }
   }
 
-  // TODO - Abhishek make this protected & move caller code of this method
-  // from MemberMBeanBridge to MemberCommandService
   public static void setShellEnv(Map<String, String> env) {
     ENV.set(env);
   }
@@ -93,8 +86,6 @@ public class CommandExecutionContext {
     return FROM_SHELL.get() != null && FROM_SHELL.get();
   }
 
-  // TODO - Abhishek make this protected & move caller code of this method
-  // from MemberMBeanBridge to MemberCommandService
   public static void setShellRequest() {
     FROM_SHELL.set(true);
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/AbstractResultData.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/AbstractResultData.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/AbstractResultData.java
index 0d1d91b..0bb96cf 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/AbstractResultData.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/AbstractResultData.java
@@ -14,24 +14,25 @@
  */
 package org.apache.geode.management.internal.cli.result;
 
-import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.CliUtil.DeflaterInflaterData;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.json.GfJsonArray;
-import org.apache.geode.management.internal.cli.json.GfJsonException;
-import org.apache.geode.management.internal.cli.json.GfJsonObject;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
-
 import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.sql.Time;
 import java.text.MessageFormat;
 import java.util.Base64;
 import java.util.zip.DataFormatException;
 
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.CliUtil.DeflaterInflaterData;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.json.GfJsonArray;
+import org.apache.geode.management.internal.cli.json.GfJsonException;
+import org.apache.geode.management.internal.cli.json.GfJsonObject;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
+
 /**
  * 
  * 
@@ -123,7 +124,7 @@ public abstract class AbstractResultData implements ResultData {
   }
 
   private static String addTimeStampBeforeLastDot(String src) {
-    String toAdd = String.valueOf(new java.sql.Time(System.currentTimeMillis()));
+    String toAdd = String.valueOf(new Time(System.currentTimeMillis()));
     toAdd = "-" + toAdd.replaceAll(":", "_");
 
     int lastIndexOf = src.lastIndexOf(".");
@@ -147,11 +148,10 @@ public abstract class AbstractResultData implements ResultData {
 
   public ResultData addAsFile(String fileName, byte[] data, int fileType, String message,
       boolean addTimeStampToName) {
-    byte[] bytes = data;
     if (addTimeStampToName) {
       fileName = addTimeStampBeforeLastDot(fileName);
     }
-    return addAsFile(fileName, bytes, fileType, message);
+    return addAsFile(fileName, data, fileType, message);
   }
 
   private ResultData addAsFile(String fileName, byte[] data, int fileType, String message) {
@@ -191,11 +191,8 @@ public abstract class AbstractResultData implements ResultData {
       throws GfJsonException, DataFormatException, IOException {
     boolean overwriteAllExisting = false;
     int length = byteDataArray.size();
-    String options = length > 1 ? "(y/N/a)" : "(y/N)"; // TODO - Abhishek Make this consistent -
-                                                       // with
-                                                       // AbstractCliAroundInterceptor.readYesNo()
-
-    BYTEARRAY_LOOP: for (int i = 0; i < length; i++) {
+    String options = length > 1 ? "(y/N/a)" : "(y/N)";
+    for (int i = 0; i < length; i++) {
       GfJsonObject object = byteDataArray.getJSONObject(i);
 
       int fileType = object.getInt(FILE_TYPE_FIELD);
@@ -205,8 +202,8 @@ public abstract class AbstractResultData implements ResultData {
       }
 
       // build file name
-      byte[] fileNameBytes = null;
-      String fileName = null;
+      byte[] fileNameBytes;
+      String fileName;
       GfJsonArray fileNameJsonBytes = object.getJSONArray(FILE_NAME_FIELD);
       if (fileNameJsonBytes != null) { // if in gfsh
         fileNameBytes = GfJsonArray.toByteArray(fileNameJsonBytes);
@@ -216,8 +213,8 @@ public abstract class AbstractResultData implements ResultData {
       }
 
       // build file message
-      byte[] fileMessageBytes = null;
-      String fileMessage = null;
+      byte[] fileMessageBytes;
+      String fileMessage;
       GfJsonArray fileMessageJsonBytes = object.getJSONArray(FILE_MESSAGE);
       if (fileMessageJsonBytes != null) { // if in gfsh
         fileMessageBytes = GfJsonArray.toByteArray(fileMessageJsonBytes);
@@ -247,7 +244,7 @@ public abstract class AbstractResultData implements ResultData {
       if (fileToDumpData.exists()) {
         String fileExistsMessage =
             CliStrings.format(CliStrings.ABSTRACTRESULTDATA__MSG__FILE_WITH_NAME_0_EXISTS_IN_1,
-                new Object[] {fileName, fileToDumpData.getParent(), options});
+                fileName, fileToDumpData.getParent(), options);
         if (gfsh != null && !gfsh.isQuietMode() && !overwriteAllExisting) {
           fileExistsMessage = fileExistsMessage + " Overwrite? " + options + " : ";
           String interaction = gfsh.interact(fileExistsMessage);
@@ -255,7 +252,7 @@ public abstract class AbstractResultData implements ResultData {
             overwriteAllExisting = true;
           } else if (!"y".equalsIgnoreCase(interaction.trim())) {
             // do not save file & continue
-            continue BYTEARRAY_LOOP;
+            continue;
           }
         } else {
           throw new IOException(fileExistsMessage);
@@ -289,18 +286,14 @@ public abstract class AbstractResultData implements ResultData {
         fos.flush();
         fos.close();
       }
-      // System.out.println("fileMessage :: "+fileMessage);
       if (fileMessage != null && !fileMessage.isEmpty()) {
         if (gfsh != null) {
-          Gfsh.println(
-              MessageFormat.format(fileMessage, new Object[] {fileToDumpData.getAbsolutePath()}));
+          Gfsh.println(MessageFormat.format(fileMessage, fileToDumpData.getAbsolutePath()));
         }
       }
-      // System.out.println(new String(uncompressed));
     }
   }
 
-  // TODO - Abhishek : prepare common utility for this & ANSI Styling
   static void handleCondition(String message) throws IOException {
     Gfsh gfsh = Gfsh.getCurrentInstance();
     // null check required in GfshVM too to avoid test issues

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CommandResult.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CommandResult.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CommandResult.java
index 00f1fd9..bbb59d0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CommandResult.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CommandResult.java
@@ -38,7 +38,7 @@ import org.apache.geode.management.internal.cli.result.TableBuilder.Table;
  * 
  * @since GemFire 7.0
  */
-// Should this have info about the command String??
+
 public class CommandResult implements Result {
 
   private GfJsonObject gfJsonObject;
@@ -57,7 +57,7 @@ public class CommandResult implements Result {
     this.resultData = resultData;
     this.gfJsonObject = this.resultData.getGfJsonObject();
     this.status = this.resultData.getStatus();
-    this.resultLines = new Vector<String>();
+    this.resultLines = new Vector<>();
   }
 
   @Override
@@ -78,7 +78,6 @@ public class CommandResult implements Result {
     index = 0;
   }
 
-  // TODO -Abhishek - extract this code out in a FormatBuilder or PresentationBuilder??
   private void buildData() {
     try {
       if (ResultData.TYPE_OBJECT.equals(resultData.getType())) {
@@ -95,7 +94,6 @@ public class CommandResult implements Result {
           RowGroup rowGroup = resultTable.newRowGroup();
 
           if (ResultData.TYPE_TABULAR.equals(resultData.getType())) {
-            // resultTable.setColumnSeparator(" | ");
             resultTable.setColumnSeparator("   ");
             resultTable.setTabularResult(true);
             buildTable(rowGroup, content);
@@ -111,7 +109,6 @@ public class CommandResult implements Result {
     } catch (GfJsonException e) {
       resultLines
           .add("Error occurred while processing Command Result. Internal Error - Invalid Result.");
-      // TODO - Abhishek. Add stack trace when 'debug' is enabled. Log to LogWrapper always
     } finally {
       isDataBuilt = true;
     }
@@ -152,7 +149,7 @@ public class CommandResult implements Result {
     }
   }
 
-  /* private */ void buildObjectResultOutput() {
+  void buildObjectResultOutput() {
     try {
       Table resultTable = TableBuilder.newTable();
       resultTable.setColumnSeparator(" : ");
@@ -169,12 +166,7 @@ public class CommandResult implements Result {
           GfJsonObject object = objectsArray.getJSONObject(i);
           buildObjectSection(resultTable, null, object, 0);
         }
-      } /*
-         * else { // GfJsonObject jsonObject =
-         * content.getJSONObject(ObjectResultData.ROOT_OBJECT_ACCESSOR); //
-         * buildObjectSection(resultTable, null, jsonObject, 0); }
-         */
-
+      }
       addFooterInTable(resultTable, getGfJsonObject());
 
       resultLines.addAll(resultTable.buildTableList());
@@ -182,7 +174,6 @@ public class CommandResult implements Result {
     } catch (GfJsonException e) {
       resultLines
           .add("Error occurred while processing Command Result. Internal Error - Invalid Result.");
-      // TODO - Abhishek. Add stack trace when 'debug' is enabled. Log to LogWrapper always
     } finally {
       isDataBuilt = true;
     }
@@ -191,7 +182,7 @@ public class CommandResult implements Result {
   private void buildObjectSection(Table table, RowGroup parentRowGroup, GfJsonObject object,
       int depth) throws GfJsonException {
     Iterator<String> keys = object.keys();
-    RowGroup rowGroup = null;
+    RowGroup rowGroup;
     if (parentRowGroup != null) {
       rowGroup = parentRowGroup;
     } else {
@@ -205,8 +196,8 @@ public class CommandResult implements Result {
 
     List<String> fieldsToSkipOnUI = null;
     if (object.has(CliJsonSerializable.FIELDS_TO_SKIP_ON_UI)) {
-      GfJsonArray jsonArray = object.getJSONArray(CliJsonSerializable.FIELDS_TO_SKIP_ON_UI);;
-      fieldsToSkipOnUI = new ArrayList<String>();
+      GfJsonArray jsonArray = object.getJSONArray(CliJsonSerializable.FIELDS_TO_SKIP_ON_UI);
+      fieldsToSkipOnUI = new ArrayList<>();
       for (int i = 0; i < jsonArray.size(); i++) {
         fieldsToSkipOnUI.add(String.valueOf(jsonArray.get(i)));
       }
@@ -222,8 +213,8 @@ public class CommandResult implements Result {
 
       try {
         nestedCollection = object.getJSONArray(key);
-      } catch (GfJsonException e) {
-        /* next check if it's a nested object */}
+      } catch (GfJsonException ignored) {
+      }
 
       Object field = null;
       if (nestedCollection == null) {
@@ -240,10 +231,8 @@ public class CommandResult implements Result {
 
       Row newRow = rowGroup.newRow();
       String prefix = "";
-      /* if (nestedCollection != null) */ {
-        for (int i = 0; i < depth; i++) {
-          prefix += " . ";
-        }
+      for (int i = 0; i < depth; i++) {
+        prefix += " . ";
       }
       String fieldNameToDisplay = fieldDisplayNames.getString(key);
 
@@ -252,22 +241,21 @@ public class CommandResult implements Result {
       }
 
       if (nestedCollection != null) {
-        Map<String, Integer> columnsMap = new HashMap<String, Integer>();
+        Map<String, Integer> columnsMap = new HashMap<>();
 
-        GfJsonArray rowsArray = nestedCollection;
         RowGroup newRowGroup = table.newRowGroup();
         newRowGroup.setColumnSeparator(" | ");
         newRowGroup.newBlankRow();
         newRowGroup.newRow().newLeftCol(fieldNameToDisplay);
         Row headerRow = newRowGroup.newRow();
 
-        int numOfRows = rowsArray.size();
+        int numOfRows = nestedCollection.size();
         List<String> tableFieldsToSkipOnUI = null;
         for (int j = 0; j < numOfRows; j++) {
-          GfJsonObject content = rowsArray.getJSONObject(j);
+          GfJsonObject content = nestedCollection.getJSONObject(j);
           if (content.has(CliJsonSerializable.FIELDS_TO_SKIP_ON_UI)) {
             GfJsonArray jsonArray = content.getJSONArray(CliJsonSerializable.FIELDS_TO_SKIP_ON_UI);
-            tableFieldsToSkipOnUI = new ArrayList<String>();
+            tableFieldsToSkipOnUI = new ArrayList<>();
             for (int i = 0; i < jsonArray.size(); i++) {
               tableFieldsToSkipOnUI.add(String.valueOf(jsonArray.get(i)));
             }
@@ -284,7 +272,7 @@ public class CommandResult implements Result {
               if (CliJsonSerializable.FIELDS_TO_SKIP.contains((String) columnName)
                   || (tableFieldsToSkipOnUI != null
                       && tableFieldsToSkipOnUI.contains(columnName))) {
-                // skip file data if any //TODO - make response format better
+                // skip file data if any
                 continue;
               }
 
@@ -299,7 +287,7 @@ public class CommandResult implements Result {
             Object columnName = columnNames.get(i);
             if (CliJsonSerializable.FIELDS_TO_SKIP.contains((String) columnName)
                 || (tableFieldsToSkipOnUI != null && tableFieldsToSkipOnUI.contains(columnName))) {
-              // skip file data if any //TODO - make response format better
+              // skip file data if any
               continue;
             }
             newRow.newLeftCol(String.valueOf(content.get((String) columnName)));
@@ -308,18 +296,7 @@ public class CommandResult implements Result {
       } else if (nestedObject != null) {
         buildObjectSection(table, rowGroup, nestedObject, depth + 1);
       } else {
-        // Row newRow = rowGroup.newRow();
-        // String prefix = "";
-        // for (int i = 0; i < depth; i++) {
-        // prefix += " . ";
-        // }
-        // newRow.newLeftCol(prefix+fieldDisplayNames.getString(key)).newLeftCol(field);
-        Object value = field;
-        /*
-         * if (isPrimitiveOrStringOrWrapperArray(value)) { value = Arrays.toString((String[])value);
-         * }
-         */
-        newRow.newLeftCol(value);
+        newRow.newLeftCol(field);
       }
       nestedCollection = null;
       nestedObject = null;
@@ -375,14 +352,14 @@ public class CommandResult implements Result {
       GfJsonArray jsonArr = (GfJsonArray) object;
       try {
         isPrimitive = isPrimitiveOrStringOrWrapper(jsonArr.get(0));
-      } catch (GfJsonException e) {
+      } catch (GfJsonException ignored) {
       }
     }
 
     return isPrimitive;
   }
 
-  /* private */ void buildComposite() {
+  void buildComposite() {
     try {
       GfJsonObject content = getContent();
       if (content != null) {
@@ -418,7 +395,7 @@ public class CommandResult implements Result {
   private void buildSection(Table table, RowGroup parentRowGroup, GfJsonObject section, int depth)
       throws GfJsonException {
     Iterator<String> keys = section.keys();
-    RowGroup rowGroup = null;
+    RowGroup rowGroup;
     if (parentRowGroup != null) {
       rowGroup = parentRowGroup;
     } else {
@@ -428,7 +405,6 @@ public class CommandResult implements Result {
     while (keys.hasNext()) {
       String key = keys.next();
       Object object = section.get(key);
-      // System.out.println(key +" : " + object);
       if (key.startsWith(CompositeResultData.TABLE_DATA_ACCESSOR)) {
         GfJsonObject tableObject = section.getJSONObject(key);
 
@@ -446,7 +422,6 @@ public class CommandResult implements Result {
         rowGroup.newRowSeparator(separatorString.charAt(0), true);
       } else if (key.equals(ResultData.RESULT_HEADER) || key.equals(ResultData.RESULT_FOOTER)) {
         // skip header & footer
-        continue;
       } else {
         Row newRow = rowGroup.newRow();
         String prefix = "";
@@ -468,22 +443,14 @@ public class CommandResult implements Result {
             newRow.newLeftCol(prefix + key).newLeftCol("");
           }
         }
-        // System.out.println(key+" : "+object);
       }
     }
     addFooterInRowGroup(rowGroup, section);
   }
 
-  // public static void main(String[] args) {
-  // String[] valuesSeparatedByLines = getValuesSeparatedByLines(CliConstants.LINE_SEPARATOR);
-  // System.out.println(valuesSeparatedByLines +" -- "+valuesSeparatedByLines.length);
-  // }
-
   private static String[] getValuesSeparatedByLines(Object object) {
-    String[] values = null;
     String valueString = String.valueOf(object);
-    values = valueString.split(GfshParser.LINE_SEPARATOR);
-    return values;
+    return valueString.split(GfshParser.LINE_SEPARATOR);
   }
 
   /**
@@ -502,10 +469,10 @@ public class CommandResult implements Result {
     for (int i = 0; i < numOfColumns; i++) {
       Object object = columnNames.get(i);
       if (AbstractResultData.BYTE_DATA_ACCESSOR.equals(object)) {
-        // skip file data if any //TODO - make response format better
+        // skip file data if any
         continue;
       }
-      headerRow.newCenterCol((String) object);
+      headerRow.newCenterCol(object);
     }
 
     // Build remaining rows by extracting data column-wise from JSON object
@@ -513,7 +480,7 @@ public class CommandResult implements Result {
     for (int i = 0; i < numOfColumns; i++) {
       Object object = columnNames.get(i);
       if (AbstractResultData.BYTE_DATA_ACCESSOR.equals(object)) {
-        // skip file data if any //TODO - make response format better
+        // skip file data if any
         continue;
       }
       GfJsonArray accumulatedData = content.getJSONArray((String) object);
@@ -574,13 +541,10 @@ public class CommandResult implements Result {
         GfJsonArray bytesArray = content.getJSONArray(CompositeResultData.BYTE_DATA_ACCESSOR);
         AbstractResultData.readFileDataAndDump(bytesArray, directory);
       } else {
-        throw new RuntimeException("No associated files to save .. "); // TODO Abhishek - add i18n
-                                                                       // string
+        throw new RuntimeException("No associated files to save .. ");
       }
       numTimesSaved = numTimesSaved + 1;
-    } catch (DataFormatException e) {
-      throw new RuntimeException(e);
-    } catch (GfJsonException e) {
+    } catch (DataFormatException | GfJsonException e) {
       throw new RuntimeException(e);
     }
   }
@@ -621,14 +585,10 @@ public class CommandResult implements Result {
     return gfJsonObject.getString(ResultData.RESULT_HEADER);
   }
 
-  public GfJsonObject getContent() throws GfJsonException {
+  public GfJsonObject getContent() {
     return gfJsonObject.getJSONObject(ResultData.RESULT_CONTENT);
   }
 
-  // public String getContentStr() {
-  // return gfJsonObject.getString(ResultData.RESULT_CONTENT);
-  // }
-
   public String getFooter() {
     return getFooter(gfJsonObject);
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CompositeResultData.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CompositeResultData.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CompositeResultData.java
index 7d0d23b..9d93d3a 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CompositeResultData.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/CompositeResultData.java
@@ -30,11 +30,11 @@ public class CompositeResultData extends AbstractResultData {
 
   private int subsectionCount;
 
-  /* package */ CompositeResultData() {
+  CompositeResultData() {
     super();
   }
 
-  /* package */ CompositeResultData(GfJsonObject gfJsonObject) {
+  CompositeResultData(GfJsonObject gfJsonObject) {
     super(gfJsonObject);
   }
 
@@ -131,13 +131,13 @@ public class CompositeResultData extends AbstractResultData {
    * 
    * @since GemFire 7.0
    */
-  public static class SectionResultData /* extends AbstractResultData */ {
+  public static class SectionResultData {
     protected GfJsonObject sectionGfJsonObject;
 
     private int subsectionCount = 0;
     private int tablesCount = 0;
 
-    /* package */ SectionResultData() {
+    SectionResultData() {
       sectionGfJsonObject = new GfJsonObject();
     }
 
@@ -295,7 +295,7 @@ public class CompositeResultData extends AbstractResultData {
     }
 
     public String[] retrieveStringArray(String name) {
-      String[] stringArray = null;
+      String[] stringArray;
       Object retrievedObject = sectionGfJsonObject.get(name);
 
       if (retrievedObject instanceof GfJsonArray) {
@@ -317,11 +317,6 @@ public class CompositeResultData extends AbstractResultData {
     public static String generateTableKey(String keyToRetrieve) {
       return TABLE_DATA_ACCESSOR + "-" + keyToRetrieve;
     }
-
-    // @Override
-    // public String getType() {
-    // return TYPE_SECTION;
-    // }
   }
 
   public static void main(String[] args) {
@@ -362,10 +357,8 @@ public class CompositeResultData extends AbstractResultData {
         .accumulate("NumOfBuckets", 100);
 
     try {
-      System.out.println(crd.getGfJsonObject().toIndentedString(/* 2 */0));
+      System.out.println(crd.getGfJsonObject().toIndentedString(0));
 
-    } catch (GfJsonException e) {
-      e.printStackTrace();
     } catch (Exception e) {
       e.printStackTrace();
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultBuilder.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultBuilder.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultBuilder.java
index 94dbca0..2518793 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultBuilder.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultBuilder.java
@@ -14,19 +14,18 @@
  */
 package org.apache.geode.management.internal.cli.result;
 
+import java.util.Collection;
+import java.util.List;
+
 import org.apache.geode.management.cli.Result;
 import org.apache.geode.management.internal.cli.json.GfJsonException;
 import org.apache.geode.management.internal.cli.json.GfJsonObject;
 
-import java.util.Collection;
-import java.util.List;
-
 /**
  * Provides methods for creating {@link Result} objects to return from Gfsh command functions
  */
 public class ResultBuilder {
   public static final int CODE_SHELLCLIENT_ABORT_OP = 110;
-  // public static final int OKCODE = 200;
 
   // error on gfsh
   public static final int ERRORCODE_DEFAULT = 400;
@@ -169,10 +168,6 @@ public class ResultBuilder {
     return new ObjectResultData<>();
   }
 
-  // public static CatalogedResultData createCatalogedResultData() {
-  // return new CatalogedResultData();
-  // }
-
   /**
    * Creates a {@link InfoResultData} object to start building result that is required to be shown
    * as an information without any specific format.
@@ -233,10 +228,7 @@ public class ResultBuilder {
       AbstractResultData resultData;
       if (ResultData.TYPE_TABULAR.equals(contentType)) {
         resultData = new TabularResultData(data);
-      } /*
-         * else if (ResultData.TYPE_CATALOGED.equals(contentType)) { resultData = new
-         * CatalogedResultData(new GfJsonObject(String.valueOf(content))); }
-         */ else if (ResultData.TYPE_INFO.equals(contentType)) {
+      } else if (ResultData.TYPE_INFO.equals(contentType)) {
         resultData = new InfoResultData(data);
       } else if (ResultData.TYPE_ERROR.equals(contentType)) {
         resultData = new ErrorResultData(data);
@@ -266,7 +258,6 @@ public class ResultBuilder {
       while (result.hasNextLine()) {
         builder.append(result.nextLine());
       }
-      // TODO - what to do with incoming files??
     }
 
     return builder.toString();

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultData.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultData.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultData.java
index 37a1d60..cacbef8 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultData.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/ResultData.java
@@ -28,12 +28,10 @@ public interface ResultData {
   String RESULT_FOOTER = "footer";
 
 
-  // String TYPE_CATALOGED = "catalog";
   String TYPE_COMPOSITE = "composite";
   String TYPE_ERROR = "error";
   String TYPE_INFO = "info";
   String TYPE_OBJECT = "object";
-  // String TYPE_SECTION = "composite-section";
   String TYPE_TABULAR = "table";
 
   String getHeader();
@@ -44,7 +42,7 @@ public interface ResultData {
 
   String getType();
 
-  public Status getStatus();
+  Status getStatus();
 
-  public void setStatus(final Status status);
+  void setStatus(final Status status);
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/TableBuilder.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/TableBuilder.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/TableBuilder.java
index ff23512..55081ed 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/TableBuilder.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/result/TableBuilder.java
@@ -53,12 +53,14 @@ package org.apache.geode.management.internal.cli.result;
  * 
  * @since GemFire 7.0
  */
-import org.apache.commons.lang.StringUtils;
-import org.apache.geode.management.internal.cli.GfshParser;
 
 import java.util.ArrayList;
 import java.util.List;
 
+import org.apache.commons.lang.StringUtils;
+
+import org.apache.geode.management.internal.cli.GfshParser;
+
 public class TableBuilder {
 
   public static Table newTable() {
@@ -351,7 +353,6 @@ public class TableBuilder {
           int maxNumCols = this.rowGroup.getNumCols();
 
           for (int i = 0; i < maxNumCols; i++) {
-            // int maxColLength = this.rowGroup.getMaxColLength(i);
             int maxColLength = this.rowGroup.getColSize(i);
             for (int j = 0; j < maxColLength; j++) {
               stringBuffer.append(this.rowSeparator);
@@ -382,7 +383,7 @@ public class TableBuilder {
     }
   }
 
-  private static enum Align {
+  private enum Align {
     LEFT, RIGHT, CENTER
   }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/Gfsh.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/Gfsh.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/Gfsh.java
index 503c252..2d55f42 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/Gfsh.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/Gfsh.java
@@ -56,6 +56,7 @@ import org.apache.geode.management.internal.cli.CliUtil;
 import org.apache.geode.management.internal.cli.CommandManager;
 import org.apache.geode.management.internal.cli.GfshParser;
 import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.converters.RegionPathConverter;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.result.CompositeResultData;
@@ -80,7 +81,7 @@ import org.apache.geode.management.internal.cli.util.CommentSkipHelper;
  * </ul>
  * <p />
  * Additionally, this class is used to maintain GemFire SHell (gfsh) specific information like:
- * environment TODO
+ * environment
  *
  *
  * @since GemFire 7.0
@@ -121,7 +122,6 @@ public class Gfsh extends JLineShell {
   public static final String ENV_SYS_OS_LINE_SEPARATOR = "SYS_OS_LINE_SEPARATOR";
   public static final String ENV_SYS_GEODE_HOME_DIR = "SYS_GEODE_HOME_DIR";
 
-  // TODO merge find a better place for these
   // SSL Configuration properties. keystore/truststore type is not include
   public static final String SSL_KEYSTORE = "javax.net.ssl.keyStore";
   public static final String SSL_KEYSTORE_PASSWORD = "javax.net.ssl.keyStorePassword";
@@ -133,19 +133,18 @@ public class Gfsh extends JLineShell {
   private static final int DEFAULT_HEIGHT = 100;
   private static final Object INSTANCE_LOCK = new Object();
 
-  // private static final String ANIMATION_SLOT = "A"; //see 46072
   protected static PrintStream gfshout = System.out;
   protected static PrintStream gfsherr = System.err;
-  protected static ThreadLocal<Gfsh> gfshThreadLocal = new ThreadLocal<Gfsh>();
+  protected static ThreadLocal<Gfsh> gfshThreadLocal = new ThreadLocal<>();
   private static Gfsh instance;
   // This flag is used to restrict column trimming to table only types
-  private static ThreadLocal<Boolean> resultTypeTL = new ThreadLocal<Boolean>();
+  private static ThreadLocal<Boolean> resultTypeTL = new ThreadLocal<>();
   private static String OS = System.getProperty("os.name").toLowerCase();
-  private final Map<String, String> env = new TreeMap<String, String>();
-  private final List<String> readonlyAppEnv = new ArrayList<String>();
+  private final Map<String, String> env = new TreeMap<>();
+  private final List<String> readonlyAppEnv = new ArrayList<>();
   // Map to keep reference to actual user specified Command String
   // Should always have one value at the max
-  private final Map<String, String> expandedPropCommandsMap = new HashMap<String, String>();
+  private final Map<String, String> expandedPropCommandsMap = new HashMap<>();
   private final ExecutionStrategy executionStrategy;
   private final GfshParser parser;
   private final LogWrapper gfshFileLogger;
@@ -158,11 +157,11 @@ public class Gfsh extends JLineShell {
   private Thread runner;
   private boolean debugON;
   private Terminal terminal;
-  private boolean supressScriptCmdOutput;
+  private boolean suppressScriptCmdOutput;
   private boolean isScriptRunning;
   private AbstractSignalNotificationHandler signalHandler;
 
-  protected Gfsh() throws ClassNotFoundException, IOException {
+  protected Gfsh() {
     this(null);
   }
 
@@ -173,7 +172,7 @@ public class Gfsh extends JLineShell {
    * @throws IOException
    * @throws ClassNotFoundException
    */
-  protected Gfsh(String[] args) throws ClassNotFoundException, IOException {
+  protected Gfsh(String[] args) {
     this(true, args, new GfshConfig());
   }
 
@@ -186,8 +185,7 @@ public class Gfsh extends JLineShell {
    * @throws IOException
    * @throws ClassNotFoundException
    */
-  protected Gfsh(boolean launchShell, String[] args, GfshConfig gfshConfig)
-      throws ClassNotFoundException, IOException {
+  protected Gfsh(boolean launchShell, String[] args, GfshConfig gfshConfig) {
     // 1. Disable suppressing of duplicate messages
     JLineLogHandler.setSuppressDuplicateMessages(false);
 
@@ -195,11 +193,7 @@ public class Gfsh extends JLineShell {
     this.gfshConfig = gfshConfig;
     this.gfshFileLogger = LogWrapper.getInstance();
     this.gfshFileLogger.configure(this.gfshConfig);
-    this.ansiHandler = ANSIHandler.getInstance(this.gfshConfig.isANSISupported()); // TODO -
-    // Abhishek :
-    // should take it
-    // from
-    // ConsoleReader.terminal??
+    this.ansiHandler = ANSIHandler.getInstance(this.gfshConfig.isANSISupported());
 
     /* 3. log system properties & gfsh environment */
     this.gfshFileLogger.info(Banner.getString(args));
@@ -255,8 +249,7 @@ public class Gfsh extends JLineShell {
     }
   }
 
-  public static Gfsh getInstance(boolean launchShell, String[] args, GfshConfig gfshConfig)
-      throws ClassNotFoundException, IOException {
+  public static Gfsh getInstance(boolean launchShell, String[] args, GfshConfig gfshConfig) {
     if (instance == null) {
       synchronized (INSTANCE_LOCK) {
         if (instance == null) {
@@ -295,7 +288,7 @@ public class Gfsh extends JLineShell {
   // See 46369
   private static String readLine(ConsoleReader reader, String prompt) throws IOException {
     String earlierLine = reader.getCursorBuffer().toString();
-    String readLine = null;
+    String readLine;
     try {
       readLine = reader.readLine(prompt);
     } catch (IndexOutOfBoundsException e) {
@@ -327,7 +320,6 @@ public class Gfsh extends JLineShell {
       while (loggerNames.hasMoreElements()) {
         String loggerName = loggerNames.nextElement();
         if (loggerName.startsWith("java.") || loggerName.startsWith("javax.")) {
-          // System.out.println(loggerName);
           Logger javaLogger = logManager.getLogger(loggerName);
           /*
            * From Java Docs: It is also important to note that the Logger associated with the String
@@ -423,7 +415,7 @@ public class Gfsh extends JLineShell {
       } else {
         final int spaceCharIndex = string.lastIndexOf(" ", index);
 
-        // If no spaces were found then there's no logical wayto split the string
+        // If no spaces were found then there's no logical way to split the string
         if (spaceCharIndex == -1) {
           stringBuf.append(string.substring(startOfCurrentLine, index)).append(LINE_SEPARATOR);
 
@@ -453,7 +445,7 @@ public class Gfsh extends JLineShell {
     env.put(ENV_SYS_OS_LINE_SEPARATOR, System.getProperty("line.separator"));
     env.put(ENV_SYS_GEODE_HOME_DIR, System.getenv("GEODE_HOME"));
 
-    env.put(ENV_APP_NAME, org.apache.geode.management.internal.cli.shell.Gfsh.GFSH_APP_NAME);
+    env.put(ENV_APP_NAME, Gfsh.GFSH_APP_NAME);
     readonlyAppEnv.add(ENV_APP_NAME);
     env.put(ENV_APP_LOGGING_ENABLED,
         String.valueOf(!Level.OFF.equals(this.gfshConfig.getLogLevel())));
@@ -506,7 +498,6 @@ public class Gfsh extends JLineShell {
    * Stops this GemFire Shell.
    */
   public void stop() {
-    // flashMessage("\b"); // see 46072
     closeShell();
     LogWrapper.close();
     if (operationInvoker != null && operationInvoker.isConnected()) {
@@ -544,7 +535,6 @@ public class Gfsh extends JLineShell {
    * See findResources in {@link AbstractShell}
    */
   protected Collection<URL> findResources(String resourceName) {
-    // return Collections.singleton(ClassPathLoader.getLatest().getResource(resourceName));
     return null;
   }
 
@@ -604,8 +594,6 @@ public class Gfsh extends JLineShell {
       }
       success = super.executeScriptLine(withPropsExpanded);
     } catch (Exception e) {
-      // TODO: should there be a way to differentiate error in shell & error on
-      // server. May be by exception type.
       setLastExecutionStatus(-1);
     } finally { // Add all commands to in-memory GfshHistory
       gfshHistory.setAutoFlush(true);
@@ -700,7 +688,7 @@ public class Gfsh extends JLineShell {
             while (commandResult.hasNextLine()) {
               write(commandResult.nextLine(), isError);
             }
-          } else if (!supressScriptCmdOutput) {
+          } else if (!suppressScriptCmdOutput) {
             // Command is part of script. Show output only when quite=false
             while (commandResult.hasNextLine()) {
               write(commandResult.nextLine(), isError);
@@ -742,7 +730,7 @@ public class Gfsh extends JLineShell {
   }
 
   private boolean isUnix() {
-    return !(OS.indexOf("win") >= 0);
+    return !(OS.contains("win"));
   }
 
   private void write(String message, boolean isError) {
@@ -885,7 +873,7 @@ public class Gfsh extends JLineShell {
   }
 
   public Result executeScript(File scriptFile, boolean quiet, boolean continueOnError) {
-    Result result = null;
+    Result result;
     String initialIsQuiet = getEnvProperty(ENV_APP_QUIET_EXECUTION);
     try {
       this.isScriptRunning = true;
@@ -900,12 +888,11 @@ public class Gfsh extends JLineShell {
       ScriptExecutionDetails scriptInfo = new ScriptExecutionDetails(scriptFile.getPath());
       if (scriptFile.exists()) {
         setEnvProperty(ENV_APP_QUIET_EXECUTION, String.valueOf(quiet));
-        this.supressScriptCmdOutput = quiet;
+        this.suppressScriptCmdOutput = quiet;
         BufferedReader reader = new BufferedReader(new FileReader(scriptFile));
         String lineRead = "";
         StringBuilder linesBuffer = new StringBuilder();
-        String linesBufferString = ""; // used to check whether the string in a buffer contains a
-        // ";".
+        String linesBufferString = "";
         int commandSrNum = 0;
         CommentSkipHelper commentSkipper = new CommentSkipHelper();
 
@@ -925,7 +912,6 @@ public class Gfsh extends JLineShell {
           linesBufferString = linesBuffer.toString();
           // NOTE: Similar code is in promptLoop()
           if (!linesBufferString.endsWith(GfshParser.CONTINUATION_CHARACTER)) { // see 45893
-            // String command = null;
 
             List<String> commandList = MultiCommandHelper.getMultipleCommands(linesBufferString);
             for (String cmdLet : commandList) {
@@ -995,18 +981,11 @@ public class Gfsh extends JLineShell {
   }
 
   public Map<String, String> getEnv() {
-    Map<String, String> map = new TreeMap<String, String>();
+    Map<String, String> map = new TreeMap<>();
     map.putAll(env);
     return map;
   }
 
-  @Override
-  public void setPromptPath(String currentContext) {
-    super.setPromptPath(currentContext);
-    // Enable when "use region" command is required. See #46110
-    // env.put(CliConstants.ENV_APP_CONTEXT_PATH, currentContext);
-  }
-
   public boolean isQuietMode() {
     return Boolean.parseBoolean(env.get(ENV_APP_QUIET_EXECUTION));
   }
@@ -1100,7 +1079,7 @@ public class Gfsh extends JLineShell {
   @Override
   protected String getPromptText() {
     String defaultPrompt = gfshConfig.getDefaultPrompt();
-    String contextPath = /* getEnvProperty(CliConstants.ENV_APP_CONTEXT_PATH) */ "";
+    String contextPath = "";
     String clusterString = "";
 
     if (getOperationInvoker() != null && isConnectedAndReady()) {
@@ -1108,14 +1087,6 @@ public class Gfsh extends JLineShell {
       if (clusterId != OperationInvoker.CLUSTER_ID_WHEN_NOT_CONNECTED) {
         clusterString = "Cluster-" + clusterId + " ";
       }
-      // //As "use region" is not in scope for 7.0, see 46110.
-      // if (contextPath == null) {
-      // contextPath = "." + CliConstants.DEFAULT_APP_CONTEXT_PATH;
-      // } else {
-      // contextPath = "." + contextPath;
-      // }
-      // } else {
-      // contextPath = "." + CliConstants.DEFAULT_APP_CONTEXT_PATH;
     }
 
     defaultPrompt = MessageFormat.format(defaultPrompt, clusterString, contextPath);
@@ -1130,8 +1101,7 @@ public class Gfsh extends JLineShell {
     if (gfshFileLogger.severeEnabled()) {
       gfshFileLogger.severe(message);
     }
-    setPromptPath(
-        org.apache.geode.management.internal.cli.converters.RegionPathConverter.DEFAULT_APP_CONTEXT_PATH);
+    setPromptPath(RegionPathConverter.DEFAULT_APP_CONTEXT_PATH);
   }
 
   public boolean getDebug() {
@@ -1153,7 +1123,7 @@ public class Gfsh extends JLineShell {
   private String expandProperties(final String input) {
     String output = input;
     Scanner s = new Scanner(output);
-    String foundInLine = null;
+    String foundInLine;
     while ((foundInLine = s.findInLine("(\\$[\\{]\\w+[\\}])")) != null) {
       String envProperty = getEnvProperty(extractKey(foundInLine));
       envProperty = envProperty != null ? envProperty : "";
@@ -1170,7 +1140,7 @@ class ScriptExecutionDetails {
 
   ScriptExecutionDetails(String filePath) {
     this.filePath = filePath;
-    this.commandAndStatusList = new ArrayList<CommandAndStatus>();
+    this.commandAndStatusList = new ArrayList<>();
   }
 
   void addCommandAndStatus(String command, String status) {
@@ -1190,7 +1160,7 @@ class ScriptExecutionDetails {
       section.addData("Command-" + String.valueOf(commandSrNo), commandAndStatus.command);
       section.addData("Status", commandAndStatus.status);
       if (commandAndStatus.status.equals("FAILED")) {
-        compositeResultData.setStatus(org.apache.geode.management.cli.Result.Status.ERROR);
+        compositeResultData.setStatus(Result.Status.ERROR);
       }
       if (i != this.commandAndStatusList.size()) {
         section.setFooter(Gfsh.LINE_SEPARATOR);

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/GfshExecutionStrategy.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/GfshExecutionStrategy.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/GfshExecutionStrategy.java
index 6794b3b..735143f 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/GfshExecutionStrategy.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/GfshExecutionStrategy.java
@@ -131,14 +131,6 @@ public class GfshExecutionStrategy implements ExecutionStrategy {
     return cliMetadata != null ? cliMetadata.interceptor() : CliMetaData.ANNOTATION_NULL_VALUE;
   }
 
-  // Not used currently
-  // private static String getCommandName(ParseResult result) {
-  // Method method = result.getMethod();
-  // CliCommand cliCommand = method.getAnnotation(CliCommand.class);
-  //
-  // return cliCommand != null ? cliCommand.value() [0] : null;
-  // }
-
   /**
    * Indicates commands are able to be presented. This generally means all important system startup
    * activities have completed. Copied from {@link ExecutionStrategy#isReadyForCommands()}.
@@ -157,7 +149,6 @@ public class GfshExecutionStrategy implements ExecutionStrategy {
    */
   @Override
   public void terminate() {
-    // TODO: Is additional cleanup required?
     shell = null;
   }
   //////////////// ExecutionStrategy interface Methods End /////////////////////
@@ -247,8 +238,6 @@ public class GfshExecutionStrategy implements ExecutionStrategy {
 
       String debugInfo = commandResponse.getDebugInfo();
       if (StringUtils.isNotBlank(debugInfo)) {
-        // TODO - Abhishek When debug is ON, log response in gfsh logs
-        // TODO - Abhishek handle \n better. Is it coming from GemFire formatter
         debugInfo = debugInfo.replaceAll("\n\n\n", "\n");
         debugInfo = debugInfo.replaceAll("\n\n", "\n");
         debugInfo =

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/JmxOperationInvoker.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/JmxOperationInvoker.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/JmxOperationInvoker.java
index 5066496..d2407b3 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/JmxOperationInvoker.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/JmxOperationInvoker.java
@@ -18,7 +18,6 @@ import static org.apache.geode.distributed.ConfigurationProperties.CLUSTER_SSL_P
 import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_SSL_PREFIX;
 
 import java.io.IOException;
-import java.net.MalformedURLException;
 import java.text.MessageFormat;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -88,21 +87,21 @@ public class JmxOperationInvoker implements OperationInvoker {
 
   private ObjectName managerMemberObjectName;
 
-  /* package */ final AtomicBoolean isConnected = new AtomicBoolean(false);
-  /* package */ final AtomicBoolean isSelfDisconnect = new AtomicBoolean(false);
+  final AtomicBoolean isConnected = new AtomicBoolean(false);
+  final AtomicBoolean isSelfDisconnect = new AtomicBoolean(false);
 
   private int clusterId = CLUSTER_ID_WHEN_NOT_CONNECTED;
 
   public JmxOperationInvoker(final String host, final int port, Properties gfProperties)
       throws Exception {
-    final Set<String> propsToClear = new TreeSet<String>();
+    final Set<String> propsToClear = new TreeSet<>();
     try {
       this.managerHost = host;
       this.managerPort = port;
       this.endpoints = host + "[" + port + "]"; // Use the same syntax as the "connect" command.
 
       // Modify check period from default (60 sec) to 1 sec
-      final Map<String, Object> env = new HashMap<String, Object>();
+      final Map<String, Object> env = new HashMap<>();
 
       env.put(JMXConnectionListener.CHECK_PERIOD_PROP, JMXConnectionListener.CHECK_PERIOD);
       env.put(JMXConnector.CREDENTIALS, gfProperties);
@@ -169,12 +168,6 @@ public class JmxOperationInvoker implements OperationInvoker {
 
       this.isConnected.set(true);
       this.clusterId = distributedSystemMXBeanProxy.getDistributedSystemId();
-    } catch (NullPointerException e) {
-      throw e;
-    } catch (MalformedURLException e) {
-      throw e;
-    } catch (IOException e) {
-      throw e;
     } finally {
       for (String propToClear : propsToClear) {
         System.clearProperty(propToClear);
@@ -215,7 +208,7 @@ public class JmxOperationInvoker implements OperationInvoker {
       throw new JMXInvocationException(attributeName + " not found for " + resourceName, e);
     } catch (InstanceNotFoundException e) {
       throw new JMXInvocationException(resourceName + " is not registered in the MBean server.", e);
-    } catch (MalformedObjectNameException e) {
+    } catch (MalformedObjectNameException | IOException e) {
       throw new JMXInvocationException(resourceName + " is not a valid resource name.", e);
     } catch (MBeanException e) {
       throw new JMXInvocationException(
@@ -225,8 +218,6 @@ public class JmxOperationInvoker implements OperationInvoker {
           e);
     } catch (NullPointerException e) {
       throw new JMXInvocationException("Given resourceName is null.", e);
-    } catch (IOException e) {
-      throw new JMXInvocationException(resourceName + " is not a valid resource name.", e);
     }
   }
 
@@ -283,8 +274,6 @@ public class JmxOperationInvoker implements OperationInvoker {
 
   @Override
   public Object processCommand(final CommandRequest commandRequest) throws JMXInvocationException {
-    // Gfsh.getCurrentInstance().printAsSevere(String.format("Command (%1$s)%n",
-    // commandRequest.getInput()));
     if (commandRequest.hasFileData()) {
       return memberMXBeanProxy.processCommand(commandRequest.getInput(),
           commandRequest.getEnvironment(), ArrayUtils.toByteArray(commandRequest.getFileData()));
@@ -365,7 +354,7 @@ public class JmxOperationInvoker implements OperationInvoker {
     return this.clusterId;
   }
 
-  /* package */ void resetClusterId() {
+  void resetClusterId() {
     clusterId = CLUSTER_ID_WHEN_NOT_CONNECTED;
   }
 
@@ -378,12 +367,10 @@ public class JmxOperationInvoker implements OperationInvoker {
    *
    * @return for an IPv6 address returns compatible host address otherwise returns the same string
    */
-  // TODO - Abhishek: move to utility class
-  // Taken from GFMon
   public static String checkAndConvertToCompatibleIPv6Syntax(String hostAddress) {
     // if host string contains ":", considering it as an IPv6 Address
     // Conforming to RFC2732 - http://www.ietf.org/rfc/rfc2732.txt
-    if (hostAddress.indexOf(":") != -1) {
+    if (hostAddress.contains(":")) {
       LogWrapper logger = LogWrapper.getInstance();
       if (logger.fineEnabled()) {
         logger.fine("IPv6 host address detected, using IPv6 syntax for host in JMX connection URL");

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/unsafe/GfshSignalHandler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/unsafe/GfshSignalHandler.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/unsafe/GfshSignalHandler.java
index 5d9e31b..641c4d9 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/unsafe/GfshSignalHandler.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/shell/unsafe/GfshSignalHandler.java
@@ -18,12 +18,12 @@ import java.util.Collections;
 import java.util.Hashtable;
 import java.util.Map;
 
+import sun.misc.SignalHandler;
+
 import org.apache.geode.internal.process.signal.AbstractSignalNotificationHandler;
 import org.apache.geode.internal.process.signal.Signal;
 import org.apache.geode.internal.process.signal.SignalEvent;
 
-import sun.misc.SignalHandler;
-
 /**
  * This class externalizes signal handling in order to make the GemFire build process a bit cleaner
  * - for example we have to have exceptions for sun.misc classes when building javadocs.
@@ -42,13 +42,6 @@ public class GfshSignalHandler extends AbstractSignalNotificationHandler impleme
 
   public GfshSignalHandler() {
     for (final Signal signal : Signal.values()) {
-      // NOTE SignalHandler registration for SIGQUIT led to an IllegalArgumentException without the
-      // following
-      // "if" statement...
-      // Exception in thread "main" java.lang.IllegalArgumentException: Signal already used by VM:
-      // SIGQUIT
-      // if (!Signal.SIGQUIT.equals(signal)) {
-      // TODO uncomment above if statement if all Signals need to be handled by this SignalHandler
       if (Signal.SIGINT.equals(signal)) {
         originalSignalHandlers.put(signal,
             sun.misc.Signal.handle(new sun.misc.Signal(signal.getName()), this));
@@ -58,8 +51,6 @@ public class GfshSignalHandler extends AbstractSignalNotificationHandler impleme
 
   @Override
   public void handle(final sun.misc.Signal sig) {
-    // System.err.printf("Thread (%1$s) is processing Signal '%2$s' (%3$d)...%n",
-    // Thread.currentThread().getName(), sig.getName(), sig.getNumber());
     notifyListeners(new SignalEvent(sig, Signal.valueOfName(sig.getName())));
     handleDefault(sig);
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/ReadWriteFile.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/ReadWriteFile.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/ReadWriteFile.java
index 8adac15..c9d05b0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/ReadWriteFile.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/ReadWriteFile.java
@@ -14,15 +14,9 @@
  */
 package org.apache.geode.management.internal.cli.util;
 
-import org.apache.geode.cache.execute.FunctionException;
-import org.apache.geode.internal.logging.LogWriterImpl;
-import org.apache.geode.internal.logging.log4j.LogLevel;
-import org.apache.geode.management.internal.cli.GfshParser;
-
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.File;
-import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.FileWriter;
 import java.io.IOException;
@@ -32,6 +26,11 @@ import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 
+import org.apache.geode.cache.execute.FunctionException;
+import org.apache.geode.internal.logging.LogWriterImpl;
+import org.apache.geode.internal.logging.log4j.LogLevel;
+import org.apache.geode.management.internal.cli.GfshParser;
+
 /**
  * 
  * 
@@ -55,50 +54,38 @@ public class ReadWriteFile {
       String onlyLogLevel, String startTime, String endTime) {
     try {
       long lineCount = 0;
-      BufferedReader input = null;
-      BufferedWriter output = null;
+      BufferedReader input;
+      BufferedWriter output;
       File logFileNameFile = new File(logFileName);
-      if (logFileNameFile.canRead() == false) {
+      if (!logFileNameFile.canRead()) {
         return ("Cannot read logFileName=" + logFileName);
       }
       input = new BufferedReader(new FileReader(logFileName));
-      String line = null;
+      String line;
       File logToBeWrittenToFile = new File(logToBeWritten);
       output = new BufferedWriter(new FileWriter(logToBeWrittenToFile));
       if (!logToBeWrittenToFile.exists()) {
-        if (input != null) {
-          input.close();
-        }
-        if (output != null) {
-          output.flush();
-          output.close();
-        }
-        return (logToBeWritten + " doesn not exist");
+        input.close();
+        output.flush();
+        output.close();
+        return (logToBeWritten + " does not exist");
       }
       if (!logToBeWrittenToFile.isFile()) {
-        if (input != null) {
-          input.close();
-        }
-        if (output != null) {
-          output.flush();
-          output.close();
-        }
+        input.close();
+        output.flush();
+        output.close();
         return (logToBeWritten + " is not a file");
       }
       if (!logToBeWrittenToFile.canWrite()) {
-        if (input != null) {
-          input.close();
-        }
-        if (output != null) {
-          output.flush();
-          output.close();
-        }
+        input.close();
+        output.flush();
+        output.close();
         return ("can not write file " + logToBeWritten);
       }
 
       // build possible log levels based on user input
       // get all the levels below the one mentioned by user
-      List<String> logLevels = new ArrayList<String>();
+      List<String> logLevels = new ArrayList<>();
       if (onlyLogLevel.toLowerCase().equals("false")) {
         int[] intLogLevels = LogWriterImpl.allLevels;
         for (int level : intLogLevels) {
@@ -112,18 +99,13 @@ public class ReadWriteFile {
       boolean timeRangeCheck = false;
       boolean foundLogLevelTag = false;
       boolean validateLogLevel = true;
-      while (input.ready() == true && (line = input.readLine()) != null) {
-        if (new File(logFileName).canRead() == false) {
+      while (input.ready() && (line = input.readLine()) != null) {
+        if (!new File(logFileName).canRead()) {
           return ("Cannot read logFileName=" + logFileName);
         }
-        // boolean validateLogLevel = true;
         lineCount++;
-        if (line.startsWith("[")) {
-          foundLogLevelTag = true;
-        } else {
-          foundLogLevelTag = false;
-        }
-        if (line.contains("[info ") && timeRangeCheck == false) {
+        foundLogLevelTag = line.startsWith("[");
+        if (line.contains("[info ") && !timeRangeCheck) {
           String stTime = "";
           int spaceCounter = 0;
           for (int i = line.indexOf("[info ") + 6; i < line.length(); i++) {
@@ -152,12 +134,12 @@ public class ReadWriteFile {
             // set this so that no need to check time range for each line
             timeRangeCheck = true;
           } else {
-            // dont take this log file as this does not fit in time range
+            // don't take this log file as this does not fit in time range
             break;
           }
         }
 
-        if (foundLogLevelTag == true) {
+        if (foundLogLevelTag) {
           validateLogLevel = checkLogLevel(line, logLevel, logLevels, foundLogLevelTag);
         }
 
@@ -178,11 +160,9 @@ public class ReadWriteFile {
         output.flush();
         output.close();
       }
-      return ("Sucessfully written file " + logFileName);
+      return ("Successfully written file " + logFileName);
     } catch (FunctionException ex) {
       return ("readWriteFile FunctionException " + ex.getMessage());
-    } catch (FileNotFoundException ex) {
-      return ("readWriteFile FileNotFoundException " + ex.getMessage());
     } catch (IOException ex) {
       return ("readWriteFile FileNotFoundException " + ex.getMessage());
     } catch (Exception ex) {
@@ -194,7 +174,7 @@ public class ReadWriteFile {
       boolean foundLogLevelTag) {
     if (line == null) {
       return false;
-    } else if (line != null && foundLogLevelTag == true) {
+    } else if (foundLogLevelTag) {
       if (logLevel.toLowerCase().equals("all")) {
         return true;
       } else if (line.equals(GfshParser.LINE_SEPARATOR)) {
@@ -207,7 +187,7 @@ public class ReadWriteFile {
             if (indexFrom > -1 && indexTo > -1 && indexTo > indexFrom) {
               boolean flag =
                   line.substring(indexFrom + 1, indexTo).toLowerCase().contains(permittedLogLevel);
-              if (flag == true) {
+              if (flag) {
                 return flag;
               }
             }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/CacheElement.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/CacheElement.java b/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/CacheElement.java
index 7450757..97f48a5 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/CacheElement.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/CacheElement.java
@@ -14,9 +14,9 @@
  */
 package org.apache.geode.management.internal.configuration.domain;
 
+import static javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI;
 import static org.apache.geode.management.internal.configuration.utils.XmlConstants.W3C_XML_SCHEMA_INSTANCE_ATTRIBUTE_SCHEMA_LOCATION;
 import static org.apache.geode.management.internal.configuration.utils.XmlUtils.getAttribute;
-import static javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI;
 
 import java.io.IOException;
 import java.net.URL;
@@ -111,8 +111,7 @@ public class CacheElement {
         XmlUtils.buildSchemaLocationMap(getAttribute(doc.getFirstChild(),
             W3C_XML_SCHEMA_INSTANCE_ATTRIBUTE_SCHEMA_LOCATION, W3C_XML_SCHEMA_INSTANCE_NS_URI));
 
-    final LinkedHashMap<String, CacheElement> elementMap =
-        new LinkedHashMap<String, CacheElement>();
+    final LinkedHashMap<String, CacheElement> elementMap = new LinkedHashMap<>();
 
     buildElementMapCacheType(elementMap,
         resolveSchema(schemaLocationMap, CacheXml.GEODE_NAMESPACE));
@@ -210,10 +209,6 @@ public class CacheElement {
           final String name = getAttribute(child, "name");
           elementMap.put(name, new CacheElement(name, rank++, isMultiple(child)));
           break;
-        // TODO group support as XSD matures
-        // case "xsd:group":
-        // buildElementMapGroup(elementMap, doc, child, rank, xPathContext);
-        // break;
         case "xsd:choice":
         case "xsd:sequence":
           rank = buildElementMapXPath(elementMap, schema, child, rank,
@@ -223,7 +218,6 @@ public class CacheElement {
           // ignore extensions
           break;
         default:
-          // TODO jbarrett - localize
           throw new UnsupportedOperationException(
               "Unsupported child type '" + child.getNodeName() + "'");
       }
@@ -236,16 +230,12 @@ public class CacheElement {
    * Tests if element allows multiple.
    * 
    * @param element to test for multiple.
-   * @return true if mulitple allowed, otherwise false.
+   * @return true if multiple allowed, otherwise false.
    * @since GemFire 8.1
    */
   private static boolean isMultiple(final Element element) {
-    final String maxOccurs = getAttribute(element, "maxOccurs");
-    if (null != maxOccurs && !maxOccurs.equals("1")) {
-      // is "unbounded" or greater than 1 if valid schema.
-      return true;
-    }
-    return false;
+    String maxOccurs = getAttribute(element, "maxOccurs");
+    return null != maxOccurs && !maxOccurs.equals("1");
   }
 
 }


[22/47] geode git commit: GEODE-3436: Restore refactoring of StatusCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of StatusCommands

* See initial commit GEODE-3270 (359e3fff6482ecfb375939d387f4dad3a636246b)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 851932ec10ea3146308710f274aa9b7a17d4dbab
Parents: 18f65de
Author: YehEmily <em...@gmail.com>
Authored: Mon Aug 28 10:08:26 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:28 2017 -0700

----------------------------------------------------------------------
 .../StatusClusterConfigServiceCommand.java      | 82 ++++++++++++++++++++
 .../internal/cli/commands/StatusCommands.java   | 82 --------------------
 .../internal/security/TestCommand.java          |  2 +-
 3 files changed, 83 insertions(+), 83 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/851932ec/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
new file mode 100644
index 0000000..6a0fc1e
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.FetchSharedConfigurationStatusFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.configuration.domain.SharedConfigurationStatus;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+
+public class StatusClusterConfigServiceCommand implements GfshCommand {
+  private static final FetchSharedConfigurationStatusFunction fetchSharedConfigStatusFunction =
+      new FetchSharedConfigurationStatusFunction();
+
+  @SuppressWarnings("unchecked")
+  @CliCommand(value = CliStrings.STATUS_SHARED_CONFIG, help = CliStrings.STATUS_SHARED_CONFIG_HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_LOCATOR)
+  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+  public Result statusSharedConfiguration() {
+    final InternalCache cache = GemFireCacheImpl.getInstance();
+    final Set<DistributedMember> locators = new HashSet<DistributedMember>(
+        cache.getDistributionManager().getAllHostedLocatorsWithSharedConfiguration().keySet());
+    if (locators.isEmpty()) {
+      return ResultBuilder.createInfoResult(CliStrings.NO_LOCATORS_WITH_SHARED_CONFIG);
+    } else {
+      return ResultBuilder.buildResult(getSharedConfigurationStatus(locators));
+    }
+  }
+
+  private TabularResultData getSharedConfigurationStatus(Set<DistributedMember> locators) {
+    boolean isSharedConfigRunning = false;
+    ResultCollector<?, ?> rc =
+        CliUtil.executeFunction(fetchSharedConfigStatusFunction, null, locators);
+    List<CliFunctionResult> results = (List<CliFunctionResult>) rc.getResult();
+    TabularResultData table = ResultBuilder.createTabularResultData();
+    table.setHeader("Status of shared configuration on locators");
+
+    for (CliFunctionResult result : results) {
+      table.accumulate(CliStrings.STATUS_SHARED_CONFIG_NAME_HEADER, result.getMemberIdOrName());
+      String status = (String) result.getSerializables()[0];
+      table.accumulate(CliStrings.STATUS_SHARED_CONFIG_STATUS, status);
+      if (SharedConfigurationStatus.RUNNING.name().equals(status)) {
+        isSharedConfigRunning = true;
+      }
+    }
+
+    if (!isSharedConfigRunning) {
+      table.setStatus(Status.ERROR);
+    }
+    return table;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/851932ec/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusCommands.java
deleted file mode 100644
index 0b0b78b..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusCommands.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.FetchSharedConfigurationStatusFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.configuration.domain.SharedConfigurationStatus;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.CommandMarker;
-import org.springframework.shell.core.annotation.CliCommand;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-public class StatusCommands implements GfshCommand {
-  static final FetchSharedConfigurationStatusFunction fetchSharedConfigStatusFunction =
-      new FetchSharedConfigurationStatusFunction();
-
-  @SuppressWarnings("unchecked")
-  @CliCommand(value = CliStrings.STATUS_SHARED_CONFIG, help = CliStrings.STATUS_SHARED_CONFIG_HELP)
-  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_LOCATOR)
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result statusSharedConfiguration() {
-    final InternalCache cache = GemFireCacheImpl.getInstance();
-    final Set<DistributedMember> locators = new HashSet<DistributedMember>(
-        cache.getDistributionManager().getAllHostedLocatorsWithSharedConfiguration().keySet());
-    if (locators.isEmpty()) {
-      return ResultBuilder.createInfoResult(CliStrings.NO_LOCATORS_WITH_SHARED_CONFIG);
-    } else {
-      return ResultBuilder.buildResult(getSharedConfigurationStatus(locators));
-    }
-  }
-
-  private TabularResultData getSharedConfigurationStatus(Set<DistributedMember> locators) {
-    boolean isSharedConfigRunning = false;
-    ResultCollector<?, ?> rc =
-        CliUtil.executeFunction(fetchSharedConfigStatusFunction, null, locators);
-    List<CliFunctionResult> results = (List<CliFunctionResult>) rc.getResult();
-    TabularResultData table = ResultBuilder.createTabularResultData();
-    table.setHeader("Status of shared configuration on locators");
-
-    for (CliFunctionResult result : results) {
-      table.accumulate(CliStrings.STATUS_SHARED_CONFIG_NAME_HEADER, result.getMemberIdOrName());
-      String status = (String) result.getSerializables()[0];
-      table.accumulate(CliStrings.STATUS_SHARED_CONFIG_STATUS, status);
-      if (SharedConfigurationStatus.RUNNING.name().equals(status)) {
-        isSharedConfigRunning = true;
-      }
-    }
-
-    if (!isSharedConfigRunning) {
-      table.setStatus(Status.ERROR);
-    }
-    return table;
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/851932ec/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index 4efa93f..5c91ca6 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -258,7 +258,7 @@ public class TestCommand {
     createTestCommand("describe region --name=value", clusterRead);
     createTestCommand("list regions", clusterRead);
 
-    // StatusCommands
+    // StatusClusterConfigServiceCommand
     createTestCommand("status cluster-config-service", clusterRead);
 
     // Shell Commands


[23/47] geode git commit: GEODE-3436: Restore refactoring of DeployCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of DeployCommands

* See initial commit GEODE-3257 (9d967446a44a78b612f605b6a8f8eedcfc625b3a)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 18f65de782bc1eec2e72a9209d3adc7e7e5c19cc
Parents: ca80871
Author: YehEmily <em...@gmail.com>
Authored: Wed Aug 2 17:28:10 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:28 2017 -0700

----------------------------------------------------------------------
 .../internal/cli/commands/DeployCommand.java    | 190 +++++++++++
 .../internal/cli/commands/DeployCommands.java   | 336 -------------------
 .../cli/commands/ListDeployedCommand.java       | 102 ++++++
 .../internal/cli/commands/UndeployCommand.java  | 114 +++++++
 .../controllers/DeployCommandsController.java   |   5 -
 .../cli/commands/DeployWithGroupsDUnitTest.java |   2 +-
 6 files changed, 407 insertions(+), 342 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/18f65de7/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
new file mode 100644
index 0000000..4f46539
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
@@ -0,0 +1,190 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.commons.io.FileUtils.ONE_MB;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.text.DecimalFormat;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.security.SecurityService;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.DeployFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
+import org.apache.geode.management.internal.cli.result.FileResult;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.NotAuthorizedException;
+import org.apache.geode.security.ResourcePermission;
+
+public class DeployCommand implements GfshCommand {
+  private final DeployFunction deployFunction = new DeployFunction();
+
+  /**
+   * Deploy one or more JAR files to members of a group or all members.
+   *
+   * @param groups Group(s) to deploy the JAR to or null for all members
+   * @param jars JAR file to deploy
+   * @param dir Directory of JAR files to deploy
+   * @return The result of the attempt to deploy
+   */
+  @CliCommand(value = {CliStrings.DEPLOY}, help = CliStrings.DEPLOY__HELP)
+  @CliMetaData(
+      interceptor = "org.apache.geode.management.internal.cli.commands.DeployCommand$Interceptor",
+      relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
+  public Result deploy(
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, help = CliStrings.DEPLOY__GROUP__HELP,
+          optionContext = ConverterHint.MEMBERGROUP) String[] groups,
+      @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
+          help = CliStrings.DEPLOY__JAR__HELP) String[] jars,
+      @CliOption(key = {CliStrings.DEPLOY__DIR}, help = CliStrings.DEPLOY__DIR__HELP) String dir) {
+    try {
+
+      // since deploy function can potentially do a lot of damage to security, this action should
+      // require these following privileges
+      SecurityService securityService = getSecurityService();
+
+      TabularResultData tabularData = ResultBuilder.createTabularResultData();
+
+      byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell();
+      String[] jarNames = CliUtil.bytesToNames(shellBytesData);
+      byte[][] jarBytes = CliUtil.bytesToData(shellBytesData);
+
+      Set<DistributedMember> targetMembers;
+
+      targetMembers = CliUtil.findMembers(groups, null);
+
+      if (targetMembers.size() > 0) {
+        // this deploys the jars to all the matching servers
+        ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(this.deployFunction,
+            new Object[] {jarNames, jarBytes}, targetMembers);
+
+        List<CliFunctionResult> results =
+            CliFunctionResult.cleanResults((List<?>) resultCollector.getResult());
+
+        for (CliFunctionResult result : results) {
+          if (result.getThrowable() != null) {
+            tabularData.accumulate("Member", result.getMemberIdOrName());
+            tabularData.accumulate("Deployed JAR", "");
+            tabularData.accumulate("Deployed JAR Location",
+                "ERROR: " + result.getThrowable().getClass().getName() + ": "
+                    + result.getThrowable().getMessage());
+            tabularData.setStatus(Result.Status.ERROR);
+          } else {
+            String[] strings = (String[]) result.getSerializables();
+            for (int i = 0; i < strings.length; i += 2) {
+              tabularData.accumulate("Member", result.getMemberIdOrName());
+              tabularData.accumulate("Deployed JAR", strings[i]);
+              tabularData.accumulate("Deployed JAR Location", strings[i + 1]);
+            }
+          }
+        }
+      }
+
+      Result result = ResultBuilder.buildResult(tabularData);
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().addJarsToThisLocator(jarNames, jarBytes, groups));
+      return result;
+    } catch (NotAuthorizedException e) {
+      // for NotAuthorizedException, will catch this later in the code
+      throw e;
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable t) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult(String
+          .format("Exception while attempting to deploy: (%1$s)", toString(t, isDebugging())));
+    }
+  }
+
+  /**
+   * Interceptor used by gfsh to intercept execution of deploy command at "shell".
+   */
+  public static class Interceptor extends AbstractCliAroundInterceptor {
+    private final DecimalFormat numFormatter = new DecimalFormat("###,##0.00");
+
+    @Override
+    public Result preExecution(GfshParseResult parseResult) {
+      // 2nd argument is the jar
+      String[] jars = (String[]) parseResult.getArguments()[1];
+      // 3rd argument is the dir
+      String dir = (String) parseResult.getArguments()[2];
+
+      if (ArrayUtils.isEmpty(jars) && StringUtils.isBlank(dir)) {
+        return ResultBuilder.createUserErrorResult(
+            "Parameter \"jar\" or \"dir\" is required. Use \"help <command name>\" for assistance.");
+      }
+
+      if (ArrayUtils.isNotEmpty(jars) && StringUtils.isNotBlank(dir)) {
+        return ResultBuilder
+            .createUserErrorResult("Parameters \"jar\" and \"dir\" can not both be specified.");
+      }
+
+      FileResult fileResult;
+      String[] filesToUpload = jars;
+      if (filesToUpload == null) {
+        filesToUpload = new String[] {dir};
+      }
+      try {
+
+        fileResult = new FileResult(filesToUpload);
+      } catch (FileNotFoundException fnfex) {
+        return ResultBuilder
+            .createGemFireErrorResult("'" + Arrays.toString(filesToUpload) + "' not found.");
+      } catch (IOException ioex) {
+        return ResultBuilder.createGemFireErrorResult("I/O error when reading jar/dir: "
+            + ioex.getClass().getName() + ": " + ioex.getMessage());
+      }
+
+      // Only do this additional check if a dir was provided
+      if (dir != null) {
+        String message =
+            "\nDeploying files: " + fileResult.getFormattedFileList() + "\nTotal file size is: "
+                + this.numFormatter.format((double) fileResult.computeFileSizeTotal() / ONE_MB)
+                + "MB\n\nContinue? ";
+
+        if (readYesNo(message, Response.YES) == Response.NO) {
+          return ResultBuilder.createShellClientAbortOperationResult(
+              "Aborted deploy of " + Arrays.toString(filesToUpload) + ".");
+        }
+      }
+      return fileResult;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/18f65de7/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
deleted file mode 100644
index e502154..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import static org.apache.commons.io.FileUtils.ONE_MB;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.text.DecimalFormat;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.security.SecurityService;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.DeployFunction;
-import org.apache.geode.management.internal.cli.functions.ListDeployedFunction;
-import org.apache.geode.management.internal.cli.functions.UndeployFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
-import org.apache.geode.management.internal.cli.result.FileResult;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.NotAuthorizedException;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.geode.security.ResourcePermission.Target;
-
-
-
-/**
- * Commands for deploying, un-deploying and listing files deployed using the command line shell.
- *
- * @see GfshCommand
- * @since GemFire 7.0
- */
-public class DeployCommands implements GfshCommand {
-
-  private final DeployFunction deployFunction = new DeployFunction();
-  private final UndeployFunction undeployFunction = new UndeployFunction();
-  private final ListDeployedFunction listDeployedFunction = new ListDeployedFunction();
-
-  /**
-   * Deploy one or more JAR files to members of a group or all members.
-   * 
-   * @param groups Group(s) to deploy the JAR to or null for all members
-   * @param jars JAR file to deploy
-   * @param dir Directory of JAR files to deploy
-   * @return The result of the attempt to deploy
-   */
-  @CliCommand(value = {CliStrings.DEPLOY}, help = CliStrings.DEPLOY__HELP)
-  @CliMetaData(
-      interceptor = "org.apache.geode.management.internal.cli.commands.DeployCommands$Interceptor",
-      relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
-  public Result deploy(
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, help = CliStrings.DEPLOY__GROUP__HELP,
-          optionContext = ConverterHint.MEMBERGROUP) String[] groups,
-      @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
-          help = CliStrings.DEPLOY__JAR__HELP) String[] jars,
-      @CliOption(key = {CliStrings.DEPLOY__DIR}, help = CliStrings.DEPLOY__DIR__HELP) String dir) {
-    try {
-
-      // since deploy function can potentially do a lot of damage to security, this action should
-      // require these following privileges
-      SecurityService securityService = getSecurityService();
-
-      TabularResultData tabularData = ResultBuilder.createTabularResultData();
-
-      byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell();
-      String[] jarNames = CliUtil.bytesToNames(shellBytesData);
-      byte[][] jarBytes = CliUtil.bytesToData(shellBytesData);
-
-      Set<DistributedMember> targetMembers;
-
-      targetMembers = CliUtil.findMembers(groups, null);
-
-      if (targetMembers.size() > 0) {
-        // this deploys the jars to all the matching servers
-        ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(this.deployFunction,
-            new Object[] {jarNames, jarBytes}, targetMembers);
-
-        List<CliFunctionResult> results =
-            CliFunctionResult.cleanResults((List<?>) resultCollector.getResult());
-
-        for (CliFunctionResult result : results) {
-          if (result.getThrowable() != null) {
-            tabularData.accumulate("Member", result.getMemberIdOrName());
-            tabularData.accumulate("Deployed JAR", "");
-            tabularData.accumulate("Deployed JAR Location",
-                "ERROR: " + result.getThrowable().getClass().getName() + ": "
-                    + result.getThrowable().getMessage());
-            tabularData.setStatus(Status.ERROR);
-          } else {
-            String[] strings = (String[]) result.getSerializables();
-            for (int i = 0; i < strings.length; i += 2) {
-              tabularData.accumulate("Member", result.getMemberIdOrName());
-              tabularData.accumulate("Deployed JAR", strings[i]);
-              tabularData.accumulate("Deployed JAR Location", strings[i + 1]);
-            }
-          }
-        }
-      }
-
-      Result result = ResultBuilder.buildResult(tabularData);
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().addJarsToThisLocator(jarNames, jarBytes, groups));
-      return result;
-    } catch (NotAuthorizedException e) {
-      // for NotAuthorizedException, will catch this later in the code
-      throw e;
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable t) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult(String
-          .format("Exception while attempting to deploy: (%1$s)", toString(t, isDebugging())));
-    }
-  }
-
-  /**
-   * Undeploy one or more JAR files from members of a group or all members.
-   * 
-   * @param groups Group(s) to undeploy the JAR from or null for all members
-   * @param jars JAR(s) to undeploy (separated by comma)
-   * @return The result of the attempt to undeploy
-   */
-  @CliCommand(value = {CliStrings.UNDEPLOY}, help = CliStrings.UNDEPLOY__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
-  public Result undeploy(
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.UNDEPLOY__GROUP__HELP,
-          optionContext = ConverterHint.MEMBERGROUP) String[] groups,
-      @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
-          help = CliStrings.UNDEPLOY__JAR__HELP) String[] jars) {
-
-    try {
-      TabularResultData tabularData = ResultBuilder.createTabularResultData();
-      boolean accumulatedData = false;
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(this.undeployFunction, new Object[] {jars}, targetMembers);
-      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
-      for (CliFunctionResult result : results) {
-
-        if (result.getThrowable() != null) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Un-Deployed JAR", "");
-          tabularData.accumulate("Un-Deployed JAR Location",
-              "ERROR: " + result.getThrowable().getClass().getName() + ": "
-                  + result.getThrowable().getMessage());
-          accumulatedData = true;
-          tabularData.setStatus(Status.ERROR);
-        } else {
-          String[] strings = (String[]) result.getSerializables();
-          for (int i = 0; i < strings.length; i += 2) {
-            tabularData.accumulate("Member", result.getMemberIdOrName());
-            tabularData.accumulate("Un-Deployed JAR", strings[i]);
-            tabularData.accumulate("Un-Deployed From JAR Location", strings[i + 1]);
-            accumulatedData = true;
-          }
-        }
-      }
-
-      if (!accumulatedData) {
-        return ResultBuilder.createInfoResult(CliStrings.UNDEPLOY__NO_JARS_FOUND_MESSAGE);
-      }
-
-      Result result = ResultBuilder.buildResult(tabularData);
-      if (tabularData.getStatus().equals(Status.OK)) {
-        persistClusterConfiguration(result,
-            () -> getSharedConfiguration().removeJars(jars, groups));
-      }
-      return result;
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult("Exception while attempting to un-deploy: "
-          + th.getClass().getName() + ": " + th.getMessage());
-    }
-  }
-
-  /**
-   * List all currently deployed JARs for members of a group or for all members.
-   * 
-   * @param group Group for which to list JARs or null for all members
-   * @return List of deployed JAR files
-   */
-  @CliCommand(value = {CliStrings.LIST_DEPLOYED}, help = CliStrings.LIST_DEPLOYED__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result listDeployed(@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-      help = CliStrings.LIST_DEPLOYED__GROUP__HELP) String[] group) {
-
-    try {
-      TabularResultData tabularData = ResultBuilder.createTabularResultData();
-      boolean accumulatedData = false;
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, null);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(this.listDeployedFunction, null, targetMembers);
-      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
-      for (CliFunctionResult result : results) {
-        if (result.getThrowable() != null) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("JAR", "");
-          tabularData.accumulate("JAR Location",
-              "ERROR: " + result.getThrowable().getClass().getName() + ": "
-                  + result.getThrowable().getMessage());
-          accumulatedData = true;
-          tabularData.setStatus(Status.ERROR);
-        } else {
-          String[] strings = (String[]) result.getSerializables();
-          for (int i = 0; i < strings.length; i += 2) {
-            tabularData.accumulate("Member", result.getMemberIdOrName());
-            tabularData.accumulate("JAR", strings[i]);
-            tabularData.accumulate("JAR Location", strings[i + 1]);
-            accumulatedData = true;
-          }
-        }
-      }
-
-      if (!accumulatedData) {
-        return ResultBuilder.createInfoResult(CliStrings.LIST_DEPLOYED__NO_JARS_FOUND_MESSAGE);
-      }
-      return ResultBuilder.buildResult(tabularData);
-
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult("Exception while attempting to list deployed: "
-          + th.getClass().getName() + ": " + th.getMessage());
-    }
-  }
-
-  /**
-   * Interceptor used by gfsh to intercept execution of deploy command at "shell".
-   */
-  public static class Interceptor extends AbstractCliAroundInterceptor {
-    private final DecimalFormat numFormatter = new DecimalFormat("###,##0.00");
-
-    @Override
-    public Result preExecution(GfshParseResult parseResult) {
-      // 2nd argument is the jar
-      String[] jars = (String[]) parseResult.getArguments()[1];
-      // 3rd argument is the dir
-      String dir = (String) parseResult.getArguments()[2];
-
-      if (ArrayUtils.isEmpty(jars) && StringUtils.isBlank(dir)) {
-        return ResultBuilder.createUserErrorResult(
-            "Parameter \"jar\" or \"dir\" is required. Use \"help <command name>\" for assistance.");
-      }
-
-      if (ArrayUtils.isNotEmpty(jars) && StringUtils.isNotBlank(dir)) {
-        return ResultBuilder
-            .createUserErrorResult("Parameters \"jar\" and \"dir\" can not both be specified.");
-      }
-
-      FileResult fileResult;
-      String[] filesToUpload = jars;
-      if (filesToUpload == null) {
-        filesToUpload = new String[] {dir};
-      }
-      try {
-
-        fileResult = new FileResult(filesToUpload);
-      } catch (FileNotFoundException fnfex) {
-        return ResultBuilder.createGemFireErrorResult("'" + filesToUpload + "' not found.");
-      } catch (IOException ioex) {
-        return ResultBuilder.createGemFireErrorResult("I/O error when reading jar/dir: "
-            + ioex.getClass().getName() + ": " + ioex.getMessage());
-      }
-
-      // Only do this additional check if a dir was provided
-      if (dir != null) {
-        String message =
-            "\nDeploying files: " + fileResult.getFormattedFileList() + "\nTotal file size is: "
-                + this.numFormatter.format((double) fileResult.computeFileSizeTotal() / ONE_MB)
-                + "MB\n\nContinue? ";
-
-        if (readYesNo(message, Response.YES) == Response.NO) {
-          return ResultBuilder
-              .createShellClientAbortOperationResult("Aborted deploy of " + filesToUpload + ".");
-        }
-      }
-
-      return fileResult;
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/18f65de7/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDeployedCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDeployedCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDeployedCommand.java
new file mode 100644
index 0000000..4c2bc53
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDeployedCommand.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.ListDeployedFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ListDeployedCommand implements GfshCommand {
+  private final ListDeployedFunction listDeployedFunction = new ListDeployedFunction();
+
+  /**
+   * List all currently deployed JARs for members of a group or for all members.
+   *
+   * @param group Group for which to list JARs or null for all members
+   * @return List of deployed JAR files
+   */
+  @CliCommand(value = {CliStrings.LIST_DEPLOYED}, help = CliStrings.LIST_DEPLOYED__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result listDeployed(@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+      help = CliStrings.LIST_DEPLOYED__GROUP__HELP) String[] group) {
+
+    try {
+      TabularResultData tabularData = ResultBuilder.createTabularResultData();
+      boolean accumulatedData = false;
+
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, null);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(this.listDeployedFunction, null, targetMembers);
+      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+      for (CliFunctionResult result : results) {
+        if (result.getThrowable() != null) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("JAR", "");
+          tabularData.accumulate("JAR Location",
+              "ERROR: " + result.getThrowable().getClass().getName() + ": "
+                  + result.getThrowable().getMessage());
+          accumulatedData = true;
+          tabularData.setStatus(Result.Status.ERROR);
+        } else {
+          String[] strings = (String[]) result.getSerializables();
+          for (int i = 0; i < strings.length; i += 2) {
+            tabularData.accumulate("Member", result.getMemberIdOrName());
+            tabularData.accumulate("JAR", strings[i]);
+            tabularData.accumulate("JAR Location", strings[i + 1]);
+            accumulatedData = true;
+          }
+        }
+      }
+
+      if (!accumulatedData) {
+        return ResultBuilder.createInfoResult(CliStrings.LIST_DEPLOYED__NO_JARS_FOUND_MESSAGE);
+      }
+      return ResultBuilder.buildResult(tabularData);
+
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult("Exception while attempting to list deployed: "
+          + th.getClass().getName() + ": " + th.getMessage());
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/18f65de7/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UndeployCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UndeployCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UndeployCommand.java
new file mode 100644
index 0000000..5df7ac7
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UndeployCommand.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.UndeployFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class UndeployCommand implements GfshCommand {
+  private final UndeployFunction undeployFunction = new UndeployFunction();
+
+  /**
+   * Undeploy one or more JAR files from members of a group or all members.
+   *
+   * @param groups Group(s) to undeploy the JAR from or null for all members
+   * @param jars JAR(s) to undeploy (separated by comma)
+   * @return The result of the attempt to undeploy
+   */
+  @CliCommand(value = {CliStrings.UNDEPLOY}, help = CliStrings.UNDEPLOY__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
+  public Result undeploy(
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.UNDEPLOY__GROUP__HELP,
+          optionContext = ConverterHint.MEMBERGROUP) String[] groups,
+      @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
+          help = CliStrings.UNDEPLOY__JAR__HELP) String[] jars) {
+
+    try {
+      TabularResultData tabularData = ResultBuilder.createTabularResultData();
+      boolean accumulatedData = false;
+
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(this.undeployFunction, new Object[] {jars}, targetMembers);
+      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+      for (CliFunctionResult result : results) {
+
+        if (result.getThrowable() != null) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Un-Deployed JAR", "");
+          tabularData.accumulate("Un-Deployed JAR Location",
+              "ERROR: " + result.getThrowable().getClass().getName() + ": "
+                  + result.getThrowable().getMessage());
+          accumulatedData = true;
+          tabularData.setStatus(Result.Status.ERROR);
+        } else {
+          String[] strings = (String[]) result.getSerializables();
+          for (int i = 0; i < strings.length; i += 2) {
+            tabularData.accumulate("Member", result.getMemberIdOrName());
+            tabularData.accumulate("Un-Deployed JAR", strings[i]);
+            tabularData.accumulate("Un-Deployed From JAR Location", strings[i + 1]);
+            accumulatedData = true;
+          }
+        }
+      }
+
+      if (!accumulatedData) {
+        return ResultBuilder.createInfoResult(CliStrings.UNDEPLOY__NO_JARS_FOUND_MESSAGE);
+      }
+
+      Result result = ResultBuilder.buildResult(tabularData);
+      if (tabularData.getStatus().equals(Result.Status.OK)) {
+        persistClusterConfiguration(result,
+            () -> getSharedConfiguration().removeJars(jars, groups));
+      }
+      return result;
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult("Exception while attempting to un-deploy: "
+          + th.getClass().getName() + ": " + th.getMessage());
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/18f65de7/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
index f1cb1c7..9d3e086 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
@@ -83,9 +83,6 @@ public class DeployCommandsController extends AbstractMultiPartCommandsControlle
     if (hasValue(directory)) {
       command.addOption(CliStrings.DEPLOY__DIR, directory);
     }
-
-    // save(jarFileResources);
-
     return processCommand(command.toString(), ConvertUtils.convert(jarFileResources));
   }
 
@@ -104,8 +101,6 @@ public class DeployCommandsController extends AbstractMultiPartCommandsControlle
       command.addOption(CliStrings.JAR,
           StringUtils.join(jarFileNames, StringUtils.COMMA_DELIMITER));
     }
-
     return processCommand(command.toString());
   }
-
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/18f65de7/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployWithGroupsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployWithGroupsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployWithGroupsDUnitTest.java
index 8db7275..a89121f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployWithGroupsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployWithGroupsDUnitTest.java
@@ -36,7 +36,7 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 
 /**
- * Unit tests for the DeployCommands class
+ * Unit tests for DeployCommand, UndeployCommand, ListDeployedCommand
  * 
  * @since GemFire 7.0
  */


[26/47] geode git commit: GEODE-3436: Restore refactoring of DiskStoreCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of DiskStoreCommands

* See initial commit GEODE-3258 (5d6cad7755ec3c4fe931e3d0f8e89fb181038543)


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

Branch: refs/heads/feature/GEODE-3543
Commit: ca808714ef93ba5232ce5be5f7e2533106bcfc34
Parents: 0dc67f0
Author: YehEmily <em...@gmail.com>
Authored: Thu Aug 3 09:00:08 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:28 2017 -0700

----------------------------------------------------------------------
 .../commands/AlterOfflineDiskStoreCommand.java  |  141 ++
 .../cli/commands/BackupDiskStoreCommand.java    |  142 ++
 .../cli/commands/CompactDiskStoreCommand.java   |  185 +++
 .../CompactOfflineDiskStoreCommand.java         |  176 +++
 .../cli/commands/CreateDiskStoreCommand.java    |  166 ++
 .../cli/commands/DescribeDiskStoreCommand.java  |  177 +++
 .../DescribeOfflineDiskStoreCommand.java        |   75 +
 .../cli/commands/DestroyDiskStoreCommand.java   |  106 ++
 .../cli/commands/DiskStoreCommands.java         | 1433 ------------------
 .../cli/commands/DiskStoreCommandsUtils.java    |   60 +
 .../commands/ExportOfflineDiskStoreCommand.java |   68 +
 .../cli/commands/ListDiskStoresCommand.java     |  112 ++
 .../commands/RevokeMissingDiskStoreCommand.java |   61 +
 .../commands/ShowMissingDiskStoreCommand.java   |  149 ++
 .../UpgradeOfflineDiskStoreCommand.java         |  177 +++
 .../cli/commands/ValidateDiskStoreCommand.java  |  104 ++
 .../DiskStoreCommandsController.java            |   18 +-
 .../commands/DiskStoreCommandsDUnitTest.java    |   46 +-
 .../commands/DiskStoreCommandsJUnitTest.java    |  112 +-
 ...stAndDescribeDiskStoreCommandsDUnitTest.java |   36 +-
 20 files changed, 2041 insertions(+), 1503 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterOfflineDiskStoreCommand.java
new file mode 100644
index 0000000..ce7594e
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterOfflineDiskStoreCommand.java
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.File;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.CacheExistsException;
+import org.apache.geode.cache.Region;
+import org.apache.geode.internal.cache.DiskStoreImpl;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+
+public class AlterOfflineDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.ALTER_DISK_STORE, help = CliStrings.ALTER_DISK_STORE__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  public Result alterOfflineDiskStore(
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__DISKSTORENAME, mandatory = true,
+          help = CliStrings.ALTER_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__REGIONNAME, mandatory = true,
+          help = CliStrings.ALTER_DISK_STORE__REGIONNAME__HELP) String regionName,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__DISKDIRS,
+          help = CliStrings.ALTER_DISK_STORE__DISKDIRS__HELP, mandatory = true) String[] diskDirs,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__COMPRESSOR, specifiedDefaultValue = "none",
+          help = CliStrings.ALTER_DISK_STORE__COMPRESSOR__HELP) String compressorClassName,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL,
+          help = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL__HELP) Integer concurrencyLevel,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED,
+          help = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED__HELP) Boolean statisticsEnabled,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY,
+          help = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY__HELP) Integer initialCapacity,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR,
+          help = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR__HELP) Float loadFactor,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION,
+          help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION__HELP) String lruEvictionAction,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM,
+          help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM__HELP) String lruEvictionAlgo,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT,
+          help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT__HELP) Integer lruEvictionLimit,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__OFF_HEAP,
+          help = CliStrings.ALTER_DISK_STORE__OFF_HEAP__HELP) Boolean offHeap,
+      @CliOption(key = CliStrings.ALTER_DISK_STORE__REMOVE,
+          help = CliStrings.ALTER_DISK_STORE__REMOVE__HELP, specifiedDefaultValue = "true",
+          unspecifiedDefaultValue = "false") boolean remove) {
+
+    Result result;
+
+    try {
+      File[] dirs = null;
+
+      if (diskDirs != null) {
+        dirs = new File[diskDirs.length];
+        for (int i = 0; i < diskDirs.length; i++) {
+          dirs[i] = new File((diskDirs[i]));
+        }
+      }
+
+      if (regionName.equals(Region.SEPARATOR)) {
+        return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
+      }
+
+      if ((lruEvictionAlgo != null) || (lruEvictionAction != null) || (lruEvictionLimit != null)
+          || (concurrencyLevel != null) || (initialCapacity != null) || (loadFactor != null)
+          || (compressorClassName != null) || (offHeap != null) || (statisticsEnabled != null)) {
+        if (!remove) {
+          String lruEvictionLimitString =
+              lruEvictionLimit == null ? null : lruEvictionLimit.toString();
+          String concurrencyLevelString =
+              concurrencyLevel == null ? null : concurrencyLevel.toString();
+          String initialCapacityString =
+              initialCapacity == null ? null : initialCapacity.toString();
+          String loadFactorString = loadFactor == null ? null : loadFactor.toString();
+          String statisticsEnabledString =
+              statisticsEnabled == null ? null : statisticsEnabled.toString();
+          String offHeapString = offHeap == null ? null : offHeap.toString();
+
+          if ("none".equals(compressorClassName)) {
+            compressorClassName = "";
+          }
+
+          String resultMessage = DiskStoreImpl.modifyRegion(diskStoreName, dirs, "/" + regionName,
+              lruEvictionAlgo, lruEvictionAction, lruEvictionLimitString, concurrencyLevelString,
+              initialCapacityString, loadFactorString, compressorClassName, statisticsEnabledString,
+              offHeapString, false);
+
+          result = ResultBuilder.createInfoResult(resultMessage);
+        } else {
+          result = ResultBuilder.createParsingErrorResult(
+              "Cannot use the --remove=true parameter with any other parameters");
+        }
+      } else {
+        if (remove) {
+          DiskStoreImpl.destroyRegion(diskStoreName, dirs, "/" + regionName);
+          result = ResultBuilder.createInfoResult("The region " + regionName
+              + " was successfully removed from the disk store " + diskStoreName);
+        } else {
+          // Please provide an option
+          result = ResultBuilder.createParsingErrorResult("Please provide a relevant parameter");
+        }
+      }
+      // Catch the IllegalArgumentException thrown by the modifyDiskStore function and sent the
+    } catch (IllegalArgumentException e) {
+      String message = "Please check the parameters";
+      message += "\n" + e.getMessage();
+      result = ResultBuilder.createGemFireErrorResult(message);
+    } catch (IllegalStateException e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    } catch (CacheExistsException e) {
+      // Indicates that the command is being used when a cache is open
+      result = ResultBuilder.createGemFireErrorResult("Cannot execute "
+          + CliStrings.ALTER_DISK_STORE + " when a cache exists (Offline command)");
+    } catch (Exception e) {
+      result = createErrorResult(e.getMessage());
+    }
+    return result;
+  }
+
+  private Result createErrorResult(String message) {
+    ErrorResultData erd = ResultBuilder.createErrorResultData();
+    erd.addLine(message);
+    return ResultBuilder.buildResult(erd);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/BackupDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/BackupDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/BackupDiskStoreCommand.java
new file mode 100644
index 0000000..6fc5df1
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/BackupDiskStoreCommand.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.File;
+import java.util.Map;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.admin.BackupStatus;
+import org.apache.geode.admin.internal.AdminDistributedSystemImpl;
+import org.apache.geode.cache.persistence.PersistentID;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.DM;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class BackupDiskStoreCommand implements GfshCommand {
+  /**
+   * Internally, we also verify the resource operation permissions CLUSTER:WRITE:DISK if the region
+   * is persistent
+   */
+  @CliCommand(value = CliStrings.BACKUP_DISK_STORE, help = CliStrings.BACKUP_DISK_STORE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  @ResourceOperation(resource = ResourcePermission.Resource.DATA,
+      operation = ResourcePermission.Operation.READ)
+  public Result backupDiskStore(
+      @CliOption(key = CliStrings.BACKUP_DISK_STORE__DISKDIRS,
+          help = CliStrings.BACKUP_DISK_STORE__DISKDIRS__HELP, mandatory = true) String targetDir,
+      @CliOption(key = CliStrings.BACKUP_DISK_STORE__BASELINEDIR,
+          help = CliStrings.BACKUP_DISK_STORE__BASELINEDIR__HELP) String baselineDir) {
+
+    getSecurityService().authorize(ResourcePermission.Resource.CLUSTER,
+        ResourcePermission.Operation.WRITE, ResourcePermission.Target.DISK);
+    Result result;
+    try {
+      InternalCache cache = getCache();
+      DM dm = cache.getDistributionManager();
+      BackupStatus backupStatus;
+
+      if (baselineDir != null && !baselineDir.isEmpty()) {
+        backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir),
+            new File(baselineDir));
+      } else {
+        backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir), null);
+      }
+
+      Map<DistributedMember, Set<PersistentID>> backedupMemberDiskstoreMap =
+          backupStatus.getBackedUpDiskStores();
+
+      Set<DistributedMember> backedupMembers = backedupMemberDiskstoreMap.keySet();
+      CompositeResultData crd = ResultBuilder.createCompositeResultData();
+
+      if (!backedupMembers.isEmpty()) {
+        CompositeResultData.SectionResultData backedupDiskStoresSection = crd.addSection();
+        backedupDiskStoresSection.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_BACKED_UP_DISK_STORES);
+        TabularResultData backedupDiskStoresTable = backedupDiskStoresSection.addTable();
+
+        for (DistributedMember member : backedupMembers) {
+          Set<PersistentID> backedupDiskStores = backedupMemberDiskstoreMap.get(member);
+          boolean printMember = true;
+          String memberName = member.getName();
+
+          if (memberName == null || memberName.isEmpty()) {
+            memberName = member.getId();
+          }
+          for (PersistentID persistentId : backedupDiskStores) {
+            if (persistentId != null) {
+
+              String UUID = persistentId.getUUID().toString();
+              String hostName = persistentId.getHost().getHostName();
+              String directory = persistentId.getDirectory();
+
+              if (printMember) {
+                writeToBackupDiskStoreTable(backedupDiskStoresTable, memberName, UUID, hostName,
+                    directory);
+                printMember = false;
+              } else {
+                writeToBackupDiskStoreTable(backedupDiskStoresTable, "", UUID, hostName, directory);
+              }
+            }
+          }
+        }
+      } else {
+        CompositeResultData.SectionResultData noMembersBackedUp = crd.addSection();
+        noMembersBackedUp.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_NO_DISKSTORES_BACKED_UP);
+      }
+
+      Set<PersistentID> offlineDiskStores = backupStatus.getOfflineDiskStores();
+
+      if (!offlineDiskStores.isEmpty()) {
+        CompositeResultData.SectionResultData offlineDiskStoresSection = crd.addSection();
+        TabularResultData offlineDiskStoresTable = offlineDiskStoresSection.addTable();
+
+        offlineDiskStoresSection.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_OFFLINE_DISK_STORES);
+        for (PersistentID offlineDiskStore : offlineDiskStores) {
+          offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID,
+              offlineDiskStore.getUUID().toString());
+          offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_HOST,
+              offlineDiskStore.getHost().getHostName());
+          offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY,
+              offlineDiskStore.getDirectory());
+        }
+      }
+      result = ResultBuilder.buildResult(crd);
+
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+    return result;
+  }
+
+  private void writeToBackupDiskStoreTable(TabularResultData backedupDiskStoreTable,
+      String memberId, String UUID, String host, String directory) {
+    backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_MEMBER, memberId);
+    backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID, UUID);
+    backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY, directory);
+    backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_HOST, host);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactDiskStoreCommand.java
new file mode 100644
index 0000000..34cc6c3
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactDiskStoreCommand.java
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.persistence.PersistentID;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.messages.CompactRequest;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CompactDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.COMPACT_DISK_STORE, help = CliStrings.COMPACT_DISK_STORE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.DISK)
+  public Result compactDiskStore(
+      @CliOption(key = CliStrings.COMPACT_DISK_STORE__NAME, mandatory = true,
+          optionContext = ConverterHint.DISKSTORE,
+          help = CliStrings.COMPACT_DISK_STORE__NAME__HELP) String diskStoreName,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.COMPACT_DISK_STORE__GROUP__HELP) String[] groups) {
+    Result result;
+
+    try {
+      // disk store exists validation
+      if (!diskStoreExists(diskStoreName)) {
+        result = ResultBuilder.createUserErrorResult(
+            CliStrings.format(CliStrings.COMPACT_DISK_STORE__DISKSTORE_0_DOES_NOT_EXIST,
+                new Object[] {diskStoreName}));
+      } else {
+        InternalDistributedSystem ds = getCache().getInternalDistributedSystem();
+
+        Map<DistributedMember, PersistentID> overallCompactInfo = new HashMap<>();
+
+        Set<?> otherMembers = ds.getDistributionManager().getOtherNormalDistributionManagerIds();
+        Set<InternalDistributedMember> allMembers = new HashSet<>();
+
+        for (Object member : otherMembers) {
+          allMembers.add((InternalDistributedMember) member);
+        }
+        allMembers.add(ds.getDistributedMember());
+
+        String groupInfo = "";
+        // if groups are specified, find members in the specified group
+        if (groups != null && groups.length > 0) {
+          groupInfo = CliStrings.format(CliStrings.COMPACT_DISK_STORE__MSG__FOR_GROUP,
+              new Object[] {Arrays.toString(groups) + "."});
+          final Set<InternalDistributedMember> selectedMembers = new HashSet<>();
+          List<String> targetedGroups = Arrays.asList(groups);
+          for (InternalDistributedMember member : allMembers) {
+            List<String> memberGroups = member.getGroups();
+            if (!Collections.disjoint(targetedGroups, memberGroups)) {
+              selectedMembers.add(member);
+            }
+          }
+
+          allMembers = selectedMembers;
+        }
+
+        // allMembers should not be empty when groups are not specified - it'll
+        // have at least one member
+        if (allMembers.isEmpty()) {
+          result = ResultBuilder.createUserErrorResult(
+              CliStrings.format(CliStrings.COMPACT_DISK_STORE__NO_MEMBERS_FOUND_IN_SPECIFED_GROUP,
+                  new Object[] {Arrays.toString(groups)}));
+        } else {
+          // first invoke on local member if it exists in the targeted set
+          if (allMembers.remove(ds.getDistributedMember())) {
+            PersistentID compactedDiskStoreId = CompactRequest.compactDiskStore(diskStoreName);
+            if (compactedDiskStoreId != null) {
+              overallCompactInfo.put(ds.getDistributedMember(), compactedDiskStoreId);
+            }
+          }
+
+          // was this local member the only one? Then don't try to send
+          // CompactRequest. Otherwise, send the request to others
+          if (!allMembers.isEmpty()) {
+            // Invoke compact on all 'other' members
+            Map<DistributedMember, PersistentID> memberCompactInfo =
+                CompactRequest.send(ds.getDistributionManager(), diskStoreName, allMembers);
+            if (memberCompactInfo != null && !memberCompactInfo.isEmpty()) {
+              overallCompactInfo.putAll(memberCompactInfo);
+              memberCompactInfo.clear();
+            }
+            String notExecutedMembers = CompactRequest.getNotExecutedMembers();
+            if (notExecutedMembers != null && !notExecutedMembers.isEmpty()) {
+              LogWrapper.getInstance()
+                  .info("compact disk-store \"" + diskStoreName
+                      + "\" message was scheduled to be sent to but was not send to "
+                      + notExecutedMembers);
+            }
+          }
+
+          // If compaction happened at all, then prepare the summary
+          if (overallCompactInfo != null && !overallCompactInfo.isEmpty()) {
+            CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
+            CompositeResultData.SectionResultData section;
+
+            Set<Map.Entry<DistributedMember, PersistentID>> entries = overallCompactInfo.entrySet();
+
+            for (Map.Entry<DistributedMember, PersistentID> entry : entries) {
+              String memberId = entry.getKey().getId();
+              section = compositeResultData.addSection(memberId);
+              section.addData("On Member", memberId);
+
+              PersistentID persistentID = entry.getValue();
+              if (persistentID != null) {
+                CompositeResultData.SectionResultData subSection =
+                    section.addSection("DiskStore" + memberId);
+                subSection.addData("UUID", persistentID.getUUID());
+                subSection.addData("Host", persistentID.getHost().getHostName());
+                subSection.addData("Directory", persistentID.getDirectory());
+              }
+            }
+            compositeResultData.setHeader("Compacted " + diskStoreName + groupInfo);
+            result = ResultBuilder.buildResult(compositeResultData);
+          } else {
+            result = ResultBuilder.createInfoResult(
+                CliStrings.COMPACT_DISK_STORE__COMPACTION_ATTEMPTED_BUT_NOTHING_TO_COMPACT);
+          }
+        } // all members' if
+      } // disk store exists' if
+    } catch (RuntimeException e) {
+      LogWrapper.getInstance().info(e.getMessage(), e);
+      result = ResultBuilder.createGemFireErrorResult(
+          CliStrings.format(CliStrings.COMPACT_DISK_STORE__ERROR_WHILE_COMPACTING_REASON_0,
+              new Object[] {e.getMessage()}));
+    }
+    return result;
+  }
+
+  private boolean diskStoreExists(String diskStoreName) {
+    InternalCache cache = getCache();
+    ManagementService managementService = ManagementService.getExistingManagementService(cache);
+    DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
+    Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
+
+    Set<Map.Entry<String, String[]>> entrySet = diskstore.entrySet();
+
+    for (Map.Entry<String, String[]> entry : entrySet) {
+      String[] value = entry.getValue();
+      if (CliUtil.contains(value, diskStoreName)) {
+        return true;
+      }
+    }
+    return false;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactOfflineDiskStoreCommand.java
new file mode 100644
index 0000000..ae73440
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactOfflineDiskStoreCommand.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.GemFireIOException;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParser;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
+import org.apache.geode.management.internal.cli.util.DiskStoreCompacter;
+
+public class CompactOfflineDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.COMPACT_OFFLINE_DISK_STORE,
+      help = CliStrings.COMPACT_OFFLINE_DISK_STORE__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  public Result compactOfflineDiskStore(
+      @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME, mandatory = true,
+          help = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
+      @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
+          help = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+      @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
+          unspecifiedDefaultValue = "-1",
+          help = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
+      @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__J,
+          help = CliStrings.COMPACT_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps) {
+    Result result;
+    LogWrapper logWrapper = LogWrapper.getInstance();
+
+    StringBuilder output = new StringBuilder();
+    StringBuilder error = new StringBuilder();
+    StringBuilder errorMessage = new StringBuilder();
+    Process compacterProcess = null;
+
+    try {
+      String validatedDirectories = DiskStoreCommandsUtils.validatedDirectories(diskDirs);
+      if (validatedDirectories != null) {
+        throw new IllegalArgumentException(
+            "Could not find " + CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS + ": \""
+                + validatedDirectories + "\"");
+      }
+
+      List<String> commandList = new ArrayList<>();
+      commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+          + File.separatorChar + "java");
+
+      DiskStoreCommandsUtils.configureLogging(commandList);
+
+      if (jvmProps != null && jvmProps.length != 0) {
+        commandList.addAll(Arrays.asList(jvmProps));
+      }
+      commandList.add("-classpath");
+      commandList.add(System.getProperty("java.class.path", "."));
+      commandList.add(DiskStoreCompacter.class.getName());
+
+      commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);
+
+      if (diskDirs != null && diskDirs.length != 0) {
+        StringBuilder builder = new StringBuilder();
+        int arrayLength = diskDirs.length;
+        for (int i = 0; i < arrayLength; i++) {
+          if (File.separatorChar == '\\') {
+            builder.append(diskDirs[i].replace("\\", "/")); // see 46120
+          } else {
+            builder.append(diskDirs[i]);
+          }
+          if (i + 1 != arrayLength) {
+            builder.append(',');
+          }
+        }
+        commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder.toString());
+      }
+      // -1 is ignore as maxOplogSize
+      commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);
+
+      ProcessBuilder procBuilder = new ProcessBuilder(commandList);
+      compacterProcess = procBuilder.start();
+      InputStream inputStream = compacterProcess.getInputStream();
+      InputStream errorStream = compacterProcess.getErrorStream();
+      BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
+      BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
+
+      String line;
+      while ((line = inputReader.readLine()) != null) {
+        output.append(line).append(GfshParser.LINE_SEPARATOR);
+      }
+
+      boolean switchToStackTrace = false;
+      while ((line = errorReader.readLine()) != null) {
+        if (!switchToStackTrace && DiskStoreCompacter.STACKTRACE_START.equals(line)) {
+          switchToStackTrace = true;
+        } else if (switchToStackTrace) {
+          error.append(line).append(GfshParser.LINE_SEPARATOR);
+        } else {
+          errorMessage.append(line);
+        }
+      }
+
+      if (errorMessage.length() > 0) {
+        throw new GemFireIOException(errorMessage.toString());
+      }
+
+      // do we have to waitFor??
+      compacterProcess.destroy();
+      result = ResultBuilder.createInfoResult(output.toString());
+    } catch (IOException e) {
+      if (output.length() != 0) {
+        Gfsh.println(output.toString());
+      }
+      String fieldsMessage = (maxOplogSize != -1
+          ? CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize + "," : "");
+      fieldsMessage += CliUtil.arrayToString(diskDirs);
+      String errorString = CliStrings.format(
+          CliStrings.COMPACT_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2,
+          diskStoreName, fieldsMessage);
+      result = ResultBuilder.createUserErrorResult(errorString);
+      if (logWrapper.fineEnabled()) {
+        logWrapper.fine(e.getMessage(), e);
+      }
+    } catch (GemFireIOException e) {
+      if (output.length() != 0) {
+        Gfsh.println(output.toString());
+      }
+      result = ResultBuilder.createUserErrorResult(errorMessage.toString());
+      if (logWrapper.fineEnabled()) {
+        logWrapper.fine(error.toString());
+      }
+    } catch (IllegalArgumentException e) {
+      if (output.length() != 0) {
+        Gfsh.println(output.toString());
+      }
+      result = ResultBuilder.createUserErrorResult(e.getMessage());
+    } finally {
+      if (compacterProcess != null) {
+        try {
+          // just to check whether the process has exited
+          // Process.exitValue() throws IllegalThreadStateException if Process
+          // is alive
+          compacterProcess.exitValue();
+        } catch (IllegalThreadStateException ise) {
+          // not yet terminated, destroy the process
+          compacterProcess.destroy();
+        }
+      }
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDiskStoreCommand.java
new file mode 100644
index 0000000..19784d6
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDiskStoreCommand.java
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.File;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.DiskStoreAttributes;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.CreateDiskStoreFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CreateDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.CREATE_DISK_STORE, help = CliStrings.CREATE_DISK_STORE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.DISK)
+  public Result createDiskStore(
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__NAME, mandatory = true,
+          optionContext = ConverterHint.DISKSTORE,
+          help = CliStrings.CREATE_DISK_STORE__NAME__HELP) String name,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__ALLOW_FORCE_COMPACTION,
+          specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
+          help = CliStrings.CREATE_DISK_STORE__ALLOW_FORCE_COMPACTION__HELP) boolean allowForceCompaction,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__AUTO_COMPACT, specifiedDefaultValue = "true",
+          unspecifiedDefaultValue = "true",
+          help = CliStrings.CREATE_DISK_STORE__AUTO_COMPACT__HELP) boolean autoCompact,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__COMPACTION_THRESHOLD,
+          unspecifiedDefaultValue = "50",
+          help = CliStrings.CREATE_DISK_STORE__COMPACTION_THRESHOLD__HELP) int compactionThreshold,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__MAX_OPLOG_SIZE,
+          unspecifiedDefaultValue = "1024",
+          help = CliStrings.CREATE_DISK_STORE__MAX_OPLOG_SIZE__HELP) int maxOplogSize,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__QUEUE_SIZE, unspecifiedDefaultValue = "0",
+          help = CliStrings.CREATE_DISK_STORE__QUEUE_SIZE__HELP) int queueSize,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__TIME_INTERVAL,
+          unspecifiedDefaultValue = "1000",
+          help = CliStrings.CREATE_DISK_STORE__TIME_INTERVAL__HELP) long timeInterval,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__WRITE_BUFFER_SIZE,
+          unspecifiedDefaultValue = "32768",
+          help = CliStrings.CREATE_DISK_STORE__WRITE_BUFFER_SIZE__HELP) int writeBufferSize,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE, mandatory = true,
+          help = CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE__HELP) String[] directoriesAndSizes,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.CREATE_DISK_STORE__GROUP__HELP,
+          optionContext = ConverterHint.MEMBERGROUP) String[] groups,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__DISK_USAGE_WARNING_PCT,
+          unspecifiedDefaultValue = "90",
+          help = CliStrings.CREATE_DISK_STORE__DISK_USAGE_WARNING_PCT__HELP) float diskUsageWarningPercentage,
+      @CliOption(key = CliStrings.CREATE_DISK_STORE__DISK_USAGE_CRITICAL_PCT,
+          unspecifiedDefaultValue = "99",
+          help = CliStrings.CREATE_DISK_STORE__DISK_USAGE_CRITICAL_PCT__HELP) float diskUsageCriticalPercentage) {
+
+    try {
+      DiskStoreAttributes diskStoreAttributes = new DiskStoreAttributes();
+      diskStoreAttributes.allowForceCompaction = allowForceCompaction;
+      diskStoreAttributes.autoCompact = autoCompact;
+      diskStoreAttributes.compactionThreshold = compactionThreshold;
+      diskStoreAttributes.maxOplogSizeInBytes = maxOplogSize * (1024 * 1024);
+      diskStoreAttributes.queueSize = queueSize;
+      diskStoreAttributes.timeInterval = timeInterval;
+      diskStoreAttributes.writeBufferSize = writeBufferSize;
+
+      File[] directories = new File[directoriesAndSizes.length];
+      int[] sizes = new int[directoriesAndSizes.length];
+      for (int i = 0; i < directoriesAndSizes.length; i++) {
+        final int hashPosition = directoriesAndSizes[i].indexOf('#');
+        if (hashPosition == -1) {
+          directories[i] = new File(directoriesAndSizes[i]);
+          sizes[i] = Integer.MAX_VALUE;
+        } else {
+          directories[i] = new File(directoriesAndSizes[i].substring(0, hashPosition));
+          sizes[i] = Integer.parseInt(directoriesAndSizes[i].substring(hashPosition + 1));
+        }
+      }
+      diskStoreAttributes.diskDirs = directories;
+      diskStoreAttributes.diskDirSizes = sizes;
+
+      diskStoreAttributes.setDiskUsageWarningPercentage(diskUsageWarningPercentage);
+      diskStoreAttributes.setDiskUsageCriticalPercentage(diskUsageCriticalPercentage);
+
+      TabularResultData tabularData = ResultBuilder.createTabularResultData();
+      boolean accumulatedData = false;
+
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      ResultCollector<?, ?> rc = CliUtil.executeFunction(new CreateDiskStoreFunction(),
+          new Object[] {name, diskStoreAttributes}, targetMembers);
+      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+      AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+      for (CliFunctionResult result : results) {
+        if (result.getThrowable() != null) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
+              + ": " + result.getThrowable().getMessage());
+          accumulatedData = true;
+          tabularData.setStatus(Result.Status.ERROR);
+        } else if (result.isSuccessful()) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Result", result.getMessage());
+          accumulatedData = true;
+
+          if (xmlEntity.get() == null) {
+            xmlEntity.set(result.getXmlEntity());
+          }
+        }
+      }
+
+      if (!accumulatedData) {
+        return ResultBuilder.createInfoResult("Unable to create disk store(s).");
+      }
+
+      Result result = ResultBuilder.buildResult(tabularData);
+
+      if (xmlEntity.get() != null) {
+        persistClusterConfiguration(result,
+            () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
+      }
+
+      return ResultBuilder.buildResult(tabularData);
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult(
+          CliStrings.format(CliStrings.CREATE_DISK_STORE__ERROR_WHILE_CREATING_REASON_0,
+              new Object[] {th.getMessage()}));
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeDiskStoreCommand.java
new file mode 100644
index 0000000..4efd973
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeDiskStoreCommand.java
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.lang.ClassUtils;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
+import org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.cli.util.DiskStoreNotFoundException;
+import org.apache.geode.management.internal.cli.util.MemberNotFoundException;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DescribeDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.DESCRIBE_DISK_STORE, help = CliStrings.DESCRIBE_DISK_STORE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result describeDiskStore(
+      @CliOption(key = CliStrings.MEMBER, mandatory = true,
+          optionContext = ConverterHint.MEMBERIDNAME,
+          help = CliStrings.DESCRIBE_DISK_STORE__MEMBER__HELP) final String memberName,
+      @CliOption(key = CliStrings.DESCRIBE_DISK_STORE__NAME, mandatory = true,
+          optionContext = ConverterHint.DISKSTORE,
+          help = CliStrings.DESCRIBE_DISK_STORE__NAME__HELP) final String diskStoreName) {
+    try {
+      return toCompositeResult(getDiskStoreDescription(memberName, diskStoreName));
+    } catch (DiskStoreNotFoundException | MemberNotFoundException e) {
+      return ResultBuilder.createShellClientErrorResult(e.getMessage());
+    } catch (FunctionInvocationTargetException ignore) {
+      return ResultBuilder.createGemFireErrorResult(CliStrings
+          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_DISK_STORE));
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable t) {
+      SystemFailure.checkFailure();
+      return ResultBuilder
+          .createGemFireErrorResult(String.format(CliStrings.DESCRIBE_DISK_STORE__ERROR_MESSAGE,
+              memberName, diskStoreName, toString(t, isDebugging())));
+    }
+  }
+
+  DiskStoreDetails getDiskStoreDescription(final String memberName, final String diskStoreName) {
+    final DistributedMember member = getMember(getCache(), memberName);
+
+    final ResultCollector<?, ?> resultCollector =
+        getMembersFunctionExecutor(Collections.singleton(member)).setArguments(diskStoreName)
+            .execute(new DescribeDiskStoreFunction());
+
+    final Object result = ((List<?>) resultCollector.getResult()).get(0);
+
+    if (result instanceof DiskStoreDetails) { // disk store details in hand...
+      return (DiskStoreDetails) result;
+    } else if (result instanceof DiskStoreNotFoundException) { // bad disk store name...
+      throw (DiskStoreNotFoundException) result;
+    } else { // unknown and unexpected return type...
+      final Throwable cause = (result instanceof Throwable ? (Throwable) result : null);
+
+      if (isLogging()) {
+        if (cause != null) {
+          getGfsh().logSevere(String.format(
+              "Exception (%1$s) occurred while executing '%2$s' on member (%3$s) with disk store (%4$s).",
+              ClassUtils.getClassName(cause), CliStrings.DESCRIBE_DISK_STORE, memberName,
+              diskStoreName), cause);
+        } else {
+          getGfsh().logSevere(String.format(
+              "Received an unexpected result of type (%1$s) while executing '%2$s' on member (%3$s) with disk store (%4$s).",
+              ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE, memberName,
+              diskStoreName), null);
+        }
+      }
+
+      throw new RuntimeException(
+          CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
+              ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE),
+          cause);
+    }
+  }
+
+  private Result toCompositeResult(final DiskStoreDetails diskStoreDetails) {
+    final CompositeResultData diskStoreData = ResultBuilder.createCompositeResultData();
+
+    final CompositeResultData.SectionResultData diskStoreSection = diskStoreData.addSection();
+
+    diskStoreSection.addData("Disk Store ID", diskStoreDetails.getId());
+    diskStoreSection.addData("Disk Store Name", diskStoreDetails.getName());
+    diskStoreSection.addData("Member ID", diskStoreDetails.getMemberId());
+    diskStoreSection.addData("Member Name", diskStoreDetails.getMemberName());
+    diskStoreSection.addData("Allow Force Compaction",
+        toString(diskStoreDetails.isAllowForceCompaction(), "Yes", "No"));
+    diskStoreSection.addData("Auto Compaction",
+        toString(diskStoreDetails.isAutoCompact(), "Yes", "No"));
+    diskStoreSection.addData("Compaction Threshold", diskStoreDetails.getCompactionThreshold());
+    diskStoreSection.addData("Max Oplog Size", diskStoreDetails.getMaxOplogSize());
+    diskStoreSection.addData("Queue Size", diskStoreDetails.getQueueSize());
+    diskStoreSection.addData("Time Interval", diskStoreDetails.getTimeInterval());
+    diskStoreSection.addData("Write Buffer Size", diskStoreDetails.getWriteBufferSize());
+    diskStoreSection.addData("Disk Usage Warning Percentage",
+        diskStoreDetails.getDiskUsageWarningPercentage());
+    diskStoreSection.addData("Disk Usage Critical Percentage",
+        diskStoreDetails.getDiskUsageCriticalPercentage());
+    diskStoreSection.addData("PDX Serialization Meta-Data Stored",
+        toString(diskStoreDetails.isPdxSerializationMetaDataStored(), "Yes", "No"));
+
+    final TabularResultData diskDirTable = diskStoreData.addSection().addTable();
+
+    for (DiskStoreDetails.DiskDirDetails diskDirDetails : diskStoreDetails) {
+      diskDirTable.accumulate("Disk Directory", diskDirDetails.getAbsolutePath());
+      diskDirTable.accumulate("Size", diskDirDetails.getSize());
+    }
+
+    final TabularResultData regionTable = diskStoreData.addSection().addTable();
+
+    for (DiskStoreDetails.RegionDetails regionDetails : diskStoreDetails.iterateRegions()) {
+      regionTable.accumulate("Region Path", regionDetails.getFullPath());
+      regionTable.accumulate("Region Name", regionDetails.getName());
+      regionTable.accumulate("Persistent", toString(regionDetails.isPersistent(), "Yes", "No"));
+      regionTable.accumulate("Overflow To Disk",
+          toString(regionDetails.isOverflowToDisk(), "Yes", "No"));
+    }
+
+    final TabularResultData cacheServerTable = diskStoreData.addSection().addTable();
+
+    for (DiskStoreDetails.CacheServerDetails cacheServerDetails : diskStoreDetails
+        .iterateCacheServers()) {
+      cacheServerTable.accumulate("Bind Address", cacheServerDetails.getBindAddress());
+      cacheServerTable.accumulate("Hostname for Clients", cacheServerDetails.getHostName());
+      cacheServerTable.accumulate("Port", cacheServerDetails.getPort());
+    }
+
+    final TabularResultData gatewayTable = diskStoreData.addSection().addTable();
+
+    for (DiskStoreDetails.GatewayDetails gatewayDetails : diskStoreDetails.iterateGateways()) {
+      gatewayTable.accumulate("Gateway ID", gatewayDetails.getId());
+      gatewayTable.accumulate("Persistent", toString(gatewayDetails.isPersistent(), "Yes", "No"));
+    }
+
+    final TabularResultData asyncEventQueueTable = diskStoreData.addSection().addTable();
+
+    for (DiskStoreDetails.AsyncEventQueueDetails asyncEventQueueDetails : diskStoreDetails
+        .iterateAsyncEventQueues()) {
+      asyncEventQueueTable.accumulate("Async Event Queue ID", asyncEventQueueDetails.getId());
+    }
+
+    return ResultBuilder.buildResult(diskStoreData);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeOfflineDiskStoreCommand.java
new file mode 100644
index 0000000..904a677
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeOfflineDiskStoreCommand.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.PrintStream;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.Region;
+import org.apache.geode.internal.cache.DiskStoreImpl;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+
+public class DescribeOfflineDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.DESCRIBE_OFFLINE_DISK_STORE,
+      help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  public Result describeOfflineDiskStore(
+      @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME, mandatory = true,
+          help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
+      @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
+          help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+      @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES,
+          help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES__HELP) Boolean listPdxTypes,
+      @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME,
+          help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME__HELP) String regionName) {
+
+    try {
+      final File[] dirs = new File[diskDirs.length];
+      for (int i = 0; i < diskDirs.length; i++) {
+        dirs[i] = new File((diskDirs[i]));
+      }
+
+      if (Region.SEPARATOR.equals(regionName)) {
+        return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
+      }
+
+      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+      PrintStream printStream = new PrintStream(outputStream);
+
+      DiskStoreImpl.dumpInfo(printStream, diskStoreName, dirs, regionName, listPdxTypes);
+      return ResultBuilder.createInfoResult(outputStream.toString());
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      if (th.getMessage() == null) {
+        return ResultBuilder.createGemFireErrorResult(
+            "An error occurred while describing offline disk stores: " + th);
+      }
+      return ResultBuilder.createGemFireErrorResult(
+          "An error occurred while describing offline disk stores: " + th.getMessage());
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyDiskStoreCommand.java
new file mode 100644
index 0000000..2f24736
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyDiskStoreCommand.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.DestroyDiskStoreFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DestroyDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.DESTROY_DISK_STORE, help = CliStrings.DESTROY_DISK_STORE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.DISK)
+  public Result destroyDiskStore(
+      @CliOption(key = CliStrings.DESTROY_DISK_STORE__NAME, mandatory = true,
+          help = CliStrings.DESTROY_DISK_STORE__NAME__HELP) String name,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.DESTROY_DISK_STORE__GROUP__HELP,
+          optionContext = ConverterHint.MEMBERGROUP) String[] groups) {
+    try {
+      TabularResultData tabularData = ResultBuilder.createTabularResultData();
+      boolean accumulatedData = false;
+
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      ResultCollector<?, ?> rc = CliUtil.executeFunction(new DestroyDiskStoreFunction(),
+          new Object[] {name}, targetMembers);
+      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+      AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+      for (CliFunctionResult result : results) {
+        if (result.getThrowable() != null) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
+              + ": " + result.getThrowable().getMessage());
+          accumulatedData = true;
+          tabularData.setStatus(Result.Status.ERROR);
+        } else if (result.getMessage() != null) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Result", result.getMessage());
+          accumulatedData = true;
+
+          if (xmlEntity.get() == null) {
+            xmlEntity.set(result.getXmlEntity());
+          }
+        }
+      }
+
+      if (!accumulatedData) {
+        return ResultBuilder.createInfoResult("No matching disk stores found.");
+      }
+
+      Result result = ResultBuilder.buildResult(tabularData);
+      if (xmlEntity.get() != null) {
+        persistClusterConfiguration(result,
+            () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), groups));
+      }
+
+      return result;
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult(
+          CliStrings.format(CliStrings.DESTROY_DISK_STORE__ERROR_WHILE_DESTROYING_REASON_0,
+              new Object[] {th.getMessage()}));
+    }
+  }
+}


[38/47] geode git commit: GEODE-3445: Convert connect acceptance test to DUnit test

Posted by ds...@apache.org.
GEODE-3445: Convert connect acceptance test to DUnit test


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

Branch: refs/heads/feature/GEODE-3543
Commit: 76b4ef57b30957ebe45a84f5b93cf09fb0734920
Parents: dd7c45b
Author: Jared Stewart <js...@pivotal.io>
Authored: Mon Aug 28 11:12:00 2017 -0700
Committer: Jared Stewart <js...@pivotal.io>
Committed: Tue Aug 29 15:05:40 2017 -0700

----------------------------------------------------------------------
 ...shConnectToLocatorWithSSLAcceptanceTest.java | 110 -------------------
 .../cli/commands/ConnectCommandWithSSLTest.java |  13 +--
 2 files changed, 5 insertions(+), 118 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/76b4ef57/geode-assembly/src/test/java/org/apache/geode/management/GfshConnectToLocatorWithSSLAcceptanceTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/GfshConnectToLocatorWithSSLAcceptanceTest.java b/geode-assembly/src/test/java/org/apache/geode/management/GfshConnectToLocatorWithSSLAcceptanceTest.java
deleted file mode 100644
index 75d60a3..0000000
--- a/geode-assembly/src/test/java/org/apache/geode/management/GfshConnectToLocatorWithSSLAcceptanceTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management;
-
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_CIPHERS;
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_ENABLED_COMPONENTS;
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_KEYSTORE;
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_KEYSTORE_PASSWORD;
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_KEYSTORE_TYPE;
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_PROTOCOLS;
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_TRUSTSTORE;
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_TRUSTSTORE_PASSWORD;
-import static org.apache.geode.distributed.ConfigurationProperties.SSL_TRUSTSTORE_TYPE;
-import static org.apache.geode.util.test.TestUtil.getResourcePath;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Properties;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TemporaryFolder;
-
-import org.apache.geode.security.SecurableCommunicationChannels;
-import org.apache.geode.test.dunit.rules.gfsh.GfshRule;
-import org.apache.geode.test.dunit.rules.gfsh.GfshScript;
-import org.apache.geode.test.junit.categories.AcceptanceTest;
-
-@Category(AcceptanceTest.class)
-public class GfshConnectToLocatorWithSSLAcceptanceTest {
-  @Rule
-  public GfshRule gfshRule = new GfshRule();
-
-  @Rule
-  public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
-  private File sslPropertiesFile;
-
-  @Before
-  public void setup() throws IOException {
-    File jks = new File(getResourcePath(getClass(), "/ssl/trusted.keystore"));
-    assertThat(jks).exists();
-
-    Properties serverProps = new Properties();
-    serverProps.setProperty(SSL_ENABLED_COMPONENTS, SecurableCommunicationChannels.ALL);
-    serverProps.setProperty(SSL_KEYSTORE, jks.getAbsolutePath());
-    serverProps.setProperty(SSL_KEYSTORE_PASSWORD, "password");
-    serverProps.setProperty(SSL_KEYSTORE_TYPE, "JKS");
-    serverProps.setProperty(SSL_TRUSTSTORE, jks.getAbsolutePath());
-    serverProps.setProperty(SSL_TRUSTSTORE_PASSWORD, "password");
-    serverProps.setProperty(SSL_TRUSTSTORE_TYPE, "JKS");
-    serverProps.setProperty(SSL_CIPHERS, "any");
-    serverProps.setProperty(SSL_PROTOCOLS, "any");
-
-    sslPropertiesFile = temporaryFolder.newFile("ssl.properties");
-    serverProps.store(new FileOutputStream(sslPropertiesFile), null);
-
-    GfshScript startLocator =
-        GfshScript.of("start locator --name=locator --security-properties-file="
-            + sslPropertiesFile.getAbsolutePath());
-    gfshRule.execute(startLocator);
-  }
-
-  @Test
-  public void canConnectOverHttpWithUnsignedSSLCertificateIfSkipSslValidationIsSet()
-      throws Exception {
-    GfshScript connect =
-        GfshScript.of("connect --use-http --skip-ssl-validation --security-properties-file="
-            + sslPropertiesFile.getAbsolutePath());
-    gfshRule.execute(connect);
-  }
-
-  @Test
-  public void cannotConnectOverHttpWithUnsignedSSLCertificateIfSkipSslValidationIsNotSet()
-      throws Exception {
-    GfshScript connect = GfshScript
-        .of("connect --use-http --security-properties-file=" + sslPropertiesFile.getAbsolutePath())
-        .expectFailure();
-    gfshRule.execute(connect);
-  }
-
-  @Test
-  public void cannotConnectOverHttpWithoutSSL() throws Exception {
-    GfshScript connect = GfshScript.of("connect --use-http").expectFailure();
-    gfshRule.execute(connect);
-  }
-
-  @Test
-  public void canConnectOverJmxWithSSL() throws Exception {
-    GfshScript connect = GfshScript.of("connect --use-http=false --security-properties-file="
-        + sslPropertiesFile.getAbsolutePath());
-    gfshRule.execute(connect);
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/76b4ef57/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithSSLTest.java
----------------------------------------------------------------------
diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithSSLTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithSSLTest.java
index 7c4fb44..39c1ba1 100644
--- a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithSSLTest.java
+++ b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithSSLTest.java
@@ -56,8 +56,6 @@ import java.io.OutputStream;
 import java.net.URISyntaxException;
 import java.util.Properties;
 
-import javax.net.ssl.HttpsURLConnection;
-
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -155,7 +153,6 @@ public class ConnectCommandWithSSLTest {
   @Before
   public void before() throws Exception {
     locator = lsRule.startLocatorVM(0, sslProperties);
-    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
     IgnoredException.addIgnoredException("javax.net.ssl.SSLException: Unrecognized SSL message");
     sslConfigFile = temporaryFolder.newFile("ssl.properties");
     out = new FileOutputStream(sslConfigFile);
@@ -197,7 +194,7 @@ public class ConnectCommandWithSSLTest {
     gfsh.disconnect();
 
     gfsh.connect(locator.getHttpPort(), GfshShellConnectionRule.PortType.http,
-        "security-properties-file", sslConfigFile.getAbsolutePath());
+        "security-properties-file", sslConfigFile.getAbsolutePath(), "skip-ssl-validation", "true");
     assertThat(gfsh.isConnected()).isTrue();
   }
 
@@ -245,9 +242,9 @@ public class ConnectCommandWithSSLTest {
     assertThat(gfsh.isConnected()).isTrue();
     gfsh.disconnect();
 
-    // can conect to http
+    // can connect to http
     gfsh.connect(locator.getHttpPort(), GfshShellConnectionRule.PortType.http,
-        "security-properties-file", sslConfigFile.getAbsolutePath());
+        "security-properties-file", sslConfigFile.getAbsolutePath(), "skip-ssl-validation", "true");
     assertThat(gfsh.isConnected()).isTrue();
   }
 
@@ -264,9 +261,9 @@ public class ConnectCommandWithSSLTest {
         "security-properties-file", sslConfigFile.getAbsolutePath());
     assertThat(gfsh.isConnected()).isFalse();
 
-    // cannot conect to http
+    // can conect to http
     gfsh.connect(locator.getHttpPort(), GfshShellConnectionRule.PortType.http,
-        "security-properties-file", sslConfigFile.getAbsolutePath());
+        "security-properties-file", sslConfigFile.getAbsolutePath(), "skip-ssl-validation", "true");
     assertThat(gfsh.isConnected()).isTrue();
   }
 


[02/47] geode git commit: [#150615582] limit .gitattributes to only java files

Posted by ds...@apache.org.
[#150615582] limit .gitattributes to only java files

Signed-off-by: Jens Deppe <jd...@pivotal.io>


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

Branch: refs/heads/feature/GEODE-3543
Commit: 21c1fb9d88d1fae657d527a13422540f5e8577ce
Parents: 73a847a
Author: Dick Cavender <dc...@pivotal.io>
Authored: Mon Aug 28 15:55:07 2017 -0700
Committer: Jens Deppe <jd...@pivotal.io>
Committed: Mon Aug 28 15:55:07 2017 -0700

----------------------------------------------------------------------
 .gitattributes | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/21c1fb9d/.gitattributes
----------------------------------------------------------------------
diff --git a/.gitattributes b/.gitattributes
index 6313b56..36dd437 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1 +1 @@
-* text=auto eol=lf
+*.java text=auto eol=lf


[45/47] geode git commit: GEODE-3330 Document modified CQ authorization permissions

Posted by ds...@apache.org.
GEODE-3330 Document modified CQ authorization permissions

    This closes #750


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

Branch: refs/heads/feature/GEODE-3543
Commit: 7417d73cf9960583c04c3e855f0aa6d4d649c3d6
Parents: f2492bf
Author: Karen Miller <km...@pivotal.io>
Authored: Wed Aug 30 14:00:28 2017 -0700
Committer: Karen Miller <km...@pivotal.io>
Committed: Wed Aug 30 14:25:11 2017 -0700

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


http://git-wip-us.apache.org/repos/asf/geode/blob/7417d73c/geode-docs/managing/security/implementing_authorization.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/managing/security/implementing_authorization.html.md.erb b/geode-docs/managing/security/implementing_authorization.html.md.erb
index 8f91825..e78b294 100644
--- a/geode-docs/managing/security/implementing_authorization.html.md.erb
+++ b/geode-docs/managing/security/implementing_authorization.html.md.erb
@@ -103,6 +103,8 @@ a Client-Server interaction.
 | Region.destroy(key)                | DATA:WRITE:RegionName:Key           |
 | Region.put(key)                    | DATA:WRITE:RegionName:Key           |
 | Region.replace                     | DATA:WRITE:RegionName:Key           |
+| CqQuery.execute                    | DATA:READ and CLUSTER:MANAGE:QUERY  |
+| CqQuery.executeWithInitialResults  | DATA:READ and CLUSTER:MANAGE:QUERY  |
 
 
 This table classifies the permissions assigned for `gfsh` operations.


[47/47] geode git commit: Merge branch 'develop' into feature/GEODE-3543

Posted by ds...@apache.org.
Merge branch 'develop' into feature/GEODE-3543


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

Branch: refs/heads/feature/GEODE-3543
Commit: adfac332acb202c9f65a7c5a211c1045ba7e9827
Parents: 762f39a 6a7442c
Author: Darrel Schneider <ds...@pivotal.io>
Authored: Wed Aug 30 18:23:57 2017 -0700
Committer: Darrel Schneider <ds...@pivotal.io>
Committed: Wed Aug 30 18:23:57 2017 -0700

----------------------------------------------------------------------
 .gitattributes                                  |    2 +-
 geode-assembly/build.gradle                     |    8 -
 .../org/apache/geode/BundledJarsJUnitTest.java  |   54 +-
 ...shConnectToLocatorWithSSLAcceptanceTest.java |  110 -
 .../cli/commands/GemfireCoreClasspathTest.java  |  101 +
 .../commands/GfshCommandIntegrationTest.java    |  177 --
 .../LauncherLifecycleCommandsDUnitTest.java     |    9 +-
 .../cli/commands/StatusLocatorRealGfshTest.java |   24 +-
 .../test/dunit/rules/RequiresGeodeHome.java     |    5 +-
 .../geode/distributed/LocatorLauncher.java      |  248 +--
 .../geode/distributed/ServerLauncher.java       |  266 ++-
 .../geode/internal/cache/DistributedRegion.java |   49 +
 .../sockets/ClientProtocolMessageHandler.java   |    3 -
 .../GenericProtocolServerConnection.java        |    8 +-
 .../tier/sockets/MessageExecutionContext.java   |   14 +-
 .../cache/tier/sockets/ServerConnection.java    |    1 -
 .../tier/sockets/ServerConnectionFactory.java   |   15 +-
 .../geode/management/GemFireProperties.java     |   43 +-
 .../cli/CommandProcessingException.java         |    1 -
 .../geode/management/cli/CommandService.java    |   47 +-
 .../management/internal/MBeanJMXAdapter.java    |  199 +-
 .../management/internal/ManagementAgent.java    |   70 +-
 .../internal/SystemManagementService.java       |    5 +-
 .../internal/beans/MBeanAggregator.java         |    7 +-
 .../internal/beans/ManagementAdapter.java       |   46 +-
 .../internal/beans/stats/VMStatsMonitor.java    |   14 +-
 .../geode/management/internal/cli/CliUtil.java  |  107 +-
 .../internal/cli/CommandResponseBuilder.java    |   27 +-
 .../geode/management/internal/cli/Launcher.java |   11 +-
 .../management/internal/cli/LogWrapper.java     |   44 +-
 .../commands/AlterOfflineDiskStoreCommand.java  |  141 ++
 .../cli/commands/AlterRegionCommand.java        |  229 +++
 .../cli/commands/AlterRuntimeConfigCommand.java |  246 +++
 .../cli/commands/BackupDiskStoreCommand.java    |  142 ++
 .../cli/commands/ChangeLogLevelCommand.java     |  163 ++
 .../commands/ClearDefinedIndexesCommand.java    |   40 +
 .../cli/commands/CloseDurableCQsCommand.java    |   83 +
 .../cli/commands/CloseDurableClientCommand.java |   77 +
 .../cli/commands/CompactDiskStoreCommand.java   |  185 ++
 .../CompactOfflineDiskStoreCommand.java         |  176 ++
 .../internal/cli/commands/ConfigCommands.java   |  490 -----
 .../cli/commands/ConfigurePDXCommand.java       |  138 ++
 .../internal/cli/commands/ConnectCommand.java   |   68 +-
 .../commands/CountDurableCQEventsCommand.java   |   88 +
 .../CreateAlterDestroyRegionCommands.java       | 1146 -----------
 .../commands/CreateAsyncEventQueueCommand.java  |  171 ++
 .../commands/CreateDefinedIndexesCommand.java   |  152 ++
 .../cli/commands/CreateDiskStoreCommand.java    |  166 ++
 .../cli/commands/CreateIndexCommand.java        |  194 ++
 .../cli/commands/CreateRegionCommand.java       |  725 +++++++
 .../cli/commands/DefineIndexCommand.java        |   95 +
 .../internal/cli/commands/DeployCommand.java    |  190 ++
 .../internal/cli/commands/DeployCommands.java   |  336 ---
 .../cli/commands/DescribeConfigCommand.java     |  153 ++
 .../cli/commands/DescribeDiskStoreCommand.java  |  177 ++
 .../cli/commands/DescribeMemberCommand.java     |  132 ++
 .../DescribeOfflineDiskStoreCommand.java        |   75 +
 .../cli/commands/DescribeRegionCommand.java     |  372 ++++
 .../cli/commands/DestroyDiskStoreCommand.java   |  106 +
 .../cli/commands/DestroyFunctionCommand.java    |  163 ++
 .../cli/commands/DestroyIndexCommand.java       |  174 ++
 .../cli/commands/DestroyRegionCommand.java      |  222 ++
 .../cli/commands/DiskStoreCommands.java         | 1433 -------------
 .../cli/commands/DiskStoreCommandsUtils.java    |   60 +
 .../cli/commands/DurableClientCommands.java     |  420 ----
 .../DurableClientCommandsResultBuilder.java     |  164 ++
 .../cli/commands/ExecuteFunctionCommand.java    |  329 +++
 .../cli/commands/ExportConfigCommand.java       |  159 ++
 .../commands/ExportOfflineDiskStoreCommand.java |   68 +
 .../cli/commands/ExportStackTraceCommand.java   |  157 ++
 .../internal/cli/commands/FunctionCommands.java |  537 -----
 .../internal/cli/commands/GCCommand.java        |  131 ++
 .../internal/cli/commands/GfshHelpCommand.java  |   45 +
 .../internal/cli/commands/GfshHelpCommands.java |   55 -
 .../internal/cli/commands/GfshHintCommand.java  |   42 +
 .../internal/cli/commands/IndexCommands.java    |  668 ------
 .../internal/cli/commands/IndexDefinition.java  |   27 +
 .../commands/ListAsyncEventQueuesCommand.java   |  118 ++
 .../cli/commands/ListDeployedCommand.java       |  102 +
 .../cli/commands/ListDiskStoresCommand.java     |  112 +
 .../commands/ListDurableClientCQsCommand.java   |  121 ++
 .../cli/commands/ListFunctionCommand.java       |  101 +
 .../internal/cli/commands/ListIndexCommand.java |  158 ++
 .../cli/commands/ListMemberCommand.java         |   77 +
 .../cli/commands/ListRegionCommand.java         |  113 +
 .../internal/cli/commands/MemberCommands.java   |  195 --
 .../cli/commands/MiscellaneousCommands.java     | 1926 ------------------
 .../internal/cli/commands/NetstatCommand.java   |  212 ++
 .../internal/cli/commands/PDXCommands.java      |  195 --
 .../internal/cli/commands/PDXRenameCommand.java |   81 +
 .../internal/cli/commands/QueueCommands.java    |  259 ---
 .../internal/cli/commands/RegionCommands.java   |  474 -----
 .../cli/commands/RegionCommandsUtils.java       |   78 +
 .../commands/RevokeMissingDiskStoreCommand.java |   61 +
 .../internal/cli/commands/ShellCommands.java    |   35 +-
 .../cli/commands/ShowDeadlockCommand.java       |   92 +
 .../internal/cli/commands/ShowLogCommand.java   |  102 +
 .../cli/commands/ShowMetricsCommand.java        | 1083 ++++++++++
 .../commands/ShowMissingDiskStoreCommand.java   |  149 ++
 .../internal/cli/commands/ShutdownCommand.java  |  205 ++
 .../internal/cli/commands/StartMemberUtils.java |   24 +-
 .../StatusClusterConfigServiceCommand.java      |   82 +
 .../internal/cli/commands/StatusCommands.java   |   82 -
 .../internal/cli/commands/UndeployCommand.java  |  114 ++
 .../UpgradeOfflineDiskStoreCommand.java         |  177 ++
 .../cli/commands/ValidateDiskStoreCommand.java  |  104 +
 .../internal/cli/converters/HelpConverter.java  |   25 +-
 .../cli/converters/MemberGroupConverter.java    |   11 +-
 .../internal/cli/domain/DataCommandResult.java  |   14 +-
 .../functions/CreateDefinedIndexesFunction.java |    3 +-
 .../cli/functions/DataCommandFunction.java      |   10 -
 .../cli/functions/RegionCreateFunction.java     |   23 +-
 .../internal/cli/i18n/CliStrings.java           |   54 +-
 .../cli/remote/CommandExecutionContext.java     |   15 +-
 .../internal/cli/result/AbstractResultData.java |   49 +-
 .../internal/cli/result/CommandResult.java      |   96 +-
 .../cli/result/CompositeResultData.java         |   19 +-
 .../internal/cli/result/ResultBuilder.java      |   17 +-
 .../internal/cli/result/ResultData.java         |    6 +-
 .../internal/cli/result/TableBuilder.java       |    9 +-
 .../management/internal/cli/shell/Gfsh.java     |   84 +-
 .../cli/shell/GfshExecutionStrategy.java        |   11 -
 .../internal/cli/shell/JmxOperationInvoker.java |   27 +-
 .../cli/shell/unsafe/GfshSignalHandler.java     |   13 +-
 .../internal/cli/util/ReadWriteFile.java        |   78 +-
 .../configuration/domain/CacheElement.java      |   20 +-
 .../configuration/domain/XmlEntity.java         |   50 +-
 .../messages/ConfigurationRequest.java          |   18 +-
 .../internal/configuration/utils/XmlUtils.java  |   60 +-
 .../controllers/ConfigCommandsController.java   |   17 +-
 .../web/controllers/DataCommandsController.java |    7 +-
 .../controllers/DeployCommandsController.java   |   24 +-
 .../DiskStoreCommandsController.java            |   18 +-
 .../DurableClientCommandsController.java        |   15 +-
 .../controllers/FunctionCommandsController.java |   13 +-
 .../controllers/IndexCommandsController.java    |   13 +-
 .../controllers/MemberCommandsController.java   |   23 +-
 .../MiscellaneousCommandsController.java        |    9 +-
 .../web/controllers/PdxCommandsController.java  |   10 +-
 .../controllers/QueueCommandsController.java    |   10 +-
 .../controllers/RegionCommandsController.java   |   25 +-
 .../controllers/ShellCommandsController.java    |   63 +-
 .../geode/redis/internal/RegionProvider.java    |   29 +-
 .../geode/security/NoOpStreamAuthenticator.java |   46 -
 .../geode/security/NoOpStreamAuthorizer.java    |   26 -
 .../geode/security/StreamAuthenticator.java     |   56 -
 .../apache/geode/security/StreamAuthorizer.java |   19 -
 .../geode/security/server/Authenticator.java    |   59 +
 .../geode/security/server/Authorizer.java       |   21 +
 .../security/server/NoOpAuthenticator.java      |   48 +
 .../geode/security/server/NoOpAuthorizer.java   |   27 +
 .../apache/geode/security/server/package.html   |   45 +
 ...rg.apache.geode.security.StreamAuthenticator |    1 -
 ...g.apache.geode.security.server.Authenticator |    1 +
 .../geode/cache30/ClientServerCCEDUnitTest.java |  129 +-
 .../LauncherIntegrationTestCase.java            |   12 +-
 .../LocatorLauncherRemoteIntegrationTest.java   |    4 +-
 .../ServerLauncherRemoteIntegrationTest.java    |    4 +-
 .../geode/distributed/ServerLauncherTest.java   |    5 +-
 .../internal/cache/ha/Bug48571DUnitTest.java    |   72 +-
 .../GenericProtocolServerConnectionTest.java    |    4 +-
 .../commands/AlterRegionCommandDUnitTest.java   |  639 ++++++
 .../cli/commands/ConfigCommandsDUnitTest.java   |   38 +-
 ...eateAlterDestroyRegionCommandsDUnitTest.java | 1220 +----------
 .../CreateAlterDestroyRegionCommandsTest.java   |   53 -
 .../commands/CreateRegionCommandDUnitTest.java  |  304 +++
 .../cli/commands/CreateRegionCommandTest.java   |   58 +
 .../cli/commands/DeployWithGroupsDUnitTest.java |    2 +-
 .../commands/DestroyRegionCommandDUnitTest.java |  388 ++++
 .../commands/DiskStoreCommandsDUnitTest.java    |   61 +-
 .../commands/DiskStoreCommandsJUnitTest.java    |  112 +-
 .../cli/commands/FunctionCommandsDUnitTest.java |   60 +-
 .../commands/GemfireDataCommandsDUnitTest.java  |   48 +-
 ...WithCacheLoaderDuringCacheMissDUnitTest.java |   46 +-
 .../commands/GfshCommandIntegrationTest.java    |   49 +
 .../cli/commands/IndexCommandsJUnitTest.java    |  223 --
 ...stAndDescribeDiskStoreCommandsDUnitTest.java |   40 +-
 .../cli/commands/ListIndexCommandDUnitTest.java |   45 +-
 .../cli/commands/ListIndexCommandJUnitTest.java |  223 ++
 .../cli/commands/LogLevelInterceptorTest.java   |   21 +-
 .../MiscellaneousCommandsDUnitTest.java         |  157 +-
 .../cli/commands/QueueCommandsDUnitTest.java    |   38 +-
 .../RebalanceCommandDistributedTest.java        |   15 +-
 .../cli/commands/ShellCommandsDUnitTest.java    |   29 +-
 .../cli/commands/ShowDeadlockDUnitTest.java     |  206 +-
 .../cli/commands/ShowMetricsDUnitTest.java      |   51 +-
 .../cli/commands/ShowStackTraceDUnitTest.java   |   29 +-
 .../cli/commands/StartMemberUtilsTest.java      |   91 +
 .../GfshStatusCommandsIntegrationTest.java      |   34 +-
 .../cli/help/HelperIntegrationTest.java         |   73 +-
 .../security/GfshCommandsSecurityTest.java      |    4 +-
 .../internal/security/TestCommand.java          |   22 +-
 .../dunit/rules/GfshShellConnectionRule.java    |   13 +-
 .../cli/commands/ClientCommandsTestUtils.java   |    1 -
 .../DescribeClientCommandDUnitTest.java         |    7 +-
 .../DurableClientCommandsDUnitTest.java         |  280 +--
 .../commands/ListClientCommandDUnitTest.java    |    7 +-
 .../running/firewalls_multisite.html.md.erb     |   87 -
 .../running/firewalls_ports.html.md.erb         |   72 +-
 .../implementing_authorization.html.md.erb      |    2 +
 geode-junit/build.gradle                        |    1 +
 .../concurrent/FileBasedCountDownLatch.java     |   87 +
 .../concurrent/FileBasedCountDownLatchTest.java |   37 +
 .../cli/LuceneIndexCommandsDUnitTest.java       |    2 +-
 .../protocol/protobuf/ProtobufOpsProcessor.java |    2 -
 .../protobuf/ProtobufSimpleAuthenticator.java   |   11 +-
 .../protobuf/ProtobufSimpleAuthorizer.java      |   12 +-
 .../protobuf/ProtobufStreamProcessor.java       |    1 -
 ...rg.apache.geode.security.StreamAuthenticator |    1 -
 ...g.apache.geode.security.server.Authenticator |    1 +
 .../ProtobufSimpleAuthenticatorJUnitTest.java   |    7 +-
 .../protobuf/ProtobufStreamProcessorTest.java   |    4 +-
 .../GetAllRequestOperationHandlerJUnitTest.java |   12 +-
 ...onNamesRequestOperationHandlerJUnitTest.java |    6 +-
 ...tRegionRequestOperationHandlerJUnitTest.java |    6 +-
 .../GetRequestOperationHandlerJUnitTest.java    |   12 +-
 .../PutAllRequestOperationHandlerJUnitTest.java |    8 +-
 .../PutRequestOperationHandlerJUnitTest.java    |   10 +-
 .../RemoveRequestOperationHandlerJUnitTest.java |   10 +-
 .../ClusterConfigurationDUnitTest.java          |   30 +-
 .../ConnectCommandWithHttpAndSSLDUnitTest.java  |   31 +-
 .../cli/commands/ConnectCommandWithSSLTest.java |   13 +-
 ...RebalanceCommandOverHttpDistributedTest.java |    8 +-
 gradle/test.gradle                              |   11 +-
 224 files changed, 13805 insertions(+), 12590 deletions(-)
----------------------------------------------------------------------



[44/47] geode git commit: GEODE-3249 Validate internal client/server messages

Posted by ds...@apache.org.
GEODE-3249 Validate internal client/server messages

The addition of USER_CREDENTIAL_MESSAGE in ServerConnection.isInternalMessage
caused problems for the c++ client.  This message class does require
credentials and shouldn't be included in the set of internal messages.


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

Branch: refs/heads/feature/GEODE-3543
Commit: f2492bf0abdc662cc080f1e2c0f17257e05604a3
Parents: 17662cd
Author: Bruce Schuchardt <bs...@pivotal.io>
Authored: Wed Aug 30 13:50:48 2017 -0700
Committer: Bruce Schuchardt <bs...@pivotal.io>
Committed: Wed Aug 30 13:52:50 2017 -0700

----------------------------------------------------------------------
 .../apache/geode/internal/cache/tier/sockets/ServerConnection.java  | 1 -
 1 file changed, 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/f2492bf0/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java
index 6f56e85..1925898 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnection.java
@@ -1097,7 +1097,6 @@ public abstract class ServerConnection implements Runnable {
   public boolean isInternalMessage(Message message, boolean allowOldInternalMessages) {
     int messageType = message.getMessageType();
     boolean isInternalMessage = messageType == MessageType.PING
-        || messageType == MessageType.USER_CREDENTIAL_MESSAGE
         || messageType == MessageType.REQUEST_EVENT_VALUE || messageType == MessageType.MAKE_PRIMARY
         || messageType == MessageType.REMOVE_USER_AUTH || messageType == MessageType.CLIENT_READY
         || messageType == MessageType.SIZE || messageType == MessageType.TX_FAILOVER


[12/47] geode git commit: GEODE-3436: Restore refactoring of CreateAlterDestroyRegionCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
new file mode 100644
index 0000000..30e8728
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
@@ -0,0 +1,641 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.RegionAttributes;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.asyncqueue.AsyncEvent;
+import org.apache.geode.cache.asyncqueue.AsyncEventListener;
+import org.apache.geode.cache.wan.GatewaySenderFactory;
+import org.apache.geode.internal.ClassBuilder;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CommandResult;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
+
+@Category(DistributedTest.class)
+public class AlterRegionCommandDUnitTest extends CliCommandTestBase {
+  private final String alterRegionName = "testAlterRegionRegion";
+  private final String alterAsyncEventQueueId1 = "testAlterRegionQueue1";
+  private final String alterAsyncEventQueueId2 = "testAlterRegionQueue2";
+  private final String alterAsyncEventQueueId3 = "testAlterRegionQueue3";
+  private final String alterGatewaySenderId1 = "testAlterRegionSender1";
+  private final String alterGatewaySenderId2 = "testAlterRegionSender2";
+  private final String alterGatewaySenderId3 = "testAlterRegionSender3";
+  private VM alterVm1;
+  private String alterVm1Name;
+  private VM alterVm2;
+  private String alterVm2Name;
+
+  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
+
+  @Ignore("bug51924")
+  @Test
+  public void testAlterRegion() throws IOException {
+    setUpJmxManagerOnVm0ThenConnect(null);
+
+    CommandResult cmdResult = executeCommand(CliStrings.LIST_REGION);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    assertTrue(commandResultToString(cmdResult).contains("No Regions Found"));
+
+    Host.getHost(0).getVM(0).invoke(() -> {
+      Cache cache = getCache();
+      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+          .create(alterRegionName);
+    });
+
+    this.alterVm1 = Host.getHost(0).getVM(1);
+    this.alterVm1Name = "VM" + this.alterVm1.getPid();
+    this.alterVm1.invoke(() -> {
+      Properties localProps = new Properties();
+      localProps.setProperty(NAME, alterVm1Name);
+      localProps.setProperty(GROUPS, "Group1");
+      getSystem(localProps);
+      Cache cache = getCache();
+
+      // Setup queues and gateway senders to be used by all tests
+      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+          .create(alterRegionName);
+      AsyncEventListener listener = new AsyncEventListener() {
+        @Override
+        public void close() {
+          // Nothing to do
+        }
+
+        @Override
+        public boolean processEvents(List<AsyncEvent> events) {
+          return true;
+        }
+      };
+      cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId1, listener);
+      cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId2, listener);
+      cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId3, listener);
+
+      GatewaySenderFactory gatewaySenderFactory = cache.createGatewaySenderFactory();
+      gatewaySenderFactory.setManualStart(true);
+      gatewaySenderFactory.create(alterGatewaySenderId1, 2);
+      gatewaySenderFactory.create(alterGatewaySenderId2, 3);
+      gatewaySenderFactory.create(alterGatewaySenderId3, 4);
+    });
+
+    this.alterVm2 = Host.getHost(0).getVM(2);
+    this.alterVm2Name = "VM" + this.alterVm2.getPid();
+    this.alterVm2.invoke(() -> {
+      Properties localProps = new Properties();
+      localProps.setProperty(NAME, alterVm2Name);
+      localProps.setProperty(GROUPS, "Group1,Group2");
+      getSystem(localProps);
+      Cache cache = getCache();
+
+      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+          .create(alterRegionName);
+    });
+
+    deployJarFilesForRegionAlter();
+    regionAlterGroupTest();
+    regionAlterSetAllTest();
+    regionAlterNoChangeTest();
+    regionAlterSetDefaultsTest();
+    regionAlterManipulatePlugInsTest();
+
+    this.alterVm1.invoke(() -> {
+      getCache().getRegion(alterRegionName).destroyRegion();
+    });
+  }
+
+  @Category(FlakyTest.class) // GEODE-3018
+  @Test
+  public void testAlterRegionResetCacheListeners() throws IOException {
+    setUpJmxManagerOnVm0ThenConnect(null);
+
+    CommandResult cmdResult = executeCommand(CliStrings.LIST_REGION);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    assertTrue(commandResultToString(cmdResult).contains("No Regions Found"));
+
+    Host.getHost(0).getVM(0).invoke(() -> {
+      Cache cache = getCache();
+      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+          .create(alterRegionName);
+    });
+
+    this.alterVm1 = Host.getHost(0).getVM(1);
+    this.alterVm1Name = "VM" + this.alterVm1.getPid();
+    this.alterVm1.invoke(() -> {
+      Properties localProps = new Properties();
+      localProps.setProperty(NAME, alterVm1Name);
+      localProps.setProperty(GROUPS, "Group1");
+      getSystem(localProps);
+      Cache cache = getCache();
+
+      // Setup queues and gateway senders to be used by all tests
+      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+          .create(alterRegionName);
+    });
+
+    this.alterVm2 = Host.getHost(0).getVM(2);
+    this.alterVm2Name = "VM" + this.alterVm2.getPid();
+    this.alterVm2.invoke(() -> {
+      Properties localProps = new Properties();
+      localProps.setProperty(NAME, alterVm2Name);
+      localProps.setProperty(GROUPS, "Group1,Group2");
+      getSystem(localProps);
+      Cache cache = getCache();
+
+      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+          .create(alterRegionName);
+    });
+
+    deployJarFilesForRegionAlter();
+
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerA,com.cadrdunit.RegionAlterCacheListenerB,com.cadrdunit.RegionAlterCacheListenerC");
+
+    cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    String stringResult = commandResultToString(cmdResult);
+
+    assertEquals(5, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm1.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(3, attributes.getCacheListeners().length);
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+          attributes.getCacheListeners()[0].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
+          attributes.getCacheListeners()[1].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
+          attributes.getCacheListeners()[2].getClass().getName());
+    });
+
+    // Add 1 back to each of the sets
+    commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER, "''");
+    cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    stringResult = commandResultToString(cmdResult);
+    assertEquals(4, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm1.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(0, attributes.getCacheListeners().length);
+    });
+  }
+
+  private void deployJarFilesForRegionAlter() throws IOException {
+    ClassBuilder classBuilder = new ClassBuilder();
+    final File jarFile1 = new File(new File(".").getAbsolutePath(), "testAlterRegion1.jar");
+    this.filesToBeDeleted.add(jarFile1.getAbsolutePath());
+    final File jarFile2 = new File(new File(".").getAbsolutePath(), "testAlterRegion2.jar");
+    this.filesToBeDeleted.add(jarFile2.getAbsolutePath());
+    final File jarFile3 = new File(new File(".").getAbsolutePath(), "testAlterRegion3.jar");
+    this.filesToBeDeleted.add(jarFile3.getAbsolutePath());
+    final File jarFile4 = new File(new File(".").getAbsolutePath(), "testAlterRegion4.jar");
+    this.filesToBeDeleted.add(jarFile4.getAbsolutePath());
+    final File jarFile5 = new File(new File(".").getAbsolutePath(), "testAlterRegion5.jar");
+    this.filesToBeDeleted.add(jarFile5.getAbsolutePath());
+
+    byte[] jarBytes =
+        classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerA",
+            "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
+                + "public class RegionAlterCacheListenerA extends CacheListenerAdapter {}");
+    writeJarBytesToFile(jarFile1, jarBytes);
+    CommandResult cmdResult = executeCommand("deploy --jar=testAlterRegion1.jar");
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerB",
+        "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
+            + "public class RegionAlterCacheListenerB extends CacheListenerAdapter {}");
+    writeJarBytesToFile(jarFile2, jarBytes);
+    cmdResult = executeCommand("deploy --jar=testAlterRegion2.jar");
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerC",
+        "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
+            + "public class RegionAlterCacheListenerC extends CacheListenerAdapter {}");
+    writeJarBytesToFile(jarFile3, jarBytes);
+    cmdResult = executeCommand("deploy --jar=testAlterRegion3.jar");
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheLoader",
+        "package com.cadrdunit;" + "import org.apache.geode.cache.CacheLoader;"
+            + "import org.apache.geode.cache.CacheLoaderException;"
+            + "import org.apache.geode.cache.LoaderHelper;"
+            + "public class RegionAlterCacheLoader implements CacheLoader {"
+            + "public void close() {}"
+            + "public Object load(LoaderHelper helper) throws CacheLoaderException {return null;}}");
+    writeJarBytesToFile(jarFile4, jarBytes);
+    cmdResult = executeCommand("deploy --jar=testAlterRegion4.jar");
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheWriter",
+        "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheWriterAdapter;"
+            + "public class RegionAlterCacheWriter extends CacheWriterAdapter {}");
+    writeJarBytesToFile(jarFile5, jarBytes);
+    cmdResult = executeCommand("deploy --jar=testAlterRegion5.jar");
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+  }
+
+  private void regionAlterGroupTest() {
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "5764");
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    String stringResult = commandResultToString(cmdResult);
+    assertEquals(4, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm1.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
+    });
+
+    this.alterVm2.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
+    });
+
+    commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.GROUP, "Group2");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "6963");
+    cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    stringResult = commandResultToString(cmdResult);
+    assertEquals(3, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertFalse(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm1.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
+    });
+
+    this.alterVm2.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(6963, attributes.getEvictionAttributes().getMaximum());
+    });
+  }
+
+  private void regionAlterSetAllTest() {
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "35464");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED, "true");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId1);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME, "3453");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
+        "DESTROY");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE, "7563");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION, "DESTROY");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerA");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELOADER,
+        "com.cadrdunit.RegionAlterCacheLoader");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHEWRITER,
+        "com.cadrdunit.RegionAlterCacheWriter");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId1);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME, "6234");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION,
+        "DESTROY");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, "4562");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION, "DESTROY");
+
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    String stringResult = commandResultToString(cmdResult);
+    assertEquals(5, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        "Manager.*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm1.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(35464, attributes.getEvictionAttributes().getMaximum());
+      assertEquals(3453, attributes.getEntryIdleTimeout().getTimeout());
+      assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
+      assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
+      assertTrue(attributes.getEntryTimeToLive().getAction().isDestroy());
+      assertEquals(6234, attributes.getRegionIdleTimeout().getTimeout());
+      assertTrue(attributes.getRegionIdleTimeout().getAction().isDestroy());
+      assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
+      assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
+      assertEquals(1, attributes.getAsyncEventQueueIds().size());
+      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
+      assertEquals(1, attributes.getGatewaySenderIds().size());
+      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
+      assertEquals(1, attributes.getCacheListeners().length);
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+          attributes.getCacheListeners()[0].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheWriter",
+          attributes.getCacheWriter().getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheLoader",
+          attributes.getCacheLoader().getClass().getName());
+    });
+  }
+
+  private void regionAlterNoChangeTest() {
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED, "true");
+
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    String stringResult = commandResultToString(cmdResult);
+    assertEquals(4, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm2.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(35464, attributes.getEvictionAttributes().getMaximum());
+      assertEquals(3453, attributes.getEntryIdleTimeout().getTimeout());
+      assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
+      assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
+      assertTrue(attributes.getEntryTimeToLive().getAction().isDestroy());
+      assertEquals(6234, attributes.getRegionIdleTimeout().getTimeout());
+      assertTrue(attributes.getRegionIdleTimeout().getAction().isDestroy());
+      assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
+      assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
+      assertEquals(1, attributes.getAsyncEventQueueIds().size());
+      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
+      assertEquals(1, attributes.getGatewaySenderIds().size());
+      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
+      assertEquals(1, attributes.getCacheListeners().length);
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+          attributes.getCacheListeners()[0].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheWriter",
+          attributes.getCacheWriter().getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheLoader",
+          attributes.getCacheLoader().getClass().getName());
+    });
+  }
+
+  private void regionAlterSetDefaultsTest() {
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELOADER);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHEWRITER);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION);
+
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    String stringResult = commandResultToString(cmdResult);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    assertEquals(4, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm1.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(0, attributes.getEvictionAttributes().getMaximum());
+      assertEquals(0, attributes.getEntryIdleTimeout().getTimeout());
+      assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
+      assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
+      assertTrue(attributes.getEntryTimeToLive().getAction().isInvalidate());
+      assertEquals(0, attributes.getRegionIdleTimeout().getTimeout());
+      assertTrue(attributes.getRegionIdleTimeout().getAction().isInvalidate());
+      assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
+      assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
+      assertEquals(0, attributes.getAsyncEventQueueIds().size());
+      assertEquals(0, attributes.getGatewaySenderIds().size());
+      assertEquals(0, attributes.getCacheListeners().length);
+    });
+  }
+
+  private void regionAlterManipulatePlugInsTest() {
+
+    // Start out by putting 3 entries into each of the plug-in sets
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId1);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId2);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId3);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId1);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId2);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId3);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerA");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerB");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerC");
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    String stringResult = commandResultToString(cmdResult);
+
+    assertEquals(4, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm1.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(3, attributes.getAsyncEventQueueIds().size());
+      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
+      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId2));
+      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId3));
+      assertEquals(3, attributes.getGatewaySenderIds().size());
+      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
+      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId2));
+      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId3));
+      assertEquals(3, attributes.getCacheListeners().length);
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+          attributes.getCacheListeners()[0].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
+          attributes.getCacheListeners()[1].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
+          attributes.getCacheListeners()[2].getClass().getName());
+    });
+
+    // Now take 1 entry out of each of the sets
+    commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId1);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId2);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId1);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId3);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerB");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerC");
+    cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    stringResult = commandResultToString(cmdResult);
+    assertEquals(4, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm2.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(2, attributes.getAsyncEventQueueIds().size());
+      Iterator iterator = attributes.getAsyncEventQueueIds().iterator();
+      assertEquals(alterAsyncEventQueueId1, iterator.next());
+      assertEquals(alterAsyncEventQueueId2, iterator.next());
+      assertEquals(2, attributes.getGatewaySenderIds().size());
+      iterator = attributes.getGatewaySenderIds().iterator();
+      assertEquals(alterGatewaySenderId1, iterator.next());
+      assertEquals(alterGatewaySenderId3, iterator.next());
+      assertEquals(2, attributes.getCacheListeners().length);
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
+          attributes.getCacheListeners()[0].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
+          attributes.getCacheListeners()[1].getClass().getName());
+    });
+
+    // Add 1 back to each of the sets
+    commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId1);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId2);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+        this.alterAsyncEventQueueId3);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId1);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId3);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+        this.alterGatewaySenderId2);
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerB");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerC");
+    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+        "com.cadrdunit.RegionAlterCacheListenerA");
+    cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+    stringResult = commandResultToString(cmdResult);
+    assertEquals(4, countLinesInString(stringResult, false));
+    assertEquals(false, stringResult.contains("ERROR"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+    assertTrue(stringContainsLine(stringResult,
+        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+    this.alterVm1.invoke(() -> {
+      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+      assertEquals(3, attributes.getAsyncEventQueueIds().size());
+      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
+      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId2));
+      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId3));
+      assertEquals(3, attributes.getGatewaySenderIds().size());
+      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
+      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId3));
+      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId2));
+      assertEquals(3, attributes.getCacheListeners().length);
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
+          attributes.getCacheListeners()[0].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
+          attributes.getCacheListeners()[1].getClass().getName());
+      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+          attributes.getCacheListeners()[2].getClass().getName());
+    });
+  }
+
+  private void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException {
+    final OutputStream outStream = new FileOutputStream(jarFile);
+    outStream.write(jarBytes);
+    outStream.flush();
+    outStream.close();
+  }
+}


[35/47] geode git commit: GEODE-3404: add FlakyTest category to entire test class

Posted by ds...@apache.org.
GEODE-3404: add FlakyTest category to entire test class


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

Branch: refs/heads/feature/GEODE-3543
Commit: c287d987e153c86b8e2f7ed63138957e89c3fdf7
Parents: 00a0490
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Aug 28 14:51:30 2017 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Tue Aug 29 14:32:53 2017 -0700

----------------------------------------------------------------------
 .../DurableClientCommandsDUnitTest.java         | 279 ++++++++++---------
 1 file changed, 147 insertions(+), 132 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/c287d987/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
index e15d2cc..ef3b4a7 100644
--- a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
+++ b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
@@ -14,15 +14,38 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import org.apache.geode.cache.*;
+import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_ID;
+import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_TIMEOUT;
+import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.DistributedTestUtils.getDUnitLocatorPort;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
+
+import java.util.Properties;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.AttributesFactory;
+import org.apache.geode.cache.CacheException;
+import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.Scope;
 import org.apache.geode.cache.client.ClientCache;
 import org.apache.geode.cache.client.ClientCacheFactory;
-import org.apache.geode.cache.query.*;
+import org.apache.geode.cache.query.CqAttributesFactory;
+import org.apache.geode.cache.query.CqException;
+import org.apache.geode.cache.query.CqExistsException;
+import org.apache.geode.cache.query.QueryService;
+import org.apache.geode.cache.query.RegionNotFoundException;
 import org.apache.geode.cache.query.data.Portfolio;
 import org.apache.geode.cache.server.CacheServer;
 import org.apache.geode.cache30.CacheSerializableRunnable;
 import org.apache.geode.internal.cache.DistributedRegion;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.internal.cache.InternalCache;
 import org.apache.geode.internal.cache.PartitionedRegion;
 import org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil;
 import org.apache.geode.management.cli.Result.Status;
@@ -31,29 +54,26 @@ import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.SerializableCallable;
+import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.util.Properties;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Assert.assertTrue;
-import static org.apache.geode.test.dunit.DistributedTestUtils.getDUnitLocatorPort;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
-
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1705, GEODE-3404, GEODE-3359
 public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
-  final String regionName = "stocks";
-  final String cq1 = "cq1";
-  final String cq2 = "cq2";
-  final String cq3 = "cq3";
-  final String clientName = "dc1";
+  private static final String REGION_NAME = "stocks";
+  private static final String CQ1 = "cq1";
+  private static final String CQ2 = "cq2";
+  private static final String CQ3 = "cq3";
+  private static final String CLIENT_NAME = "dc1";
+
+  @Override
+  public final void postTearDownCacheTestCase() throws Exception {
+    Host.getHost(0).getVM(0).invoke(() -> CacheServerTestUtil.closeCache());
+    Host.getHost(0).getVM(1).invoke(() -> CacheServerTestUtil.closeCache());
+    Host.getHost(0).getVM(2).invoke(() -> CacheServerTestUtil.closeCache());
+  }
 
   @Test
   public void testListDurableClientCqs() throws Exception {
@@ -61,23 +81,23 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     setupCqs();
 
     CommandStringBuilder csb = new CommandStringBuilder(CliStrings.LIST_DURABLE_CQS);
-    csb.addOption(CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, clientName);
+    csb.addOption(CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, CLIENT_NAME);
     String commandString = csb.toString();
     writeToLog("Command String :\n ", commandString);
     CommandResult commandResult = executeCommand(commandString);
     String resultAsString = commandResultToString(commandResult);
     writeToLog("Command Result :\n", resultAsString);
     assertTrue(Status.OK.equals(commandResult.getStatus()));
-    assertTrue(resultAsString.contains(cq1));
-    assertTrue(resultAsString.contains(cq2));
-    assertTrue(resultAsString.contains(cq3));
+    assertTrue(resultAsString.contains(CQ1));
+    assertTrue(resultAsString.contains(CQ2));
+    assertTrue(resultAsString.contains(CQ3));
 
-    closeCq(cq1);
-    closeCq(cq2);
-    closeCq(cq3);
+    closeCq(CQ1);
+    closeCq(CQ2);
+    closeCq(CQ3);
 
     csb = new CommandStringBuilder(CliStrings.LIST_DURABLE_CQS);
-    csb.addOption(CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, clientName);
+    csb.addOption(CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, CLIENT_NAME);
     commandString = csb.toString();
     writeToLog("Command String :\n ", commandString);
     commandResult = executeCommand(commandString);
@@ -85,7 +105,7 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     writeToLog("Command Result :\n", resultAsString);
     assertTrue(Status.ERROR.equals(commandResult.getStatus()));
     String errorMessage =
-        CliStrings.format(CliStrings.LIST_DURABLE_CQS__NO__CQS__FOR__CLIENT, clientName);
+        CliStrings.format(CliStrings.LIST_DURABLE_CQS__NO__CQS__FOR__CLIENT, CLIENT_NAME);
     assertTrue(resultAsString.contains(errorMessage));
   }
 
@@ -96,17 +116,20 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     closeDurableClient();
 
     CommandStringBuilder csb = new CommandStringBuilder(CliStrings.CLOSE_DURABLE_CLIENTS);
-    csb.addOption(CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, clientName);
+    csb.addOption(CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, CLIENT_NAME);
     String commandString = csb.toString();
+
     long giveUpTime = System.currentTimeMillis() + 20000;
     CommandResult commandResult = null;
     String resultAsString = null;
+
     do {
       writeToLog("Command String : ", commandString);
       commandResult = executeCommand(commandString);
       resultAsString = commandResultToString(commandResult);
     } while (resultAsString.contains("Cannot close a running durable client")
         && giveUpTime > System.currentTimeMillis());
+
     writeToLog("Command Result :\n", resultAsString);
     assertTrue(Status.OK.equals(commandResult.getStatus()));
 
@@ -116,11 +139,10 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     resultAsString = commandResultToString(commandResult);
     writeToLog("Command Result :\n", resultAsString);
     assertTrue(Status.ERROR.equals(commandResult.getStatus()));
-    String errorMessage = CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, clientName);
+    String errorMessage = CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, CLIENT_NAME);
     assertTrue(resultAsString.contains(errorMessage));
   }
 
-  @Category(FlakyTest.class) // GEODE-1705
   @Test
   public void testCloseDurableCQ() throws Exception {
     setupSystem();
@@ -129,8 +151,8 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     closeDurableClient();
 
     CommandStringBuilder csb = new CommandStringBuilder(CliStrings.CLOSE_DURABLE_CQS);
-    csb.addOption(CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID, clientName);
-    csb.addOption(CliStrings.CLOSE_DURABLE_CQS__NAME, cq1);
+    csb.addOption(CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID, CLIENT_NAME);
+    csb.addOption(CliStrings.CLOSE_DURABLE_CQS__NAME, CQ1);
     String commandString = csb.toString();
     writeToLog("Command String : ", commandString);
     CommandResult commandResult = executeCommand(commandString);
@@ -139,8 +161,8 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     assertTrue(Status.OK.equals(commandResult.getStatus()));
 
     csb = new CommandStringBuilder(CliStrings.CLOSE_DURABLE_CQS);
-    csb.addOption(CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID, clientName);
-    csb.addOption(CliStrings.CLOSE_DURABLE_CQS__NAME, cq1);
+    csb.addOption(CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID, CLIENT_NAME);
+    csb.addOption(CliStrings.CLOSE_DURABLE_CQS__NAME, CQ1);
     commandString = csb.toString();
     writeToLog("Command String : ", commandString);
     commandResult = executeCommand(commandString);
@@ -154,10 +176,10 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
   public void testCountSubscriptionQueueSize() throws Exception {
     setupSystem();
     setupCqs();
-    doPuts(regionName, Host.getHost(0).getVM(1));
+    doPuts(REGION_NAME, Host.getHost(0).getVM(1));
 
     CommandStringBuilder csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
-    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, clientName);
+    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
     String commandString = csb.toString();
     writeToLog("Command String : ", commandString);
     CommandResult commandResult = executeCommand(commandString);
@@ -167,8 +189,8 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     assertTrue(resultAsString.contains("4"));
 
     csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
-    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, clientName);
-    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME, cq3);
+    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
+    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME, CQ3);
     commandString = csb.toString();
     writeToLog("Command String : ", commandString);
     commandResult = executeCommand(commandString);
@@ -177,14 +199,14 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     assertTrue(Status.OK.equals(commandResult.getStatus()));
 
     // CLOSE all the cqs
-    closeCq(cq1);
-    closeCq(cq2);
-    closeCq(cq3);
+    closeCq(CQ1);
+    closeCq(CQ2);
+    closeCq(CQ3);
 
     // Run the commands again
     csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
-    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, clientName);
-    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME, cq1);
+    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
+    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME, CQ1);
     commandString = csb.toString();
     writeToLog("Command String : ", commandString);
     commandResult = executeCommand(commandString);
@@ -192,11 +214,11 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     writeToLog("Command Result :\n", resultAsString);
     assertTrue(Status.ERROR.equals(commandResult.getStatus()));
     String errorMessage = CliStrings
-        .format(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE_CQ_NOT_FOUND, clientName, cq1);
+        .format(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE_CQ_NOT_FOUND, CLIENT_NAME, CQ1);
     assertTrue(resultAsString.contains(errorMessage));
 
     csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
-    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, clientName);
+    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
     commandString = csb.toString();
     writeToLog("Command String : ", commandString);
     commandResult = executeCommand(commandString);
@@ -209,8 +231,9 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
 
     // Close the client
     csb = new CommandStringBuilder(CliStrings.CLOSE_DURABLE_CLIENTS);
-    csb.addOption(CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, clientName);
+    csb.addOption(CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, CLIENT_NAME);
     commandString = csb.toString();
+
     // since it can take the server a bit to know that the client has disconnected
     // we loop here
     long giveUpTime = System.currentTimeMillis() + 20000;
@@ -220,12 +243,13 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
       resultAsString = commandResultToString(commandResult);
     } while (resultAsString.contains("Cannot close a running durable client")
         && giveUpTime > System.currentTimeMillis());
+
     writeToLog("Command Result :\n", resultAsString);
     assertTrue("failed executing" + commandString + "; result = " + resultAsString,
         Status.OK.equals(commandResult.getStatus()));
 
     csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
-    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, clientName);
+    csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
     commandString = csb.toString();
     writeToLog("Command String : ", commandString);
     commandResult = executeCommand(commandString);
@@ -233,7 +257,7 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     writeToLog("Command Result :\n", resultAsString);
     assertTrue(Status.ERROR.equals(commandResult.getStatus()));
     assertTrue(resultAsString
-        .contains(CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, clientName)));
+        .contains(CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, CLIENT_NAME)));
   }
 
   private void writeToLog(String text, String resultAsString) {
@@ -244,12 +268,12 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
     disconnectAllFromDS();
     setUpJmxManagerOnVm0ThenConnect(getServerProperties());
 
-    final VM manager = Host.getHost(0).getVM(0);
-    final VM server1 = Host.getHost(0).getVM(1);
-    final VM client1 = Host.getHost(0).getVM(2);
+    VM manager = Host.getHost(0).getVM(0);
+    VM server1 = Host.getHost(0).getVM(1);
+    VM client1 = Host.getHost(0).getVM(2);
 
-    int listeningPort = startCacheServer(server1, 0, false, regionName);
-    startDurableClient(client1, server1, listeningPort, clientName, "300");
+    int listeningPort = startCacheServer(server1, 0, false, REGION_NAME);
+    startDurableClient(client1, server1, listeningPort, CLIENT_NAME, "300");
   }
 
   /**
@@ -258,99 +282,94 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
    * @param cqName , Name of the cq which is to be close.
    */
   private void closeCq(final String cqName) {
-    final VM vm2 = Host.getHost(0).getVM(2);
+    VM vm2 = Host.getHost(0).getVM(2);
     vm2.invoke(new SerializableCallable() {
+      @Override
       public Object call() {
         QueryService qs = getCache().getQueryService();
         CqAttributesFactory cqAf = new CqAttributesFactory();
+
         try {
           qs.getCq(cqName).close();
-
         } catch (CqException e) {
-          e.printStackTrace();
-          return false;
+          throw new RuntimeException(e);
         }
+
         return true;
       }
     });
   }
 
   private void setupCqs() {
-    final VM vm2 = Host.getHost(0).getVM(2);
+    VM vm2 = Host.getHost(0).getVM(2);
+
     vm2.invoke(new SerializableCallable() {
+      @Override
       public Object call() {
         QueryService qs = getCache().getQueryService();
         CqAttributesFactory cqAf = new CqAttributesFactory();
+
         try {
-          qs.newCq(cq1, "select * from /" + regionName, cqAf.create(), true).execute();
-          qs.newCq(cq2, "select * from /" + regionName + " where id = 1", cqAf.create(), true)
+          qs.newCq(CQ1, "select * from /" + REGION_NAME, cqAf.create(), true).execute();
+          qs.newCq(CQ2, "select * from /" + REGION_NAME + " where id = 1", cqAf.create(), true)
               .execute();
-          qs.newCq(cq3, "select * from /" + regionName + " where id > 2", cqAf.create(), true)
+          qs.newCq(CQ3, "select * from /" + REGION_NAME + " where id > 2", cqAf.create(), true)
               .execute();
-        } catch (CqException e) {
-          e.printStackTrace();
-          return false;
-        } catch (CqExistsException e) {
-          e.printStackTrace();
-
-          return false;
-        } catch (RegionNotFoundException e) {
-          e.printStackTrace();
-
-          return false;
+        } catch (CqException | CqExistsException | RegionNotFoundException e) {
+          throw new RuntimeException(e);
         }
+
         return true;
       }
     });
   }
 
-  private int startCacheServer(VM server, final int port, final boolean createPR,
-      final String regionName) throws Exception {
-
-    Integer listeningPort = (Integer) server.invoke(new SerializableCallable() {
-      public Object call() throws Exception {
-        getSystem(getServerProperties());
-
-        GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
-        AttributesFactory factory = new AttributesFactory();
-        if (createPR) {
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
-          paf.setRedundantCopies(1);
-          paf.setTotalNumBuckets(11);
-          factory.setPartitionAttributes(paf.create());
-        } else {
-          factory.setScope(Scope.DISTRIBUTED_ACK);
-          factory.setDataPolicy(DataPolicy.REPLICATE);
-        }
-        Region region = createRootRegion(regionName, factory.create());
-        if (createPR) {
-          assertTrue(region instanceof PartitionedRegion);
-        } else {
-          assertTrue(region instanceof DistributedRegion);
-        }
-        CacheServer cacheServer = getCache().addCacheServer();
-        cacheServer.setPort(port);
-        cacheServer.start();
+  private int startCacheServer(final VM serverVM, final int port, final boolean createPR,
+      final String regionName) {
+    return serverVM.invoke(() -> {
+      getSystem(getServerProperties());
+
+      InternalCache cache = getCache();
+      AttributesFactory factory = new AttributesFactory();
+
+      if (createPR) {
+        PartitionAttributesFactory paf = new PartitionAttributesFactory();
+        paf.setRedundantCopies(1);
+        paf.setTotalNumBuckets(11);
+        factory.setPartitionAttributes(paf.create());
+      } else {
+        factory.setScope(Scope.DISTRIBUTED_ACK);
+        factory.setDataPolicy(DataPolicy.REPLICATE);
+      }
 
-        return cacheServer.getPort();
+      Region region = createRootRegion(regionName, factory.create());
+      if (createPR) {
+        assertTrue(region instanceof PartitionedRegion);
+      } else {
+        assertTrue(region instanceof DistributedRegion);
       }
-    });
 
-    return listeningPort.intValue();
+      CacheServer cacheServer = getCache().addCacheServer();
+      cacheServer.setPort(port);
+      cacheServer.start();
+
+      return cacheServer.getPort();
+    });
   }
 
-  private void startDurableClient(VM client, final VM server, final int port,
+  private void startDurableClient(final VM clientVM, final VM serverVM, final int port,
       final String durableClientId, final String durableClientTimeout) {
-    client.invoke(new CacheSerializableRunnable("Start client") {
+    clientVM.invoke(new CacheSerializableRunnable("Start client") {
+      @Override
       public void run2() throws CacheException {
         Properties props = getClientProps(durableClientId, durableClientTimeout);
         getSystem(props);
 
-        final ClientCacheFactory ccf = new ClientCacheFactory(props);
-        ccf.addPoolServer(getServerHostName(server.getHost()), port);
+        ClientCacheFactory ccf = new ClientCacheFactory(props);
+        ccf.addPoolServer(getServerHostName(serverVM.getHost()), port);
         ccf.setPoolSubscriptionEnabled(true);
 
-        ClientCache cache = (ClientCache) getClientCache(ccf);
+        ClientCache cache = getClientCache(ccf);
       }
     });
   }
@@ -358,11 +377,13 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
   /**
    * Does few puts on the region on the server
    */
-  private void doPuts(final String regionName, VM server) {
-    server.invoke(new SerializableCallable() {
-      public Object call() throws Exception {
-        GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
+  private void doPuts(final String regionName, final VM serverVM) {
+    serverVM.invoke(new SerializableRunnable() {
+      @Override
+      public void run() {
+        InternalCache cache = getCache();
         Region region = cache.getRegion(regionName);
+
         Portfolio p1 = new Portfolio();
         p1.ID = 1;
         p1.names = new String[] {"AAPL", "VMW"};
@@ -383,15 +404,16 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
         region.put("p2", p2);
         region.put("p3", p3);
         region.put("p4", p4);
-        return null;
       }
     });
   }
 
   // Closes the durable-client from the client side.
   private void closeDurableClient() {
-    final VM client = Host.getHost(0).getVM(2);
-    client.invoke(new CacheSerializableRunnable("Stop client") {
+    VM clientVM = Host.getHost(0).getVM(2);
+
+    clientVM.invoke(new CacheSerializableRunnable("Stop client") {
+      @Override
       public void run2() throws CacheException {
         ClientCacheFactory.getAnyInstance().close(true);
       }
@@ -399,24 +421,17 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
   }
 
   protected Properties getClientProps(String durableClientId, String durableClientTimeout) {
-    Properties p = new Properties();
-    p.setProperty(MCAST_PORT, "0");
-    p.setProperty(LOCATORS, "");
-    p.setProperty(DURABLE_CLIENT_ID, durableClientId);
-    p.setProperty(DURABLE_CLIENT_TIMEOUT, String.valueOf(durableClientTimeout));
-    return p;
+    Properties config = new Properties();
+    config.setProperty(MCAST_PORT, "0");
+    config.setProperty(LOCATORS, "");
+    config.setProperty(DURABLE_CLIENT_ID, durableClientId);
+    config.setProperty(DURABLE_CLIENT_TIMEOUT, String.valueOf(durableClientTimeout));
+    return config;
   }
 
   protected Properties getServerProperties() {
-    Properties p = new Properties();
-    p.setProperty(LOCATORS, "localhost[" + getDUnitLocatorPort() + "]");
-    return p;
-  }
-
-  @Override
-  public final void postTearDownCacheTestCase() throws Exception {
-    Host.getHost(0).getVM(0).invoke(() -> CacheServerTestUtil.closeCache());
-    Host.getHost(0).getVM(1).invoke(() -> CacheServerTestUtil.closeCache());
-    Host.getHost(0).getVM(2).invoke(() -> CacheServerTestUtil.closeCache());
+    Properties config = new Properties();
+    config.setProperty(LOCATORS, "localhost[" + getDUnitLocatorPort() + "]");
+    return config;
   }
 }


[14/47] geode git commit: GEODE-3436: Restore refactoring of CreateAlterDestroyRegionCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of CreateAlterDestroyRegionCommands

* See initial commit GEODE-3255 (756efe77c86bb03ac9984655e7bd040659e85890)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 0c124b77a86e1144cd6a84ae6d7d61f75a132258
Parents: 4fc3ffe
Author: YehEmily <em...@gmail.com>
Authored: Thu Aug 24 16:11:13 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:25 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/AlterRegionCommand.java        |  229 ++++
 .../CreateAlterDestroyRegionCommands.java       | 1146 -----------------
 .../cli/commands/CreateRegionCommand.java       |  725 +++++++++++
 .../cli/commands/DestroyRegionCommand.java      |  222 ++++
 .../cli/commands/RegionCommandsUtils.java       |   78 ++
 .../cli/functions/RegionCreateFunction.java     |    8 +-
 .../geode/redis/internal/RegionProvider.java    |   15 +-
 .../commands/AlterRegionCommandDUnitTest.java   |  641 +++++++++
 ...eateAlterDestroyRegionCommandsDUnitTest.java | 1211 +-----------------
 .../CreateAlterDestroyRegionCommandsTest.java   |   53 -
 .../commands/CreateRegionCommandDUnitTest.java  |  318 +++++
 .../cli/commands/CreateRegionCommandTest.java   |   58 +
 .../commands/DestroyRegionCommandDUnitTest.java |  388 ++++++
 .../internal/security/TestCommand.java          |    2 +-
 14 files changed, 2696 insertions(+), 2398 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommand.java
new file mode 100644
index 0000000..0f9b5d8
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommand.java
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.ExpirationAttributes;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.RegionAlterFunction;
+import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+
+public class AlterRegionCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.ALTER_REGION, help = CliStrings.ALTER_REGION__HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+  public Result alterRegion(
+      @CliOption(key = CliStrings.ALTER_REGION__REGION, mandatory = true,
+          help = CliStrings.ALTER_REGION__REGION__HELP) String regionPath,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.ALTER_REGION__GROUP__HELP) String[] groups,
+      @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME,
+          specifiedDefaultValue = "-1",
+          help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
+      @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
+          specifiedDefaultValue = "INVALIDATE",
+          help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
+      @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE,
+          specifiedDefaultValue = "-1",
+          help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
+      @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION,
+          specifiedDefaultValue = "INVALIDATE",
+          help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
+      @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME,
+          specifiedDefaultValue = "-1",
+          help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
+      @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION,
+          specifiedDefaultValue = "INVALIDATE",
+          help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
+      @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, specifiedDefaultValue = "-1",
+          help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
+      @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION,
+          specifiedDefaultValue = "INVALIDATE",
+          help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
+      @CliOption(key = CliStrings.ALTER_REGION__CACHELISTENER, specifiedDefaultValue = "",
+          help = CliStrings.ALTER_REGION__CACHELISTENER__HELP) String[] cacheListeners,
+      @CliOption(key = CliStrings.ALTER_REGION__CACHELOADER, specifiedDefaultValue = "",
+          help = CliStrings.ALTER_REGION__CACHELOADER__HELP) String cacheLoader,
+      @CliOption(key = CliStrings.ALTER_REGION__CACHEWRITER, specifiedDefaultValue = "",
+          help = CliStrings.ALTER_REGION__CACHEWRITER__HELP) String cacheWriter,
+      @CliOption(key = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID, specifiedDefaultValue = "",
+          help = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
+      @CliOption(key = CliStrings.ALTER_REGION__GATEWAYSENDERID, specifiedDefaultValue = "",
+          help = CliStrings.ALTER_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
+      @CliOption(key = CliStrings.ALTER_REGION__CLONINGENABLED, specifiedDefaultValue = "false",
+          help = CliStrings.ALTER_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
+      @CliOption(key = CliStrings.ALTER_REGION__EVICTIONMAX, specifiedDefaultValue = "0",
+          help = CliStrings.ALTER_REGION__EVICTIONMAX__HELP) Integer evictionMax) {
+    Result result;
+    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+
+    getSecurityService().authorizeRegionManage(regionPath);
+
+    try {
+      InternalCache cache = getCache();
+
+      if (groups != null) {
+        RegionCommandsUtils.validateGroups(cache, groups);
+      }
+
+      RegionFunctionArgs.ExpirationAttrs entryIdle = null;
+      if (entryExpirationIdleTime != null || entryExpirationIdleTimeAction != null) {
+        if (entryExpirationIdleTime != null && entryExpirationIdleTime == -1) {
+          entryExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
+        }
+        if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationIdleTimeAction)) {
+          entryExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
+        }
+        entryIdle = new RegionFunctionArgs.ExpirationAttrs(
+            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
+            entryExpirationIdleTimeAction);
+      }
+      RegionFunctionArgs.ExpirationAttrs entryTTL = null;
+      if (entryExpirationTTL != null || entryExpirationTTLAction != null) {
+        if (entryExpirationTTL != null && entryExpirationTTL == -1) {
+          entryExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
+        }
+        if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationTTLAction)) {
+          entryExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
+        }
+        entryTTL = new RegionFunctionArgs.ExpirationAttrs(
+            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
+            entryExpirationTTLAction);
+      }
+      RegionFunctionArgs.ExpirationAttrs regionIdle = null;
+      if (regionExpirationIdleTime != null || regionExpirationIdleTimeAction != null) {
+        if (regionExpirationIdleTime != null && regionExpirationIdleTime == -1) {
+          regionExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
+        }
+        if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationIdleTimeAction)) {
+          regionExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
+        }
+        regionIdle = new RegionFunctionArgs.ExpirationAttrs(
+            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
+            regionExpirationIdleTimeAction);
+      }
+      RegionFunctionArgs.ExpirationAttrs regionTTL = null;
+      if (regionExpirationTTL != null || regionExpirationTTLAction != null) {
+        if (regionExpirationTTL != null && regionExpirationTTL == -1) {
+          regionExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
+        }
+        if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationTTLAction)) {
+          regionExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
+        }
+        regionTTL = new RegionFunctionArgs.ExpirationAttrs(
+            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
+            regionExpirationTTLAction);
+      }
+
+      cacheLoader = convertDefaultValue(cacheLoader, StringUtils.EMPTY);
+      cacheWriter = convertDefaultValue(cacheWriter, StringUtils.EMPTY);
+
+      RegionFunctionArgs regionFunctionArgs;
+      regionFunctionArgs = new RegionFunctionArgs(regionPath, null, null, false, null, null, null,
+          entryIdle, entryTTL, regionIdle, regionTTL, null, null, null, null, cacheListeners,
+          cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, null, cloningEnabled,
+          null, null, null, null, null, null, null, null, evictionMax, null, null, null, null);
+
+      Set<String> cacheListenersSet = regionFunctionArgs.getCacheListeners();
+      if (cacheListenersSet != null && !cacheListenersSet.isEmpty()) {
+        for (String cacheListener : cacheListenersSet) {
+          if (!RegionCommandsUtils.isClassNameValid(cacheListener)) {
+            throw new IllegalArgumentException(CliStrings.format(
+                CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
+                new Object[] {cacheListener}));
+          }
+        }
+      }
+
+      if (cacheLoader != null && !RegionCommandsUtils.isClassNameValid(cacheLoader)) {
+        throw new IllegalArgumentException(CliStrings.format(
+            CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
+            new Object[] {cacheLoader}));
+      }
+
+      if (cacheWriter != null && !RegionCommandsUtils.isClassNameValid(cacheWriter)) {
+        throw new IllegalArgumentException(CliStrings.format(
+            CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
+            new Object[] {cacheWriter}));
+      }
+
+      if (evictionMax != null && evictionMax < 0) {
+        throw new IllegalArgumentException(CliStrings.format(
+            CliStrings.ALTER_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_EVICTIONMAX_0_IS_NOT_VALID,
+            new Object[] {evictionMax}));
+      }
+
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      ResultCollector<?, ?> resultCollector =
+          CliUtil.executeFunction(new RegionAlterFunction(), regionFunctionArgs, targetMembers);
+      List<CliFunctionResult> regionAlterResults =
+          (List<CliFunctionResult>) resultCollector.getResult();
+
+      TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
+      final String errorPrefix = "ERROR: ";
+      for (CliFunctionResult regionAlterResult : regionAlterResults) {
+        boolean success = regionAlterResult.isSuccessful();
+        tabularResultData.accumulate("Member", regionAlterResult.getMemberIdOrName());
+        if (success) {
+          tabularResultData.accumulate("Status", regionAlterResult.getMessage());
+          xmlEntity.set(regionAlterResult.getXmlEntity());
+        } else {
+          tabularResultData.accumulate("Status", errorPrefix + regionAlterResult.getMessage());
+          tabularResultData.setStatus(Result.Status.ERROR);
+        }
+      }
+      result = ResultBuilder.buildResult(tabularResultData);
+    } catch (IllegalArgumentException | IllegalStateException e) {
+      LogWrapper.getInstance().info(e.getMessage());
+      result = ResultBuilder.createUserErrorResult(e.getMessage());
+    } catch (RuntimeException e) {
+      LogWrapper.getInstance().info(e.getMessage(), e);
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+
+    if (xmlEntity.get() != null) {
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
+    }
+    return result;
+  }
+
+
+
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
deleted file mode 100644
index 2c61b73..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
+++ /dev/null
@@ -1,1146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.regex.Pattern;
-
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.LogWriter;
-import org.apache.geode.cache.DataPolicy;
-import org.apache.geode.cache.ExpirationAttributes;
-import org.apache.geode.cache.PartitionResolver;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionAttributes;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.Scope;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.compression.Compressor;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.DistributionManager;
-import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
-import org.apache.geode.internal.ClassPathLoader;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.i18n.LocalizedStrings;
-import org.apache.geode.management.DistributedRegionMXBean;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.RegionAttributesData;
-import org.apache.geode.management.RegionMXBean;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction;
-import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult;
-import org.apache.geode.management.internal.cli.functions.RegionAlterFunction;
-import org.apache.geode.management.internal.cli.functions.RegionCreateFunction;
-import org.apache.geode.management.internal.cli.functions.RegionDestroyFunction;
-import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.util.RegionPath;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.geode.security.ResourcePermission.Target;
-
-/**
- * @since GemFire 7.0
- */
-public class CreateAlterDestroyRegionCommands implements GfshCommand {
-
-  public static final Set<RegionShortcut> PERSISTENT_OVERFLOW_SHORTCUTS = new TreeSet<>();
-
-  static {
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_OVERFLOW);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_OVERFLOW);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_OVERFLOW);
-    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
-  }
-
-  /**
-   * Internally, we also verify the resource operation permissions CLUSTER:WRITE:DISK if the region
-   * is persistent
-   */
-  @CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP)
-  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
-  @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
-  public Result createRegion(
-      @CliOption(key = CliStrings.CREATE_REGION__REGION, mandatory = true,
-          help = CliStrings.CREATE_REGION__REGION__HELP) String regionPath,
-      @CliOption(key = CliStrings.CREATE_REGION__REGIONSHORTCUT,
-          help = CliStrings.CREATE_REGION__REGIONSHORTCUT__HELP) RegionShortcut regionShortcut,
-      @CliOption(key = CliStrings.CREATE_REGION__USEATTRIBUTESFROM,
-          optionContext = ConverterHint.REGION_PATH,
-          help = CliStrings.CREATE_REGION__USEATTRIBUTESFROM__HELP) String useAttributesFrom,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.CREATE_REGION__GROUP__HELP) String[] groups,
-      @CliOption(key = CliStrings.CREATE_REGION__SKIPIFEXISTS, unspecifiedDefaultValue = "true",
-          specifiedDefaultValue = "true",
-          help = CliStrings.CREATE_REGION__SKIPIFEXISTS__HELP) boolean skipIfExists,
-
-      // the following should all be in alphabetical order according to
-      // their key string
-      @CliOption(key = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID,
-          help = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
-      @CliOption(key = CliStrings.CREATE_REGION__CACHELISTENER,
-          help = CliStrings.CREATE_REGION__CACHELISTENER__HELP) String[] cacheListener,
-      @CliOption(key = CliStrings.CREATE_REGION__CACHELOADER,
-          help = CliStrings.CREATE_REGION__CACHELOADER__HELP) String cacheLoader,
-      @CliOption(key = CliStrings.CREATE_REGION__CACHEWRITER,
-          help = CliStrings.CREATE_REGION__CACHEWRITER__HELP) String cacheWriter,
-      @CliOption(key = CliStrings.CREATE_REGION__COLOCATEDWITH,
-          optionContext = ConverterHint.REGION_PATH,
-          help = CliStrings.CREATE_REGION__COLOCATEDWITH__HELP) String prColocatedWith,
-      @CliOption(key = CliStrings.CREATE_REGION__COMPRESSOR,
-          help = CliStrings.CREATE_REGION__COMPRESSOR__HELP) String compressor,
-      @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYLEVEL,
-          help = CliStrings.CREATE_REGION__CONCURRENCYLEVEL__HELP) Integer concurrencyLevel,
-      @CliOption(key = CliStrings.CREATE_REGION__DISKSTORE,
-          help = CliStrings.CREATE_REGION__DISKSTORE__HELP) String diskStore,
-      @CliOption(key = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION,
-          help = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION__HELP) Boolean enableAsyncConflation,
-      @CliOption(key = CliStrings.CREATE_REGION__CLONINGENABLED,
-          help = CliStrings.CREATE_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
-      @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED,
-          help = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED__HELP) Boolean concurrencyChecksEnabled,
-      @CliOption(key = CliStrings.CREATE_REGION__MULTICASTENABLED,
-          help = CliStrings.CREATE_REGION__MULTICASTENABLED__HELP) Boolean mcastEnabled,
-      @CliOption(key = CliStrings.CREATE_REGION__STATISTICSENABLED,
-          help = CliStrings.CREATE_REGION__STATISTICSENABLED__HELP) Boolean statisticsEnabled,
-      @CliOption(key = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION,
-          help = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION__HELP) Boolean enableSubscriptionConflation,
-      @CliOption(key = CliStrings.CREATE_REGION__DISKSYNCHRONOUS,
-          help = CliStrings.CREATE_REGION__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
-      @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME,
-          help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
-      @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
-          help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
-      @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE,
-          help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
-      @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION,
-          help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
-      @CliOption(key = CliStrings.CREATE_REGION__GATEWAYSENDERID,
-          help = CliStrings.CREATE_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
-      @CliOption(key = CliStrings.CREATE_REGION__KEYCONSTRAINT,
-          help = CliStrings.CREATE_REGION__KEYCONSTRAINT__HELP) String keyConstraint,
-      @CliOption(key = CliStrings.CREATE_REGION__LOCALMAXMEMORY,
-          help = CliStrings.CREATE_REGION__LOCALMAXMEMORY__HELP) Integer prLocalMaxMemory,
-      @CliOption(key = CliStrings.CREATE_REGION__OFF_HEAP, specifiedDefaultValue = "true",
-          help = CliStrings.CREATE_REGION__OFF_HEAP__HELP) Boolean offHeap,
-      @CliOption(key = CliStrings.CREATE_REGION__PARTITION_RESOLVER,
-          help = CliStrings.CREATE_REGION__PARTITION_RESOLVER__HELP) String partitionResolver,
-      @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME,
-          help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
-      @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION,
-          help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
-      @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL,
-          help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
-      @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION,
-          help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
-      @CliOption(key = CliStrings.CREATE_REGION__RECOVERYDELAY,
-          help = CliStrings.CREATE_REGION__RECOVERYDELAY__HELP) Long prRecoveryDelay,
-      @CliOption(key = CliStrings.CREATE_REGION__REDUNDANTCOPIES,
-          help = CliStrings.CREATE_REGION__REDUNDANTCOPIES__HELP) Integer prRedundantCopies,
-      @CliOption(key = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY,
-          help = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY__HELP) Long prStartupRecoveryDelay,
-      @CliOption(key = CliStrings.CREATE_REGION__TOTALMAXMEMORY,
-          help = CliStrings.CREATE_REGION__TOTALMAXMEMORY__HELP) Long prTotalMaxMemory,
-      @CliOption(key = CliStrings.CREATE_REGION__TOTALNUMBUCKETS,
-          help = CliStrings.CREATE_REGION__TOTALNUMBUCKETS__HELP) Integer prTotalNumBuckets,
-      @CliOption(key = CliStrings.CREATE_REGION__VALUECONSTRAINT,
-          help = CliStrings.CREATE_REGION__VALUECONSTRAINT__HELP) String valueConstraint
-  // NOTICE: keep the region attributes params in alphabetical order
-  ) {
-    Result result;
-    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
-    try {
-      InternalCache cache = getCache();
-
-      if (regionShortcut != null && useAttributesFrom != null) {
-        throw new IllegalArgumentException(
-            CliStrings.CREATE_REGION__MSG__ONLY_ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_CAN_BE_SPECIFIED);
-      } else if (regionShortcut == null && useAttributesFrom == null) {
-        throw new IllegalArgumentException(
-            CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUTESFROM_IS_REQUIRED);
-      }
-
-      validateRegionPathAndParent(cache, regionPath);
-      validateGroups(cache, groups);
-
-      RegionFunctionArgs.ExpirationAttrs entryIdle = null;
-      if (entryExpirationIdleTime != null) {
-        entryIdle = new RegionFunctionArgs.ExpirationAttrs(
-            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
-            entryExpirationIdleTimeAction);
-      }
-      RegionFunctionArgs.ExpirationAttrs entryTTL = null;
-      if (entryExpirationTTL != null) {
-        entryTTL = new RegionFunctionArgs.ExpirationAttrs(
-            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
-            entryExpirationTTLAction);
-      }
-      RegionFunctionArgs.ExpirationAttrs regionIdle = null;
-      if (regionExpirationIdleTime != null) {
-        regionIdle = new RegionFunctionArgs.ExpirationAttrs(
-            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
-            regionExpirationIdleTimeAction);
-      }
-      RegionFunctionArgs.ExpirationAttrs regionTTL = null;
-      if (regionExpirationTTL != null) {
-        regionTTL = new RegionFunctionArgs.ExpirationAttrs(
-            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
-            regionExpirationTTLAction);
-      }
-
-      RegionFunctionArgs regionFunctionArgs;
-      if (useAttributesFrom != null) {
-        if (!regionExists(cache, useAttributesFrom)) {
-          throw new IllegalArgumentException(CliStrings.format(
-              CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
-              new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
-        }
-
-        FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult =
-            getRegionAttributes(cache, useAttributesFrom);
-        RegionAttributes<?, ?> regionAttributes = regionAttributesResult.getRegionAttributes();
-
-        // give preference to user specified plugins than the ones retrieved from other region
-        String[] cacheListenerClasses = cacheListener != null && cacheListener.length != 0
-            ? cacheListener : regionAttributesResult.getCacheListenerClasses();
-        String cacheLoaderClass =
-            cacheLoader != null ? cacheLoader : regionAttributesResult.getCacheLoaderClass();
-        String cacheWriterClass =
-            cacheWriter != null ? cacheWriter : regionAttributesResult.getCacheWriterClass();
-
-        regionFunctionArgs = new RegionFunctionArgs(regionPath, useAttributesFrom, skipIfExists,
-            keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle,
-            regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
-            enableSubscriptionConflation, cacheListenerClasses, cacheLoaderClass, cacheWriterClass,
-            asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
-            concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
-            prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, offHeap, mcastEnabled,
-            regionAttributes, partitionResolver);
-
-        if (regionAttributes.getPartitionAttributes() == null
-            && regionFunctionArgs.hasPartitionAttributes()) {
-          throw new IllegalArgumentException(CliStrings.format(
-              CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
-              regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
-              + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
-                  useAttributesFrom));
-        }
-      } else {
-        regionFunctionArgs = new RegionFunctionArgs(regionPath, regionShortcut, useAttributesFrom,
-            skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL,
-            regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
-            enableSubscriptionConflation, cacheListener, cacheLoader, cacheWriter,
-            asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
-            concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
-            prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, null, compressor, offHeap,
-            mcastEnabled, partitionResolver);
-
-        if (!regionShortcut.name().startsWith("PARTITION")
-            && regionFunctionArgs.hasPartitionAttributes()) {
-          throw new IllegalArgumentException(CliStrings.format(
-              CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
-              regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
-              + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
-                  useAttributesFrom));
-        }
-      }
-
-      // Do we prefer to validate or authorize first?
-      validateRegionFunctionArgs(cache, regionFunctionArgs);
-      if (isPersistentShortcut(regionFunctionArgs.getRegionShortcut())
-          || isAttributePersistent(regionFunctionArgs.getRegionAttributes())) {
-        getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
-      }
-
-      Set<DistributedMember> membersToCreateRegionOn;
-      if (groups != null && groups.length != 0) {
-        membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups);
-        // have only normal members from the group
-        membersToCreateRegionOn
-            .removeIf(distributedMember -> ((InternalDistributedMember) distributedMember)
-                .getVmKind() == DistributionManager.LOCATOR_DM_TYPE);
-      } else {
-        membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache);
-      }
-
-      if (membersToCreateRegionOn.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
-      }
-
-      ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionCreateFunction.INSTANCE,
-          regionFunctionArgs, membersToCreateRegionOn);
-      @SuppressWarnings("unchecked")
-      List<CliFunctionResult> regionCreateResults =
-          (List<CliFunctionResult>) resultCollector.getResult();
-
-      TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
-      final String errorPrefix = "ERROR: ";
-      for (CliFunctionResult regionCreateResult : regionCreateResults) {
-        boolean success = regionCreateResult.isSuccessful();
-        tabularResultData.accumulate("Member", regionCreateResult.getMemberIdOrName());
-        tabularResultData.accumulate("Status",
-            (success ? "" : errorPrefix) + regionCreateResult.getMessage());
-
-        if (success) {
-          xmlEntity.set(regionCreateResult.getXmlEntity());
-        }
-      }
-      result = ResultBuilder.buildResult(tabularResultData);
-      verifyDistributedRegionMbean(cache, regionPath);
-
-    } catch (IllegalArgumentException | IllegalStateException e) {
-      LogWrapper.getInstance().info(e.getMessage());
-      result = ResultBuilder.createUserErrorResult(e.getMessage());
-    }
-    if (xmlEntity.get() != null) {
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
-    }
-
-    return result;
-  }
-
-  public boolean verifyDistributedRegionMbean(InternalCache cache, String regionName) {
-    int federationInterval =
-        cache.getInternalDistributedSystem().getConfig().getJmxManagerUpdateRate();
-    long timeEnd = System.currentTimeMillis() + federationInterval + 50;
-
-    for (; System.currentTimeMillis() <= timeEnd;) {
-      try {
-        DistributedRegionMXBean bean =
-            ManagementService.getManagementService(cache).getDistributedRegionMXBean(regionName);
-        if (bean == null) {
-          bean = ManagementService.getManagementService(cache)
-              .getDistributedRegionMXBean(Region.SEPARATOR + regionName);
-        }
-        if (bean != null) {
-          return true;
-        } else {
-          Thread.sleep(2);
-        }
-      } catch (Exception ignored) {
-      }
-    }
-    return false;
-  }
-
-  @CliCommand(value = CliStrings.ALTER_REGION, help = CliStrings.ALTER_REGION__HELP)
-  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
-  public Result alterRegion(
-      @CliOption(key = CliStrings.ALTER_REGION__REGION, mandatory = true,
-          help = CliStrings.ALTER_REGION__REGION__HELP) String regionPath,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.ALTER_REGION__GROUP__HELP) String[] groups,
-      @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME,
-          specifiedDefaultValue = "-1",
-          help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
-      @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
-          specifiedDefaultValue = "INVALIDATE",
-          help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
-      @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE,
-          specifiedDefaultValue = "-1",
-          help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
-      @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION,
-          specifiedDefaultValue = "INVALIDATE",
-          help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
-      @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME,
-          specifiedDefaultValue = "-1",
-          help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
-      @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION,
-          specifiedDefaultValue = "INVALIDATE",
-          help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
-      @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, specifiedDefaultValue = "-1",
-          help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
-      @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION,
-          specifiedDefaultValue = "INVALIDATE",
-          help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
-      @CliOption(key = CliStrings.ALTER_REGION__CACHELISTENER, specifiedDefaultValue = "",
-          help = CliStrings.ALTER_REGION__CACHELISTENER__HELP) String[] cacheListeners,
-      @CliOption(key = CliStrings.ALTER_REGION__CACHELOADER, specifiedDefaultValue = "",
-          help = CliStrings.ALTER_REGION__CACHELOADER__HELP) String cacheLoader,
-      @CliOption(key = CliStrings.ALTER_REGION__CACHEWRITER, specifiedDefaultValue = "",
-          help = CliStrings.ALTER_REGION__CACHEWRITER__HELP) String cacheWriter,
-      @CliOption(key = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID, specifiedDefaultValue = "",
-          help = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
-      @CliOption(key = CliStrings.ALTER_REGION__GATEWAYSENDERID, specifiedDefaultValue = "",
-          help = CliStrings.ALTER_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
-      @CliOption(key = CliStrings.ALTER_REGION__CLONINGENABLED, specifiedDefaultValue = "false",
-          help = CliStrings.ALTER_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
-      @CliOption(key = CliStrings.ALTER_REGION__EVICTIONMAX, specifiedDefaultValue = "0",
-          help = CliStrings.ALTER_REGION__EVICTIONMAX__HELP) Integer evictionMax) {
-    Result result;
-    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
-    getSecurityService().authorizeRegionManage(regionPath);
-
-    try {
-      InternalCache cache = getCache();
-
-      if (groups != null) {
-        validateGroups(cache, groups);
-      }
-
-      RegionFunctionArgs.ExpirationAttrs entryIdle = null;
-      if (entryExpirationIdleTime != null || entryExpirationIdleTimeAction != null) {
-        if (entryExpirationIdleTime != null && entryExpirationIdleTime == -1) {
-          entryExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
-        }
-        if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationIdleTimeAction)) {
-          entryExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
-        }
-        entryIdle = new RegionFunctionArgs.ExpirationAttrs(
-            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
-            entryExpirationIdleTimeAction);
-      }
-      RegionFunctionArgs.ExpirationAttrs entryTTL = null;
-      if (entryExpirationTTL != null || entryExpirationTTLAction != null) {
-        if (entryExpirationTTL != null && entryExpirationTTL == -1) {
-          entryExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
-        }
-        if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationTTLAction)) {
-          entryExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
-        }
-        entryTTL = new RegionFunctionArgs.ExpirationAttrs(
-            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
-            entryExpirationTTLAction);
-      }
-      RegionFunctionArgs.ExpirationAttrs regionIdle = null;
-      if (regionExpirationIdleTime != null || regionExpirationIdleTimeAction != null) {
-        if (regionExpirationIdleTime != null && regionExpirationIdleTime == -1) {
-          regionExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
-        }
-        if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationIdleTimeAction)) {
-          regionExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
-        }
-        regionIdle = new RegionFunctionArgs.ExpirationAttrs(
-            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
-            regionExpirationIdleTimeAction);
-      }
-      RegionFunctionArgs.ExpirationAttrs regionTTL = null;
-      if (regionExpirationTTL != null || regionExpirationTTLAction != null) {
-        if (regionExpirationTTL != null && regionExpirationTTL == -1) {
-          regionExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
-        }
-        if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationTTLAction)) {
-          regionExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
-        }
-        regionTTL = new RegionFunctionArgs.ExpirationAttrs(
-            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
-            regionExpirationTTLAction);
-      }
-
-      cacheLoader = convertDefaultValue(cacheLoader, StringUtils.EMPTY);
-      cacheWriter = convertDefaultValue(cacheWriter, StringUtils.EMPTY);
-
-      RegionFunctionArgs regionFunctionArgs;
-      regionFunctionArgs = new RegionFunctionArgs(regionPath, null, null, false, null, null, null,
-          entryIdle, entryTTL, regionIdle, regionTTL, null, null, null, null, cacheListeners,
-          cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, null, cloningEnabled,
-          null, null, null, null, null, null, null, null, evictionMax, null, null, null, null);
-
-      Set<String> cacheListenersSet = regionFunctionArgs.getCacheListeners();
-      if (cacheListenersSet != null && !cacheListenersSet.isEmpty()) {
-        for (String cacheListener : cacheListenersSet) {
-          if (!isClassNameValid(cacheListener)) {
-            throw new IllegalArgumentException(CliStrings.format(
-                CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
-                new Object[] {cacheListener}));
-          }
-        }
-      }
-
-      if (cacheLoader != null && !isClassNameValid(cacheLoader)) {
-        throw new IllegalArgumentException(CliStrings.format(
-            CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
-            new Object[] {cacheLoader}));
-      }
-
-      if (cacheWriter != null && !isClassNameValid(cacheWriter)) {
-        throw new IllegalArgumentException(CliStrings.format(
-            CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
-            new Object[] {cacheWriter}));
-      }
-
-      if (evictionMax != null && evictionMax < 0) {
-        throw new IllegalArgumentException(CliStrings.format(
-            CliStrings.ALTER_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_EVICTIONMAX_0_IS_NOT_VALID,
-            new Object[] {evictionMax}));
-      }
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      ResultCollector<?, ?> resultCollector =
-          CliUtil.executeFunction(new RegionAlterFunction(), regionFunctionArgs, targetMembers);
-      List<CliFunctionResult> regionAlterResults =
-          (List<CliFunctionResult>) resultCollector.getResult();
-
-      TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
-      final String errorPrefix = "ERROR: ";
-      for (CliFunctionResult regionAlterResult : regionAlterResults) {
-        boolean success = regionAlterResult.isSuccessful();
-        tabularResultData.accumulate("Member", regionAlterResult.getMemberIdOrName());
-        if (success) {
-          tabularResultData.accumulate("Status", regionAlterResult.getMessage());
-          xmlEntity.set(regionAlterResult.getXmlEntity());
-        } else {
-          tabularResultData.accumulate("Status", errorPrefix + regionAlterResult.getMessage());
-          tabularResultData.setStatus(Status.ERROR);
-        }
-      }
-      result = ResultBuilder.buildResult(tabularResultData);
-    } catch (IllegalArgumentException | IllegalStateException e) {
-      LogWrapper.getInstance().info(e.getMessage());
-      result = ResultBuilder.createUserErrorResult(e.getMessage());
-    } catch (RuntimeException e) {
-      LogWrapper.getInstance().info(e.getMessage(), e);
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-
-    if (xmlEntity.get() != null) {
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
-    }
-    return result;
-  }
-
-  private static boolean regionExists(InternalCache cache, String regionPath) {
-    boolean regionFound = false;
-    if (regionPath != null && !Region.SEPARATOR.equals(regionPath)) {
-      ManagementService managementService = ManagementService.getExistingManagementService(cache);
-      DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean();
-
-      String[] allRegionPaths = dsMBean.listAllRegionPaths();
-      for (String allRegionPath : allRegionPaths) {
-        if (allRegionPath.equals(regionPath)) {
-          regionFound = true;
-          break;
-        }
-      }
-    }
-    return regionFound;
-  }
-
-  private void validateRegionPathAndParent(InternalCache cache, String regionPath) {
-    if (StringUtils.isEmpty(regionPath)) {
-      throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
-    }
-    // If a region path indicates a sub-region, check whether the parent region exists
-    RegionPath regionPathData = new RegionPath(regionPath);
-    String parentRegionPath = regionPathData.getParent();
-    if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) {
-      if (!regionExists(cache, parentRegionPath)) {
-        throw new IllegalArgumentException(
-            CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOES_NOT_EXIST,
-                new Object[] {regionPath}));
-      }
-    }
-  }
-
-  private void validateGroups(InternalCache cache, String[] groups) {
-    if (groups != null && groups.length != 0) {
-      Set<String> existingGroups = new HashSet<>();
-      Set<DistributedMember> members = CliUtil.getAllNormalMembers(cache);
-      for (DistributedMember distributedMember : members) {
-        List<String> memberGroups = distributedMember.getGroups();
-        existingGroups.addAll(memberGroups);
-      }
-      List<String> groupsList = new ArrayList<>(Arrays.asList(groups));
-      groupsList.removeAll(existingGroups);
-
-      if (!groupsList.isEmpty()) {
-        throw new IllegalArgumentException(
-            CliStrings.format(CliStrings.CREATE_REGION__MSG__GROUPS_0_ARE_INVALID,
-                new Object[] {String.valueOf(groupsList)}));
-      }
-    }
-  }
-
-  DistributedSystemMXBean getDSMBean(InternalCache cache) {
-    ManagementService managementService = ManagementService.getExistingManagementService(cache);
-    return managementService.getDistributedSystemMXBean();
-  }
-
-  void validateRegionFunctionArgs(InternalCache cache, RegionFunctionArgs regionFunctionArgs) {
-    if (regionFunctionArgs.getRegionPath() == null) {
-      throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
-    }
-
-    DistributedSystemMXBean dsMBean = getDSMBean(cache);
-
-    String useAttributesFrom = regionFunctionArgs.getUseAttributesFrom();
-    if (useAttributesFrom != null && !useAttributesFrom.isEmpty()
-        && regionExists(cache, useAttributesFrom)) {
-      if (!regionExists(cache, useAttributesFrom)) { // check already done in createRegion !!!
-        throw new IllegalArgumentException(CliStrings.format(
-            CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
-            new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
-      }
-      if (!regionFunctionArgs.isSetUseAttributesFrom()
-          || regionFunctionArgs.getRegionAttributes() == null) {
-        throw new IllegalArgumentException(CliStrings.format(
-            CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS,
-            useAttributesFrom));
-      }
-    }
-
-    if (regionFunctionArgs.hasPartitionAttributes()) {
-      RegionFunctionArgs.PartitionArgs partitionArgs = regionFunctionArgs.getPartitionArgs();
-      String colocatedWith = partitionArgs.getPrColocatedWith();
-      if (colocatedWith != null && !colocatedWith.isEmpty()) {
-        String[] listAllRegionPaths = dsMBean.listAllRegionPaths();
-        String foundRegionPath = null;
-        for (String regionPath : listAllRegionPaths) {
-          if (regionPath.equals(colocatedWith)) {
-            foundRegionPath = regionPath;
-            break;
-          }
-        }
-        if (foundRegionPath == null) {
-          throw new IllegalArgumentException(CliStrings.format(
-              CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
-              new Object[] {CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith}));
-        }
-        ManagementService mgmtService = ManagementService.getExistingManagementService(cache);
-        DistributedRegionMXBean distributedRegionMXBean =
-            mgmtService.getDistributedRegionMXBean(foundRegionPath);
-        String regionType = distributedRegionMXBean.getRegionType();
-        if (!(DataPolicy.PARTITION.toString().equals(regionType)
-            || DataPolicy.PERSISTENT_PARTITION.toString().equals(regionType))) {
-          throw new IllegalArgumentException(CliStrings.format(
-              CliStrings.CREATE_REGION__MSG__COLOCATEDWITH_REGION_0_IS_NOT_PARTITIONEDREGION,
-              new Object[] {colocatedWith}));
-        }
-      }
-      if (partitionArgs.isSetPRLocalMaxMemory()) {
-        int prLocalMaxMemory = partitionArgs.getPrLocalMaxMemory();
-        if (prLocalMaxMemory < 0) {
-          throw new IllegalArgumentException(
-              LocalizedStrings.AttributesFactory_PARTITIONATTRIBUTES_LOCALMAXMEMORY_MUST_NOT_BE_NEGATIVE
-                  .toLocalizedString());
-        }
-      }
-      if (partitionArgs.isSetPRTotalMaxMemory()) {
-        long prTotalMaxMemory = partitionArgs.getPrTotalMaxMemory();
-        if (prTotalMaxMemory <= 0) {
-          throw new IllegalArgumentException(
-              LocalizedStrings.AttributesFactory_TOTAL_SIZE_OF_PARTITION_REGION_MUST_BE_0
-                  .toLocalizedString());
-        }
-      }
-      if (partitionArgs.isSetPRRedundantCopies()) {
-        int prRedundantCopies = partitionArgs.getPrRedundantCopies();
-        switch (prRedundantCopies) {
-          case 0:
-          case 1:
-          case 2:
-          case 3:
-            break;
-          default:
-            throw new IllegalArgumentException(CliStrings.format(
-                CliStrings.CREATE_REGION__MSG__REDUNDANT_COPIES_SHOULD_BE_ONE_OF_0123,
-                new Object[] {prRedundantCopies}));
-        }
-      }
-    }
-
-    String keyConstraint = regionFunctionArgs.getKeyConstraint();
-    if (keyConstraint != null && !isClassNameValid(keyConstraint)) {
-      throw new IllegalArgumentException(CliStrings.format(
-          CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_KEYCONSTRAINT_0_IS_INVALID,
-          new Object[] {keyConstraint}));
-    }
-
-    String valueConstraint = regionFunctionArgs.getValueConstraint();
-    if (valueConstraint != null && !isClassNameValid(valueConstraint)) {
-      throw new IllegalArgumentException(CliStrings.format(
-          CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_VALUECONSTRAINT_0_IS_INVALID,
-          new Object[] {valueConstraint}));
-    }
-
-    Set<String> cacheListeners = regionFunctionArgs.getCacheListeners();
-    if (cacheListeners != null && !cacheListeners.isEmpty()) {
-      for (String cacheListener : cacheListeners) {
-        if (!isClassNameValid(cacheListener)) {
-          throw new IllegalArgumentException(CliStrings.format(
-              CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
-              new Object[] {cacheListener}));
-        }
-      }
-    }
-
-    String cacheLoader = regionFunctionArgs.getCacheLoader();
-    if (cacheLoader != null && !isClassNameValid(cacheLoader)) {
-      throw new IllegalArgumentException(CliStrings.format(
-          CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
-          new Object[] {cacheLoader}));
-    }
-
-    String cacheWriter = regionFunctionArgs.getCacheWriter();
-    if (cacheWriter != null && !isClassNameValid(cacheWriter)) {
-      throw new IllegalArgumentException(CliStrings.format(
-          CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
-          new Object[] {cacheWriter}));
-    }
-
-    Set<String> gatewaySenderIds = regionFunctionArgs.getGatewaySenderIds();
-    if (gatewaySenderIds != null && !gatewaySenderIds.isEmpty()) {
-      String[] gatewaySenders = dsMBean.listGatewaySenders();
-      if (gatewaySenders.length == 0) {
-        throw new IllegalArgumentException(
-            CliStrings.CREATE_REGION__MSG__NO_GATEWAYSENDERS_IN_THE_SYSTEM);
-      } else {
-        List<String> gatewaySendersList = new ArrayList<>(Arrays.asList(gatewaySenders));
-        gatewaySenderIds = new HashSet<>(gatewaySenderIds);
-        gatewaySenderIds.removeAll(gatewaySendersList);
-        if (!gatewaySenderIds.isEmpty()) {
-          throw new IllegalArgumentException(CliStrings.format(
-              CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_GATEWAYSENDER_ID_UNKNOWN_0,
-              new Object[] {gatewaySenderIds}));
-        }
-      }
-    }
-
-    if (regionFunctionArgs.isSetConcurrencyLevel()) {
-      int concurrencyLevel = regionFunctionArgs.getConcurrencyLevel();
-      if (concurrencyLevel < 0) {
-        throw new IllegalArgumentException(CliStrings.format(
-            CliStrings.CREATE_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_CONCURRENCYLEVEL_0_IS_NOT_VALID,
-            new Object[] {concurrencyLevel}));
-      }
-    }
-
-    String diskStore = regionFunctionArgs.getDiskStore();
-    if (diskStore != null) {
-      RegionShortcut regionShortcut = regionFunctionArgs.getRegionShortcut();
-      if (regionShortcut != null && !PERSISTENT_OVERFLOW_SHORTCUTS.contains(regionShortcut)) {
-        String subMessage =
-            LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
-        String message = subMessage + ". "
-            + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0,
-                new Object[] {String.valueOf(PERSISTENT_OVERFLOW_SHORTCUTS)});
-
-        throw new IllegalArgumentException(message);
-      }
-
-      RegionAttributes<?, ?> regionAttributes = regionFunctionArgs.getRegionAttributes();
-      if (regionAttributes != null && !regionAttributes.getDataPolicy().withPersistence()) {
-        String subMessage =
-            LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
-        String message = subMessage + ". "
-            + CliStrings.format(
-                CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FROM_REGION_0_IS_NOT_WITH_PERSISTENCE,
-                new Object[] {String.valueOf(regionFunctionArgs.getUseAttributesFrom())});
-
-        throw new IllegalArgumentException(message);
-      }
-
-      if (!diskStoreExists(cache, diskStore)) {
-        throw new IllegalArgumentException(CliStrings.format(
-            CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_DISKSTORE_UNKNOWN_DISKSTORE_0,
-            new Object[] {diskStore}));
-      }
-    }
-
-    RegionFunctionArgs.ExpirationAttrs entryExpirationIdleTime =
-        regionFunctionArgs.getEntryExpirationIdleTime();
-    RegionFunctionArgs.ExpirationAttrs entryExpirationTTL =
-        regionFunctionArgs.getEntryExpirationTTL();
-    RegionFunctionArgs.ExpirationAttrs regionExpirationIdleTime =
-        regionFunctionArgs.getRegionExpirationIdleTime();
-    RegionFunctionArgs.ExpirationAttrs regionExpirationTTL =
-        regionFunctionArgs.getRegionExpirationTTL();
-
-    if ((!regionFunctionArgs.isSetStatisticsEnabled() || !regionFunctionArgs.isStatisticsEnabled())
-        && (entryExpirationIdleTime != null || entryExpirationTTL != null
-            || regionExpirationIdleTime != null || regionExpirationTTL != null)) {
-      String message = LocalizedStrings.AttributesFactory_STATISTICS_MUST_BE_ENABLED_FOR_EXPIRATION
-          .toLocalizedString();
-      throw new IllegalArgumentException(message + ".");
-    }
-
-    boolean compressorFailure = false;
-    if (regionFunctionArgs.isSetCompressor()) {
-      String compressorClassName = regionFunctionArgs.getCompressor();
-      Object compressor = null;
-      try {
-        Class<?> compressorClass = ClassPathLoader.getLatest().forName(compressorClassName);
-        compressor = compressorClass.newInstance();
-      } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
-        compressorFailure = true;
-      }
-
-      if (compressorFailure || !(compressor instanceof Compressor)) {
-        throw new IllegalArgumentException(
-            CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_COMPRESSOR,
-                new Object[] {regionFunctionArgs.getCompressor()}));
-      }
-    }
-
-    if (regionFunctionArgs.hasPartitionAttributes()) {
-      if (regionFunctionArgs.isPartitionResolverSet()) {
-        String partitionResolverClassName = regionFunctionArgs.getPartitionResolver();
-        try {
-          Class<PartitionResolver> resolverClass = (Class<PartitionResolver>) ClassPathLoader
-              .getLatest().forName(partitionResolverClassName);
-          PartitionResolver partitionResolver = resolverClass.newInstance();
-        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
-          throw new IllegalArgumentException(
-              CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER,
-                  new Object[] {regionFunctionArgs.getPartitionResolver()}),
-              e);
-        }
-      }
-    }
-  }
-
-  private boolean diskStoreExists(InternalCache cache, String diskStoreName) {
-    ManagementService managementService = ManagementService.getExistingManagementService(cache);
-    DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
-    Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
-
-    Set<Entry<String, String[]>> entrySet = diskstore.entrySet();
-
-    for (Entry<String, String[]> entry : entrySet) {
-      String[] value = entry.getValue();
-      if (CliUtil.contains(value, diskStoreName)) {
-        return true;
-      }
-    }
-
-    return false;
-  }
-
-  private static <K, V> FetchRegionAttributesFunctionResult<K, V> getRegionAttributes(
-      InternalCache cache, String regionPath) {
-    if (!isClusterWideSameConfig(cache, regionPath)) {
-      throw new IllegalStateException(CliStrings.format(
-          CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FORM_REGIONS_EXISTS_BUT_DIFFERENT_SCOPE_OR_DATAPOLICY_USE_DESCRIBE_REGION_FOR_0,
-          regionPath));
-    }
-    FetchRegionAttributesFunctionResult<K, V> attributes = null;
-
-    // First check whether the region exists on a this manager, if yes then no
-    // need to use FetchRegionAttributesFunction to fetch RegionAttributes
-    try {
-      attributes = FetchRegionAttributesFunction.getRegionAttributes(regionPath);
-    } catch (IllegalArgumentException e) {
-      /* region doesn't exist on the manager */
-    }
-
-    if (attributes == null) {
-      // find first member which has the region
-      Set<DistributedMember> regionAssociatedMembers =
-          CliUtil.getRegionAssociatedMembers(regionPath, cache, false);
-      if (regionAssociatedMembers != null && !regionAssociatedMembers.isEmpty()) {
-        DistributedMember distributedMember = regionAssociatedMembers.iterator().next();
-        ResultCollector<?, ?> resultCollector = CliUtil
-            .executeFunction(FetchRegionAttributesFunction.INSTANCE, regionPath, distributedMember);
-        List<?> resultsList = (List<?>) resultCollector.getResult();
-
-        if (resultsList != null && !resultsList.isEmpty()) {
-          for (Object object : resultsList) {
-            if (object instanceof IllegalArgumentException) {
-              throw (IllegalArgumentException) object;
-            } else if (object instanceof Throwable) {
-              Throwable th = (Throwable) object;
-              LogWrapper.getInstance().info(CliUtil.stackTraceAsString((th)));
-              throw new IllegalArgumentException(CliStrings.format(
-                  CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1,
-                  new Object[] {regionPath, th.getMessage()}));
-            } else { // has to be RegionAttributes
-              @SuppressWarnings("unchecked") // to avoid warning :(
-              FetchRegionAttributesFunctionResult<K, V> regAttr =
-                  ((FetchRegionAttributesFunctionResult<K, V>) object);
-              if (attributes == null) {
-                attributes = regAttr;
-                break;
-              } // attributes null check
-            } // not IllegalArgumentException or other throwable
-          } // iterate over list - there should be only one result in the list
-        } // result list is not null or empty
-      } // regionAssociatedMembers is not-empty
-    } // attributes are null because do not exist on local member
-
-    return attributes;
-  }
-
-  private static boolean isClusterWideSameConfig(InternalCache cache, String regionPath) {
-    ManagementService managementService = ManagementService.getExistingManagementService(cache);
-
-    DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
-
-    Set<DistributedMember> allMembers = CliUtil.getAllNormalMembers(cache);
-
-    RegionAttributesData regionAttributesToValidateAgainst = null;
-    for (DistributedMember distributedMember : allMembers) {
-      ObjectName regionObjectName;
-      try {
-        regionObjectName = dsMXBean
-            .fetchRegionObjectName(CliUtil.getMemberNameOrId(distributedMember), regionPath);
-        RegionMXBean regionMBean =
-            managementService.getMBeanInstance(regionObjectName, RegionMXBean.class);
-        RegionAttributesData regionAttributes = regionMBean.listRegionAttributes();
-
-        if (regionAttributesToValidateAgainst == null) {
-          regionAttributesToValidateAgainst = regionAttributes;
-        } else if (!(regionAttributesToValidateAgainst.getScope()
-            .equals(regionAttributes.getScope())
-            || regionAttributesToValidateAgainst.getDataPolicy()
-                .equals(regionAttributes.getDataPolicy()))) {
-          return false;
-        }
-      } catch (Exception e) {
-        // ignore
-      }
-    }
-
-    return true;
-  }
-
-  private boolean isClassNameValid(String fqcn) {
-    if (fqcn.isEmpty()) {
-      return true;
-    }
-
-    String regex = "([\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*";
-    return Pattern.matches(regex, fqcn);
-  }
-
-  @CliCommand(value = {CliStrings.DESTROY_REGION}, help = CliStrings.DESTROY_REGION__HELP)
-  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
-  @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
-  public Result destroyRegion(
-      @CliOption(key = CliStrings.DESTROY_REGION__REGION, optionContext = ConverterHint.REGION_PATH,
-          mandatory = true, help = CliStrings.DESTROY_REGION__REGION__HELP) String regionPath) {
-
-    if (regionPath == null) {
-      return ResultBuilder
-          .createInfoResult(CliStrings.DESTROY_REGION__MSG__SPECIFY_REGIONPATH_TO_DESTROY);
-    }
-
-    if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
-      return ResultBuilder.createInfoResult(CliStrings.format(
-          CliStrings.DESTROY_REGION__MSG__REGIONPATH_0_NOT_VALID, new Object[] {regionPath}));
-    }
-
-    Result result;
-    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-    try {
-      InternalCache cache = getCache();
-      ManagementService managementService = ManagementService.getExistingManagementService(cache);
-      String regionPathToUse = regionPath;
-
-      if (!regionPathToUse.startsWith(Region.SEPARATOR)) {
-        regionPathToUse = Region.SEPARATOR + regionPathToUse;
-      }
-
-      Set<DistributedMember> regionMembersList =
-          findMembersForRegion(cache, managementService, regionPathToUse);
-
-      if (regionMembersList.size() == 0) {
-        return ResultBuilder.createUserErrorResult(
-            CliStrings.format(CliStrings.DESTROY_REGION__MSG__COULD_NOT_FIND_REGIONPATH_0_IN_GEODE,
-                regionPath, "jmx-manager-update-rate milliseconds"));
-      }
-
-      CliFunctionResult destroyRegionResult;
-
-      ResultCollector<?, ?> resultCollector =
-          CliUtil.executeFunction(RegionDestroyFunction.INSTANCE, regionPath, regionMembersList);
-      List<CliFunctionResult> resultsList = (List<CliFunctionResult>) resultCollector.getResult();
-      String message =
-          CliStrings.format(CliStrings.DESTROY_REGION__MSG__REGION_0_1_DESTROYED, regionPath, "");
-
-      // Only if there is an error is this set to false
-      boolean isRegionDestroyed = true;
-      for (CliFunctionResult aResultsList : resultsList) {
-        destroyRegionResult = aResultsList;
-        if (destroyRegionResult.isSuccessful()) {
-          xmlEntity.set(destroyRegionResult.getXmlEntity());
-        } else if (destroyRegionResult.getThrowable() != null) {
-          Throwable t = destroyRegionResult.getThrowable();
-          LogWrapper.getInstance().info(t.getMessage(), t);
-          message = CliStrings.format(
-              CliStrings.DESTROY_REGION__MSG__ERROR_OCCURRED_WHILE_DESTROYING_0_REASON_1,
-              regionPath, t.getMessage());
-          isRegionDestroyed = false;
-        } else {
-          message = CliStrings.format(
-              CliStrings.DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1,
-              regionPath, destroyRegionResult.getMessage());
-          isRegionDestroyed = false;
-        }
-      }
-      if (isRegionDestroyed) {
-        result = ResultBuilder.createInfoResult(message);
-      } else {
-        result = ResultBuilder.createUserErrorResult(message);
-      }
-    } catch (IllegalStateException e) {
-      result = ResultBuilder.createUserErrorResult(CliStrings.format(
-          CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, regionPath,
-          e.getMessage()));
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(CliStrings.format(
-          CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, regionPath,
-          e.getMessage()));
-    }
-
-    if (xmlEntity.get() != null) {
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null));
-    }
-
-    return result;
-  }
-
-  private Set<DistributedMember> findMembersForRegion(InternalCache cache,
-      ManagementService managementService, String regionPath) {
-    Set<DistributedMember> membersList = new HashSet<>();
-    Set<String> regionMemberIds = new HashSet<>();
-    MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-
-    // needs to be escaped with quotes if it contains a hyphen
-    if (regionPath.contains("-")) {
-      regionPath = "\"" + regionPath + "\"";
-    }
-
-    String queryExp =
-        MessageFormat.format(MBeanJMXAdapter.OBJECTNAME__REGION_MXBEAN, regionPath, "*");
-
-    try {
-      ObjectName queryExpON = new ObjectName(queryExp);
-      Set<ObjectName> queryNames = mbeanServer.queryNames(null, queryExpON);
-      if (queryNames == null || queryNames.isEmpty()) {
-        return membersList; // protects against null pointer exception below
-      }
-
-      boolean addedOneRemote = false;
-      for (ObjectName regionMBeanObjectName : queryNames) {
-        try {
-          RegionMXBean regionMXBean =
-              managementService.getMBeanInstance(regionMBeanObjectName, RegionMXBean.class);
-          if (regionMXBean != null) {
-            RegionAttributesData regionAttributes = regionMXBean.listRegionAttributes();
-            String scope = regionAttributes.getScope();
-            // For Scope.LOCAL regions we need to identify each hosting member, but for
-            // other scopes we just need a single member as the region destroy will be
-            // propagated.
-            if (Scope.LOCAL.equals(Scope.fromString(scope))) {
-              regionMemberIds.add(regionMXBean.getMember());
-            } else {
-              if (!addedOneRemote) {
-                regionMemberIds.add(regionMXBean.getMember());
-                addedOneRemote = true;
-              }
-            }
-          }
-        } catch (ClassCastException e) {
-          LogWriter logger = cache.getLogger();
-          if (logger.finerEnabled()) {
-            logger.finer(regionMBeanObjectName + " is not a " + RegionMXBean.class.getSimpleName(),
-                e);
-          }
-        }
-      }
-
-      if (!regionMemberIds.isEmpty()) {
-        membersList = getMembersByIds(cache, regionMemberIds);
-      }
-    } catch (MalformedObjectNameException | NullPointerException e) {
-      LogWrapper.getInstance().info(e.getMessage(), e);
-    }
-
-    return membersList;
-  }
-
-  private Set<DistributedMember> getMembersByIds(InternalCache cache, Set<String> memberIds) {
-    Set<DistributedMember> foundMembers = Collections.emptySet();
-    if (memberIds != null && !memberIds.isEmpty()) {
-      foundMembers = new HashSet<>();
-      Set<DistributedMember> allNormalMembers = CliUtil.getAllNormalMembers(cache);
-
-      for (String memberId : memberIds) {
-        for (DistributedMember distributedMember : allNormalMembers) {
-          if (memberId.equals(distributedMember.getId())
-              || memberId.equals(distributedMember.getName())) {
-            foundMembers.add(distributedMember);
-          }
-        }
-      }
-    }
-    return foundMembers;
-  }
-
-  private boolean isPersistentShortcut(RegionShortcut shortcut) {
-    return shortcut == RegionShortcut.LOCAL_PERSISTENT
-        || shortcut == RegionShortcut.LOCAL_PERSISTENT_OVERFLOW
-        || shortcut == RegionShortcut.PARTITION_PERSISTENT
-        || shortcut == RegionShortcut.PARTITION_PERSISTENT_OVERFLOW
-        || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT
-        || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW
-        || shortcut == RegionShortcut.REPLICATE_PERSISTENT
-        || shortcut == RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW;
-  }
-
-  private boolean isAttributePersistent(RegionAttributes attributes) {
-    return attributes != null && attributes.getDataPolicy() != null
-        && attributes.getDataPolicy().toString().contains("PERSISTENT");
-  }
-}


[19/47] geode git commit: GEODE-3436: Restore refactoring of Refactoring MiscellaneousCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
deleted file mode 100644
index 1415bc6..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
+++ /dev/null
@@ -1,1926 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.zip.DataFormatException;
-import java.util.zip.GZIPInputStream;
-
-import javax.management.ObjectName;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.logging.log4j.Logger;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.LogWriter;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.Function;
-import org.apache.geode.cache.execute.FunctionException;
-import org.apache.geode.cache.execute.FunctionService;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.distributed.internal.deadlock.DeadlockDetector;
-import org.apache.geode.distributed.internal.deadlock.Dependency;
-import org.apache.geode.distributed.internal.deadlock.DependencyGraph;
-import org.apache.geode.distributed.internal.deadlock.GemFireDeadlockDetector;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.internal.logging.log4j.LogLevel;
-import org.apache.geode.management.CacheServerMXBean;
-import org.apache.geode.management.DistributedRegionMXBean;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.JVMMetrics;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.MemberMXBean;
-import org.apache.geode.management.RegionMXBean;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.ManagementConstants;
-import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.CliUtil.DeflaterInflaterData;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.GfshParser;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.domain.StackTracesPerMember;
-import org.apache.geode.management.internal.cli.functions.ChangeLogLevelFunction;
-import org.apache.geode.management.internal.cli.functions.GarbageCollectionFunction;
-import org.apache.geode.management.internal.cli.functions.GetStackTracesFunction;
-import org.apache.geode.management.internal.cli.functions.NetstatFunction;
-import org.apache.geode.management.internal.cli.functions.NetstatFunction.NetstatFunctionArgument;
-import org.apache.geode.management.internal.cli.functions.NetstatFunction.NetstatFunctionResult;
-import org.apache.geode.management.internal.cli.functions.ShutDownFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.ResultData;
-import org.apache.geode.management.internal.cli.result.ResultDataException;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-
-/**
- * @since GemFire 7.0
- */
-public class MiscellaneousCommands implements GfshCommand {
-
-  public static final String NETSTAT_FILE_REQUIRED_EXTENSION = ".txt";
-  public final static String DEFAULT_TIME_OUT = "10";
-  private final static Logger logger = LogService.getLogger();
-
-  private final GetStackTracesFunction getStackTracesFunction = new GetStackTracesFunction();
-
-  public void shutdownNode(final long timeout, final Set<DistributedMember> includeMembers)
-      throws TimeoutException, InterruptedException, ExecutionException {
-    ExecutorService exec = Executors.newSingleThreadExecutor();
-    try {
-      final Function shutDownFunction = new ShutDownFunction();
-
-      logger.info("Gfsh executing shutdown on members " + includeMembers);
-
-      Callable<String> shutdownNodes = new Callable<String>() {
-
-        @Override
-        public String call() {
-          try {
-            Execution execution = FunctionService.onMembers(includeMembers);
-            execution.execute(shutDownFunction);
-          } catch (FunctionException functionEx) {
-            // Expected Exception as the function is shutting down the target members and the result
-            // collector will get member departed exception
-          }
-          return "SUCCESS";
-        }
-      };
-
-      Future<String> result = exec.submit(shutdownNodes);
-      result.get(timeout, TimeUnit.MILLISECONDS);
-
-    } catch (TimeoutException te) {
-      logger.error("TimeoutException in shutting down members." + includeMembers);
-      throw te;
-    } catch (InterruptedException e) {
-      logger.error("InterruptedException in shutting down members." + includeMembers);
-      throw e;
-    } catch (ExecutionException e) {
-      logger.error("ExecutionException in shutting down members." + includeMembers);
-      throw e;
-    } finally {
-      exec.shutdownNow();
-    }
-  }
-
-  @CliCommand(value = CliStrings.SHUTDOWN, help = CliStrings.SHUTDOWN__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_LIFECYCLE},
-      interceptor = "org.apache.geode.management.internal.cli.commands.MiscellaneousCommands$Interceptor")
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
-  public Result shutdown(
-      @CliOption(key = CliStrings.SHUTDOWN__TIMEOUT, unspecifiedDefaultValue = DEFAULT_TIME_OUT,
-          help = CliStrings.SHUTDOWN__TIMEOUT__HELP) int userSpecifiedTimeout,
-      @CliOption(key = CliStrings.INCLUDE_LOCATORS, unspecifiedDefaultValue = "false",
-          help = CliStrings.INCLUDE_LOCATORS_HELP) boolean shutdownLocators) {
-    try {
-
-      if (userSpecifiedTimeout < Integer.parseInt(DEFAULT_TIME_OUT)) {
-        return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__IMPROPER_TIMEOUT);
-      }
-
-      // convert to milliseconds
-      long timeout = userSpecifiedTimeout * 1000;
-
-      InternalCache cache = getCache();
-
-      int numDataNodes = CliUtil.getAllNormalMembers(cache).size();
-
-      Set<DistributedMember> locators = CliUtil.getAllMembers(cache);
-
-      Set<DistributedMember> dataNodes = CliUtil.getAllNormalMembers(cache);
-
-      locators.removeAll(dataNodes);
-
-      if (!shutdownLocators && numDataNodes == 0) {
-        return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__NO_DATA_NODE_FOUND);
-      }
-
-      String managerName = cache.getJmxManagerAdvisor().getDistributionManager().getId().getId();
-
-      final DistributedMember manager = CliUtil.getDistributedMemberByNameOrId(managerName);
-
-      dataNodes.remove(manager);
-
-      // shut down all data members excluding this manager if manager is a data node
-      long timeElapsed = shutDownNodeWithTimeOut(timeout, dataNodes);
-      timeout = timeout - timeElapsed;
-
-      // shut down locators one by one
-      if (shutdownLocators) {
-        if (manager == null) {
-          return ResultBuilder.createUserErrorResult(CliStrings.SHUTDOWN__MSG__MANAGER_NOT_FOUND);
-        }
-
-        // remove current locator as that would get shutdown last
-        if (locators.contains(manager)) {
-          locators.remove(manager);
-        }
-
-        for (DistributedMember locator : locators) {
-          Set<DistributedMember> lsSet = new HashSet<>();
-          lsSet.add(locator);
-          long elapsedTime = shutDownNodeWithTimeOut(timeout, lsSet);
-          timeout = timeout - elapsedTime;
-        }
-      }
-
-      if (locators.contains(manager) && !shutdownLocators) { // This means manager is a locator and
-        // shutdownLocators is false. Hence we
-        // should not stop the manager
-        return ResultBuilder.createInfoResult("Shutdown is triggered");
-      }
-      // now shut down this manager
-      Set<DistributedMember> mgrSet = new HashSet<>();
-      mgrSet.add(manager);
-      // No need to check further timeout as this is the last node we will be
-      // shutting down
-      shutDownNodeWithTimeOut(timeout, mgrSet);
-
-    } catch (TimeoutException tex) {
-      return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN_TIMEDOUT);
-    } catch (Exception ex) {
-      ex.printStackTrace();
-      return ResultBuilder.createUserErrorResult(ex.getMessage());
-    }
-
-    // @TODO. List all the nodes which could be successfully shutdown
-    return ResultBuilder.createInfoResult("Shutdown is triggered");
-  }
-
-  /**
-   * @param timeout user specified timeout
-   * @param nodesToBeStopped list of nodes to be stopped
-   * @return Elapsed time to shutdown the given nodes;
-   */
-  private long shutDownNodeWithTimeOut(long timeout, Set<DistributedMember> nodesToBeStopped)
-      throws TimeoutException, InterruptedException, ExecutionException {
-
-    long shutDownTimeStart = System.currentTimeMillis();
-    shutdownNode(timeout, nodesToBeStopped);
-
-    long shutDownTimeEnd = System.currentTimeMillis();
-
-    long timeElapsed = shutDownTimeEnd - shutDownTimeStart;
-
-    if (timeElapsed > timeout || Boolean.getBoolean("ThrowTimeoutException")) {
-      // The second check for ThrowTimeoutException is a test hook
-      throw new TimeoutException();
-    }
-    return timeElapsed;
-  }
-
-  /**
-   * Interceptor used by gfsh to intercept execution of shutdownall.
-   */
-  public static class Interceptor extends AbstractCliAroundInterceptor {
-    @Override
-    public Result preExecution(GfshParseResult parseResult) {
-
-      // This hook is for testing purpose only.
-      if (Boolean.getBoolean(CliStrings.IGNORE_INTERCEPTORS)) {
-        return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__SHUTDOWN_ENTIRE_DS);
-      }
-
-      Response response = readYesNo(CliStrings.SHUTDOWN__MSG__WARN_USER, Response.YES);
-      if (response == Response.NO) {
-        return ResultBuilder
-            .createShellClientAbortOperationResult(CliStrings.SHUTDOWN__MSG__ABORTING_SHUTDOWN);
-      } else {
-        return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__SHUTDOWN_ENTIRE_DS);
-      }
-    }
-  }
-
-  @CliCommand(value = CliStrings.GC, help = CliStrings.GC__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
-  public Result gc(
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.GC__GROUP__HELP) String[] groups,
-      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
-          help = CliStrings.GC__MEMBER__HELP) String memberId) {
-    InternalCache cache = getCache();
-    Result result;
-    CompositeResultData gcResultTable = ResultBuilder.createCompositeResultData();
-    TabularResultData resultTable = gcResultTable.addSection().addTable("Table1");
-    String headerText = "GC Summary";
-    resultTable.setHeader(headerText);
-    Set<DistributedMember> dsMembers = new HashSet<>();
-    if (memberId != null && memberId.length() > 0) {
-      DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberId);
-      if (member == null) {
-        return ResultBuilder
-            .createGemFireErrorResult(memberId + CliStrings.GC__MSG__MEMBER_NOT_FOUND);
-      }
-      dsMembers.add(member);
-      result = executeAndBuildResult(resultTable, dsMembers);
-    } else if (groups != null && groups.length > 0) {
-      for (String group : groups) {
-        dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(group));
-      }
-      result = executeAndBuildResult(resultTable, dsMembers);
-
-    } else {
-      // gc on entire cluster
-      // exclude locators
-      dsMembers = CliUtil.getAllNormalMembers(cache);
-      result = executeAndBuildResult(resultTable, dsMembers);
-
-    }
-    return result;
-  }
-
-  Result executeAndBuildResult(TabularResultData resultTable, Set<DistributedMember> dsMembers) {
-    try {
-      List<?> resultList;
-      Function garbageCollectionFunction = new GarbageCollectionFunction();
-      resultList =
-          (List<?>) CliUtil.executeFunction(garbageCollectionFunction, null, dsMembers).getResult();
-
-      for (Object object : resultList) {
-        if (object instanceof Exception) {
-          LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
-              ((Throwable) object));
-          continue;
-        } else if (object instanceof Throwable) {
-          LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
-              ((Throwable) object));
-          continue;
-        }
-
-        if (object != null) {
-          if (object instanceof String) {
-            // unexpected exception string - cache may be closed or something
-            return ResultBuilder.createUserErrorResult((String) object);
-          } else {
-            Map<String, String> resultMap = (Map<String, String>) object;
-            toTabularResultData(resultTable, resultMap.get("MemberId"),
-                resultMap.get("HeapSizeBeforeGC"), resultMap.get("HeapSizeAfterGC"),
-                resultMap.get("TimeSpentInGC"));
-          }
-        } else {
-          LogWrapper.getInstance().fine("ResultMap was null ");
-        }
-      }
-    } catch (Exception e) {
-      String stack = CliUtil.stackTraceAsString(e);
-      LogWrapper.getInstance().info("GC exception is " + stack);
-      return ResultBuilder.createGemFireErrorResult(e.getMessage() + ": " + stack);
-    }
-    return ResultBuilder.buildResult(resultTable);
-  }
-
-  protected void toTabularResultData(TabularResultData table, String memberId,
-      String heapSizeBefore, String heapSizeAfter, String timeTaken) {
-    table.accumulate(CliStrings.GC__MSG__MEMBER_NAME, memberId);
-    table.accumulate(CliStrings.GC__MSG__HEAP_SIZE_BEFORE_GC, heapSizeBefore);
-    table.accumulate(CliStrings.GC__MSG__HEAP_SIZE_AFTER_GC, heapSizeAfter);
-    table.accumulate(CliStrings.GC__MSG__TOTAL_TIME_IN_GC, timeTaken);
-  }
-
-  @CliCommand(value = CliStrings.NETSTAT, help = CliStrings.NETSTAT__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  // TODO : Verify the auto-completion for multiple values.
-  public Result netstat(
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          optionContext = ConverterHint.ALL_MEMBER_IDNAME,
-          help = CliStrings.NETSTAT__MEMBER__HELP) String[] members,
-      @CliOption(key = CliStrings.GROUP, optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.NETSTAT__GROUP__HELP) String group,
-      @CliOption(key = CliStrings.NETSTAT__FILE,
-          help = CliStrings.NETSTAT__FILE__HELP) String saveAs,
-      @CliOption(key = CliStrings.NETSTAT__WITHLSOF, specifiedDefaultValue = "true",
-          unspecifiedDefaultValue = "false",
-          help = CliStrings.NETSTAT__WITHLSOF__HELP) boolean withlsof) {
-    Result result;
-
-    Map<String, DistributedMember> hostMemberMap = new HashMap<>();
-    Map<String, List<String>> hostMemberListMap = new HashMap<>();
-
-    try {
-      if (members != null && members.length > 0 && group != null) {
-        throw new IllegalArgumentException(
-            CliStrings.NETSTAT__MSG__ONLY_ONE_OF_MEMBER_OR_GROUP_SHOULD_BE_SPECIFIED);
-      }
-      StringBuilder resultInfo = new StringBuilder();
-
-      // Execute for remote members whose id or name matches
-      InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
-
-      if (members != null) {
-        Set<String> notFoundMembers = new HashSet<>();
-        for (String memberIdOrName : members) {
-          Set<DistributedMember> membersToExecuteOn = CliUtil.getAllMembers(system);
-          boolean memberFound = false;
-          for (DistributedMember distributedMember : membersToExecuteOn) {
-            String memberName = distributedMember.getName();
-            String memberId = distributedMember.getId();
-            if (memberName.equals(memberIdOrName) || memberId.equals(memberIdOrName)) {
-              buildMaps(hostMemberMap, hostMemberListMap, memberIdOrName, distributedMember);
-
-              memberFound = true;
-              break;
-            }
-          }
-          if (!memberFound) {
-            notFoundMembers.add(memberIdOrName);
-          }
-        }
-        // if there are not found members, it's probably unknown member or member has departed
-        if (!notFoundMembers.isEmpty()) {
-          throw new IllegalArgumentException(
-              CliStrings.format(CliStrings.NETSTAT__MSG__COULD_NOT_FIND_MEMBERS_0,
-                  new Object[] {CliUtil.collectionToString(notFoundMembers, -1)}));
-        }
-      } else {
-        Set<DistributedMember> membersToExecuteOn;
-        if (group != null) {
-          membersToExecuteOn = system.getGroupMembers(group);
-        } else {
-          // consider all members
-          membersToExecuteOn = CliUtil.getAllMembers(system);
-        }
-
-        for (DistributedMember distributedMember : membersToExecuteOn) {
-          String memberName = distributedMember.getName();
-          String memberId = distributedMember.getId();
-          String memberIdOrName =
-              memberName != null && !memberName.isEmpty() ? memberName : memberId;
-
-          buildMaps(hostMemberMap, hostMemberListMap, memberIdOrName, distributedMember);
-        }
-      }
-
-      String lineSeparatorToUse;
-      lineSeparatorToUse = CommandExecutionContext.getShellLineSeparator();
-      if (lineSeparatorToUse == null) {
-        lineSeparatorToUse = GfshParser.LINE_SEPARATOR;
-      }
-      NetstatFunctionArgument nfa = new NetstatFunctionArgument(lineSeparatorToUse, withlsof);
-
-      if (!hostMemberMap.isEmpty()) {
-        Set<DistributedMember> membersToExecuteOn = new HashSet<>(hostMemberMap.values());
-        ResultCollector<?, ?> netstatResult =
-            CliUtil.executeFunction(NetstatFunction.INSTANCE, nfa, membersToExecuteOn);
-        List<?> resultList = (List<?>) netstatResult.getResult();
-        for (Object aResultList : resultList) {
-          NetstatFunctionResult netstatFunctionResult = (NetstatFunctionResult) aResultList;
-          DeflaterInflaterData deflaterInflaterData = netstatFunctionResult.getCompressedBytes();
-          try {
-            String remoteHost = netstatFunctionResult.getHost();
-            List<String> membersList = hostMemberListMap.get(remoteHost);
-            resultInfo.append(MessageFormat.format(netstatFunctionResult.getHeaderInfo(),
-                CliUtil.collectionToString(membersList, 120)));
-            DeflaterInflaterData uncompressedBytes = CliUtil.uncompressBytes(
-                deflaterInflaterData.getData(), deflaterInflaterData.getDataLength());
-            resultInfo.append(new String(uncompressedBytes.getData()));
-          } catch (DataFormatException e) {
-            resultInfo.append("Error in some data. Reason : " + e.getMessage());
-          }
-        }
-      }
-
-      InfoResultData resultData = ResultBuilder.createInfoResultData();
-      if (saveAs != null && !saveAs.isEmpty()) {
-        String saveToFile = saveAs;
-        if (!saveAs.endsWith(NETSTAT_FILE_REQUIRED_EXTENSION)) {
-          saveToFile = saveAs + NETSTAT_FILE_REQUIRED_EXTENSION;
-        }
-        resultData.addAsFile(saveToFile, resultInfo.toString(),
-            CliStrings.NETSTAT__MSG__SAVED_OUTPUT_IN_0, false); // Note: substitution for {0} will
-        // happen on client side.
-      } else {
-        resultData.addLine(resultInfo.toString());
-      }
-      result = ResultBuilder.buildResult(resultData);
-    } catch (IllegalArgumentException e) {
-      LogWrapper.getInstance()
-          .info(CliStrings.format(
-              CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
-              new Object[] {Arrays.toString(members)}));
-      result = ResultBuilder.createUserErrorResult(e.getMessage());
-    } catch (RuntimeException e) {
-      LogWrapper.getInstance()
-          .info(CliStrings.format(
-              CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
-              new Object[] {Arrays.toString(members)}), e);
-      result = ResultBuilder.createGemFireErrorResult(
-          CliStrings.format(CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
-              new Object[] {Arrays.toString(members)}));
-    } finally {
-      hostMemberMap.clear();
-      hostMemberListMap.clear();
-    }
-    return result;
-  }
-
-  private void buildMaps(Map<String, DistributedMember> hostMemberMap,
-      Map<String, List<String>> hostMemberListMap, String memberIdOrName,
-      DistributedMember distributedMember) {
-    String host = distributedMember.getHost();
-
-    // Maintain one member for a host - function execution purpose - once only for a host
-    if (!hostMemberMap.containsKey(host)) {
-      hostMemberMap.put(host, distributedMember);
-    }
-
-    // Maintain all members for a host - display purpose
-    List<String> list;
-    if (!hostMemberListMap.containsKey(host)) {
-      list = new ArrayList<>();
-      hostMemberListMap.put(host, list);
-    } else {
-      list = hostMemberListMap.get(host);
-    }
-    list.add(memberIdOrName);
-  }
-
-  @CliCommand(value = CliStrings.SHOW_DEADLOCK, help = CliStrings.SHOW_DEADLOCK__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result showDeadlock(@CliOption(key = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE,
-      help = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE__HELP,
-      mandatory = true) String filename) {
-
-    Result result;
-    try {
-      if (!filename.endsWith(".txt")) {
-        return ResultBuilder
-            .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".txt"));
-      }
-      InternalCache cache = getCache();
-
-      Set<DistributedMember> allMembers = CliUtil.getAllMembers(cache);
-      GemFireDeadlockDetector gfeDeadLockDetector = new GemFireDeadlockDetector(allMembers);
-      DependencyGraph dependencyGraph = gfeDeadLockDetector.find();
-      Collection<Dependency> deadlock = dependencyGraph.findCycle();
-      DependencyGraph deepest = null;
-      if (deadlock == null) {
-        deepest = dependencyGraph.findLongestCallChain();
-        if (deepest != null) {
-          deadlock = deepest.getEdges();
-        }
-      }
-      Set<Dependency> dependencies = (Set<Dependency>) dependencyGraph.getEdges();
-
-      InfoResultData resultData = ResultBuilder.createInfoResultData();
-
-      if (deadlock != null) {
-        if (deepest != null) {
-          resultData.addLine(CliStrings.SHOW_DEADLOCK__DEEPEST_FOUND);
-        } else {
-          resultData.addLine(CliStrings.SHOW_DEADLOCK__DEADLOCK__DETECTED);
-        }
-        resultData.addLine(DeadlockDetector.prettyFormat(deadlock));
-      } else {
-        resultData.addLine(CliStrings.SHOW_DEADLOCK__NO__DEADLOCK);
-      }
-      resultData.addAsFile(filename, DeadlockDetector.prettyFormat(dependencies),
-          MessageFormat.format(CliStrings.SHOW_DEADLOCK__DEPENDENCIES__REVIEW, filename), false);
-      result = ResultBuilder.buildResult(resultData);
-
-    } catch (Exception e) {
-      result = ResultBuilder
-          .createGemFireErrorResult(CliStrings.SHOW_DEADLOCK__ERROR + " : " + e.getMessage());
-    }
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.SHOW_LOG, help = CliStrings.SHOW_LOG_HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result showLog(
-      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
-          help = CliStrings.SHOW_LOG_MEMBER_HELP, mandatory = true) String memberNameOrId,
-      @CliOption(key = CliStrings.SHOW_LOG_LINE_NUM, unspecifiedDefaultValue = "0",
-          help = CliStrings.SHOW_LOG_LINE_NUM_HELP) int numberOfLines) {
-    Result result;
-    try {
-      InternalCache cache = getCache();
-      SystemManagementService service =
-          (SystemManagementService) ManagementService.getExistingManagementService(cache);
-      MemberMXBean bean;
-      DistributedMember memberToBeInvoked = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
-      if (memberToBeInvoked != null) {
-        String memberId = memberToBeInvoked.getId();
-
-        if (cache.getDistributedSystem().getDistributedMember().getId().equals(memberId)) {
-          bean = service.getMemberMXBean();
-        } else {
-          ObjectName objectName = service.getMemberMBeanName(memberToBeInvoked);
-          bean = service.getMBeanProxy(objectName, MemberMXBean.class);
-        }
-
-        if (numberOfLines > ManagementConstants.MAX_SHOW_LOG_LINES) {
-          numberOfLines = ManagementConstants.MAX_SHOW_LOG_LINES;
-        }
-        if (numberOfLines == 0 || numberOfLines < 0) {
-          numberOfLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES;
-        }
-        InfoResultData resultData = ResultBuilder.createInfoResultData();
-        if (bean != null) {
-          String log = bean.showLog(numberOfLines);
-          if (log != null) {
-            resultData.addLine(log);
-          } else {
-            resultData.addLine(CliStrings.SHOW_LOG_NO_LOG);
-          }
-        } else {
-          ErrorResultData errorResultData =
-              ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
-                  .addLine(memberNameOrId + CliStrings.SHOW_LOG_MSG_MEMBER_NOT_FOUND);
-          return (ResultBuilder.buildResult(errorResultData));
-        }
-
-        result = ResultBuilder.buildResult(resultData);
-      } else {
-        ErrorResultData errorResultData =
-            ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
-                .addLine(memberNameOrId + CliStrings.SHOW_LOG_MSG_MEMBER_NOT_FOUND);
-        return (ResultBuilder.buildResult(errorResultData));
-      }
-
-    } catch (Exception e) {
-      result = ResultBuilder
-          .createGemFireErrorResult(CliStrings.SHOW_LOG_ERROR + CliUtil.stackTraceAsString(e));
-    }
-    return result;
-  }
-
-  /**
-   * Current implementation supports writing it to a file and returning the location of the file
-   */
-  @CliCommand(value = CliStrings.EXPORT_STACKTRACE, help = CliStrings.EXPORT_STACKTRACE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result exportStackTrace(@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-      optionContext = ConverterHint.ALL_MEMBER_IDNAME,
-      help = CliStrings.EXPORT_STACKTRACE__HELP) String[] memberNameOrId,
-
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.GROUP) String[] group,
-
-      @CliOption(key = CliStrings.EXPORT_STACKTRACE__FILE,
-          help = CliStrings.EXPORT_STACKTRACE__FILE__HELP) String fileName,
-
-      @CliOption(key = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT,
-          unspecifiedDefaultValue = "false",
-          help = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT__HELP) boolean failIfFilePresent) {
-
-    Result result;
-    StringBuffer filePrefix = new StringBuffer("stacktrace");
-
-    if (fileName == null) {
-      fileName = filePrefix.append("_").append(System.currentTimeMillis()).toString();
-    }
-    final File outFile = new File(fileName);
-    try {
-      if (outFile.exists() && failIfFilePresent) {
-        return ResultBuilder.createShellClientErrorResult(CliStrings.format(
-            CliStrings.EXPORT_STACKTRACE__ERROR__FILE__PRESENT, outFile.getCanonicalPath()));
-      }
-
-
-      InternalCache cache = getCache();
-      InternalDistributedSystem ads = cache.getInternalDistributedSystem();
-
-      InfoResultData resultData = ResultBuilder.createInfoResultData();
-
-      Map<String, byte[]> dumps = new HashMap<>();
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(getStackTracesFunction, null, targetMembers);
-      ArrayList<Object> resultList = (ArrayList<Object>) rc.getResult();
-
-      for (Object resultObj : resultList) {
-        if (resultObj instanceof StackTracesPerMember) {
-          StackTracesPerMember stackTracePerMember = (StackTracesPerMember) resultObj;
-          dumps.put(stackTracePerMember.getMemberNameOrId(), stackTracePerMember.getStackTraces());
-        }
-      }
-
-      String filePath = writeStacksToFile(dumps, fileName);
-      resultData.addLine(CliStrings.format(CliStrings.EXPORT_STACKTRACE__SUCCESS, filePath));
-      resultData.addLine(CliStrings.EXPORT_STACKTRACE__HOST + ads.getDistributedMember().getHost());
-
-      result = ResultBuilder.buildResult(resultData);
-    } catch (IOException ex) {
-      result = ResultBuilder
-          .createGemFireErrorResult(CliStrings.EXPORT_STACKTRACE__ERROR + ex.getMessage());
-    }
-    return result;
-  }
-
-  /**
-   * Interceptor used by gfsh to intercept execution of shutdownall.
-   */
-  public static class ExportStackTraceInterceptor extends AbstractCliAroundInterceptor {
-    @Override
-    public Result preExecution(GfshParseResult parseResult) {
-
-      Map<String, String> paramValueMap = parseResult.getParamValueStrings();
-      String fileName = paramValueMap.get(CliStrings.EXPORT_STACKTRACE__FILE);
-
-      Response response = readYesNo(
-          CliStrings.format(CliStrings.EXPORT_STACKTRACE_WARN_USER, fileName), Response.YES);
-      if (response == Response.NO) {
-        return ResultBuilder
-            .createShellClientAbortOperationResult(CliStrings.EXPORT_STACKTRACE_MSG_ABORTING);
-      } else {
-        // we don't to show any info result
-        return ResultBuilder.createInfoResult("");
-      }
-    }
-  }
-
-  /***
-   * Writes the Stack traces member-wise to a text file
-   *
-   * @param dumps - Map containing key : member , value : zipped stack traces
-   * @param fileName - Name of the file to which the stack-traces are written to
-   * @return Canonical path of the file which contains the stack-traces
-   * @throws IOException
-   */
-  private String writeStacksToFile(Map<String, byte[]> dumps, String fileName) throws IOException {
-    String filePath;
-    PrintWriter ps;
-    File outputFile;
-
-    outputFile = new File(fileName);
-    try (OutputStream os = new FileOutputStream(outputFile)) {
-      ps = new PrintWriter(os);
-
-      for (Entry<String, byte[]> entry : dumps.entrySet()) {
-        ps.append("*** Stack-trace for member " + entry.getKey() + " ***");
-        ps.flush();
-        GZIPInputStream zipIn = new GZIPInputStream(new ByteArrayInputStream(entry.getValue()));
-        BufferedInputStream bin = new BufferedInputStream(zipIn);
-        byte[] buffer = new byte[10000];
-        int count;
-        while ((count = bin.read(buffer)) != -1) {
-          os.write(buffer, 0, count);
-        }
-        ps.append('\n');
-      }
-      ps.flush();
-      filePath = outputFile.getCanonicalPath();
-    }
-
-    return filePath;
-  }
-
-  @CliCommand(value = CliStrings.SHOW_METRICS, help = CliStrings.SHOW_METRICS__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_STATISTICS})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result showMetrics(
-      @CliOption(key = {CliStrings.MEMBER}, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
-          help = CliStrings.SHOW_METRICS__MEMBER__HELP) String memberNameOrId,
-      @CliOption(key = {CliStrings.SHOW_METRICS__REGION}, optionContext = ConverterHint.REGION_PATH,
-          help = CliStrings.SHOW_METRICS__REGION__HELP) String regionName,
-      @CliOption(key = {CliStrings.SHOW_METRICS__FILE},
-          help = CliStrings.SHOW_METRICS__FILE__HELP) String export_to_report_to,
-      @CliOption(key = {CliStrings.SHOW_METRICS__CACHESERVER__PORT},
-          help = CliStrings.SHOW_METRICS__CACHESERVER__PORT__HELP) String cacheServerPortString,
-      @CliOption(key = {CliStrings.SHOW_METRICS__CATEGORY},
-          help = CliStrings.SHOW_METRICS__CATEGORY__HELP) String[] categories) {
-
-    Result result;
-    try {
-
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        if (!export_to_report_to.endsWith(".csv")) {
-          return ResultBuilder
-              .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".csv"));
-        }
-      }
-      if (regionName != null && !regionName.isEmpty()) {
-
-        if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
-          return ResultBuilder
-              .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
-        }
-
-        // MBean names contain the forward slash
-        if (!regionName.startsWith("/")) {
-          regionName = "/" + regionName;
-        }
-
-        if (memberNameOrId == null || memberNameOrId.isEmpty()) {
-          result = ResultBuilder.buildResult(
-              getDistributedRegionMetrics(regionName, export_to_report_to, categories));
-        } else {
-          DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
-
-          if (member != null) {
-            result = ResultBuilder.buildResult(
-                getRegionMetricsFromMember(regionName, member, export_to_report_to, categories));
-          } else {
-            ErrorResultData erd = ResultBuilder.createErrorResultData();
-            erd.addLine(
-                CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId));
-            result = ResultBuilder.buildResult(erd);
-          }
-        }
-      } else if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
-
-        DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
-
-        if (member != null) {
-          int cacheServerPort = -1;
-          if (cacheServerPortString != null && !cacheServerPortString.isEmpty()) {
-            try {
-              cacheServerPort = Integer.parseInt(cacheServerPortString);
-            } catch (NumberFormatException nfe) {
-              return ResultBuilder.createUserErrorResult("Invalid port");
-            }
-          }
-          result = ResultBuilder.buildResult(
-              getMemberMetrics(member, export_to_report_to, categories, cacheServerPort));
-        } else {
-          ErrorResultData erd = ResultBuilder.createErrorResultData();
-          erd.addLine(CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId));
-          result = ResultBuilder.buildResult(erd);
-        }
-      } else {
-        if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
-          return ResultBuilder
-              .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
-        }
-        result = ResultBuilder.buildResult(getSystemWideMetrics(export_to_report_to, categories));
-      }
-    } catch (Exception e) {
-      logger.error(e.getMessage(), e);
-      return ResultBuilder.createGemFireErrorResult(CliUtil.stackTraceAsString(e));
-    }
-    return result;
-  }
-
-  /**
-   * Gets the system wide metrics
-   *
-   * @return ResultData with required System wide statistics or ErrorResultData if DS MBean is not
-   *         found to gather metrics
-   */
-  private ResultData getSystemWideMetrics(String export_to_report_to, String[] categoriesArr) {
-    final InternalCache cache = getCache();
-    final ManagementService managementService = ManagementService.getManagementService(cache);
-    DistributedSystemMXBean dsMxBean = managementService.getDistributedSystemMXBean();
-    StringBuilder csvBuilder = null;
-    if (dsMxBean != null) {
-
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        csvBuilder = new StringBuilder();
-        csvBuilder.append("Category");
-        csvBuilder.append(',');
-        csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
-        csvBuilder.append(',');
-        csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
-        csvBuilder.append('\n');
-      }
-
-      CompositeResultData crd = ResultBuilder.createCompositeResultData();
-      SectionResultData section = crd.addSection();
-      TabularResultData metricsTable = section.addTable();
-      Map<String, Boolean> categoriesMap = getSystemMetricsCategories();
-
-      if (categoriesArr != null && categoriesArr.length != 0) {
-        Set<String> categories = createSet(categoriesArr);
-        Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
-        Set<String> userCategories = getSetDifference(categories, checkSet);
-
-        // Checking if the categories specified by the user are valid or not
-
-        if (userCategories.isEmpty()) {
-          for (String category : checkSet) {
-            categoriesMap.put(category, false);
-          }
-          for (String category : categories) {
-            categoriesMap.put(category.toLowerCase(), true);
-          }
-        } else {
-          StringBuilder sb = new StringBuilder();
-          sb.append("Invalid Categories\n");
-
-          for (String category : userCategories) {
-            sb.append(category);
-            sb.append('\n');
-          }
-          return ResultBuilder.createErrorResultData().addLine(sb.toString());
-        }
-      }
-      metricsTable.setHeader("Cluster-wide Metrics");
-
-      if (categoriesMap.get("cluster")) {
-        writeToTableAndCsv(metricsTable, "cluster", "totalHeapSize", dsMxBean.getTotalHeapSize(),
-            csvBuilder);
-      }
-
-      if (categoriesMap.get("cache")) {
-        writeToTableAndCsv(metricsTable, "cache", "totalRegionEntryCount",
-            dsMxBean.getTotalRegionEntryCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalRegionCount", dsMxBean.getTotalRegionCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalMissCount", dsMxBean.getTotalMissCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalHitCount", dsMxBean.getTotalHitCount(),
-            csvBuilder);
-      }
-
-      if (categoriesMap.get("diskstore")) {
-        writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
-            dsMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
-        writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
-            dsMxBean.getDiskReadsRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "diskWritesRate", dsMxBean.getDiskWritesRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "flushTimeAvgLatency",
-            dsMxBean.getDiskFlushAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalBackupInProgress",
-            dsMxBean.getTotalBackupInProgress(), csvBuilder);
-      }
-
-      if (categoriesMap.get("query")) {
-        writeToTableAndCsv(metricsTable, "query", "activeCQCount", dsMxBean.getActiveCQCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "queryRequestRate", dsMxBean.getQueryRequestRate(),
-            csvBuilder);
-      }
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        crd.addAsFile(export_to_report_to, csvBuilder.toString(),
-            "Cluster wide metrics exported to {0}.", false);
-      }
-
-      return crd;
-    } else {
-      String errorMessage =
-          CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Distributed System MBean not found");
-      return ResultBuilder.createErrorResultData().addLine(errorMessage);
-    }
-  }
-
-  /**
-   * Gets the Cluster wide metrics for a given member
-   *
-   * @return ResultData with required Member statistics or ErrorResultData if MemberMbean is not
-   *         found to gather metrics
-   * @throws ResultDataException if building result fails
-   */
-  private ResultData getMemberMetrics(DistributedMember distributedMember,
-      String export_to_report_to, String[] categoriesArr, int cacheServerPort)
-      throws ResultDataException {
-    final InternalCache cache = getCache();
-    final SystemManagementService managementService =
-        (SystemManagementService) ManagementService.getManagementService(cache);
-
-    ObjectName memberMBeanName = managementService.getMemberMBeanName(distributedMember);
-    MemberMXBean memberMxBean =
-        managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
-    ObjectName csMxBeanName;
-    CacheServerMXBean csMxBean = null;
-
-    if (memberMxBean != null) {
-
-      if (cacheServerPort != -1) {
-        csMxBeanName =
-            managementService.getCacheServerMBeanName(cacheServerPort, distributedMember);
-        csMxBean = managementService.getMBeanInstance(csMxBeanName, CacheServerMXBean.class);
-
-        if (csMxBean == null) {
-          ErrorResultData erd = ResultBuilder.createErrorResultData();
-          erd.addLine(CliStrings.format(CliStrings.SHOW_METRICS__CACHE__SERVER__NOT__FOUND,
-              cacheServerPort, MBeanJMXAdapter.getMemberNameOrId(distributedMember)));
-          return erd;
-        }
-      }
-
-      JVMMetrics jvmMetrics = memberMxBean.showJVMMetrics();
-
-      CompositeResultData crd = ResultBuilder.createCompositeResultData();
-      SectionResultData section = crd.addSection();
-      TabularResultData metricsTable = section.addTable();
-      metricsTable.setHeader("Member Metrics");
-      StringBuilder csvBuilder = null;
-
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        csvBuilder = new StringBuilder();
-        csvBuilder.append("Category");
-        csvBuilder.append(',');
-        csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
-        csvBuilder.append(',');
-        csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
-        csvBuilder.append('\n');
-      }
-
-      Map<String, Boolean> categoriesMap = getMemberMetricsCategories();
-
-      if (categoriesArr != null && categoriesArr.length != 0) {
-        Set<String> categories = createSet(categoriesArr);
-        Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
-        Set<String> userCategories = getSetDifference(categories, checkSet);
-
-        // Checking if the categories specified by the user are valid or not
-        if (userCategories.isEmpty()) {
-          for (String category : checkSet) {
-            categoriesMap.put(category, false);
-          }
-          for (String category : categories) {
-            categoriesMap.put(category.toLowerCase(), true);
-          }
-        } else {
-          StringBuilder sb = new StringBuilder();
-          sb.append("Invalid Categories\n");
-
-          for (String category : userCategories) {
-            sb.append(category);
-            sb.append('\n');
-          }
-          return ResultBuilder.createErrorResultData().addLine(sb.toString());
-        }
-      }
-
-      /*
-       * Member Metrics
-       */
-      // member, jvm, region, serialization, communication, function, transaction, diskstore, lock,
-      // eviction, distribution
-      if (categoriesMap.get("member")) {
-        writeToTableAndCsv(metricsTable, "member", "upTime", memberMxBean.getMemberUpTime(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "cpuUsage", memberMxBean.getCpuUsage(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "currentHeapSize", memberMxBean.getCurrentHeapSize(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "maximumHeapSize", memberMxBean.getMaximumHeapSize(),
-            csvBuilder);
-      }
-      /*
-       * JVM Metrics
-       */
-      if (categoriesMap.get("jvm")) {
-        writeToTableAndCsv(metricsTable, "jvm ", "jvmThreads ", jvmMetrics.getTotalThreads(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "fileDescriptorLimit",
-            memberMxBean.getFileDescriptorLimit(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalFileDescriptorOpen",
-            memberMxBean.getTotalFileDescriptorOpen(), csvBuilder);
-      }
-      /*
-       * Member wide region metrics
-       */
-      if (categoriesMap.get("region")) {
-        writeToTableAndCsv(metricsTable, "region ", "totalRegionCount ",
-            memberMxBean.getTotalRegionCount(), csvBuilder);
-        String[] regionNames = memberMxBean.listRegions();
-        if (regionNames != null) {
-          for (int i = 0; i < regionNames.length; i++) {
-            if (i == 0) {
-              writeToTableAndCsv(metricsTable, "", "listOfRegions", regionNames[i].substring(1),
-                  csvBuilder);
-            } else {
-              writeToTableAndCsv(metricsTable, "", "", regionNames[i].substring(1), csvBuilder);
-            }
-          }
-        }
-
-        String[] rootRegionNames = memberMxBean.getRootRegionNames();
-        if (rootRegionNames != null) {
-          for (int i = 0; i < rootRegionNames.length; i++) {
-            if (i == 0) {
-              writeToTableAndCsv(metricsTable, "", "rootRegions", rootRegionNames[i], csvBuilder);
-            } else {
-              writeToTableAndCsv(metricsTable, "", "", rootRegionNames[i], csvBuilder);
-            }
-          }
-        }
-        writeToTableAndCsv(metricsTable, "", "totalRegionEntryCount",
-            memberMxBean.getTotalRegionEntryCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalBucketCount", memberMxBean.getTotalBucketCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalPrimaryBucketCount",
-            memberMxBean.getTotalPrimaryBucketCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "getsAvgLatency", memberMxBean.getGetsAvgLatency(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putsAvgLatency", memberMxBean.getPutsAvgLatency(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "createsRate", memberMxBean.getCreatesRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "destroyRate", memberMxBean.getDestroysRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putAllAvgLatency", memberMxBean.getPutAllAvgLatency(),
-            csvBuilder);
-        // Not available from stats. After Stats re-org it will be available
-        // writeToTableAndCsv(metricsTable, "", "getAllAvgLatency",
-        // memberMxBean.getGetAllAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalMissCount", memberMxBean.getTotalMissCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalHitCount", memberMxBean.getTotalHitCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "getsRate", memberMxBean.getGetsRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putsRate", memberMxBean.getPutsRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "cacheWriterCallsAvgLatency",
-            memberMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
-            memberMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalLoadsCompleted",
-            memberMxBean.getTotalLoadsCompleted(), csvBuilder);
-      }
-
-      /*
-       * SERIALIZATION
-       */
-      if (categoriesMap.get("serialization")) {
-        writeToTableAndCsv(metricsTable, "serialization", "serializationRate",
-            memberMxBean.getSerializationRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "serializationLatency",
-            memberMxBean.getSerializationRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "deserializationRate",
-            memberMxBean.getDeserializationRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "deserializationLatency",
-            memberMxBean.getDeserializationLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "deserializationAvgLatency",
-            memberMxBean.getDeserializationAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "PDXDeserializationAvgLatency",
-            memberMxBean.getPDXDeserializationAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "PDXDeserializationRate",
-            memberMxBean.getPDXDeserializationRate(), csvBuilder);
-      }
-
-      /*
-       * Communication Metrics
-       */
-      if (categoriesMap.get("communication")) {
-        writeToTableAndCsv(metricsTable, "communication", "bytesSentRate",
-            memberMxBean.getBytesSentRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "bytesReceivedRate",
-            memberMxBean.getBytesReceivedRate(), csvBuilder);
-        String[] connectedGatewayReceivers = memberMxBean.listConnectedGatewayReceivers();
-        writeToTableAndCsv(metricsTable, "", "connectedGatewayReceivers", connectedGatewayReceivers,
-            csvBuilder);
-
-        String[] connectedGatewaySenders = memberMxBean.listConnectedGatewaySenders();
-        writeToTableAndCsv(metricsTable, "", "connectedGatewaySenders", connectedGatewaySenders,
-            csvBuilder);
-      }
-
-      /*
-       * Member wide function metrics
-       */
-      if (categoriesMap.get("function")) {
-        writeToTableAndCsv(metricsTable, "function", "numRunningFunctions",
-            memberMxBean.getNumRunningFunctions(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "functionExecutionRate",
-            memberMxBean.getFunctionExecutionRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "numRunningFunctionsHavingResults",
-            memberMxBean.getNumRunningFunctionsHavingResults(), csvBuilder);
-      }
-
-      /*
-       * totalTransactionsCount currentTransactionalThreadIds transactionCommitsAvgLatency
-       * transactionCommittedTotalCount transactionRolledBackTotalCount transactionCommitsRate
-       */
-      if (categoriesMap.get("transaction")) {
-        writeToTableAndCsv(metricsTable, "transaction", "totalTransactionsCount",
-            memberMxBean.getTotalTransactionsCount(), csvBuilder);
-
-        writeToTableAndCsv(metricsTable, "", "transactionCommitsAvgLatency",
-            memberMxBean.getTransactionCommitsAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "transactionCommittedTotalCount",
-            memberMxBean.getTransactionCommittedTotalCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "transactionRolledBackTotalCount",
-            memberMxBean.getTransactionRolledBackTotalCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "transactionCommitsRate",
-            memberMxBean.getTransactionCommitsRate(), csvBuilder);
-      }
-      /*
-       * Member wide disk metrics
-       */
-      if (categoriesMap.get("diskstore")) {
-        writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
-            memberMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
-        writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
-            memberMxBean.getDiskReadsRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "diskWritesRate", memberMxBean.getDiskWritesRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "flushTimeAvgLatency",
-            memberMxBean.getDiskFlushAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalQueueSize",
-            memberMxBean.getTotalDiskTasksWaiting(), csvBuilder); // deadcoded to workaround bug
-        // 46397
-        writeToTableAndCsv(metricsTable, "", "totalBackupInProgress",
-            memberMxBean.getTotalBackupInProgress(), csvBuilder);
-      }
-      /*
-       * Member wide Lock
-       */
-      if (categoriesMap.get("lock")) {
-        writeToTableAndCsv(metricsTable, "lock", "lockWaitsInProgress",
-            memberMxBean.getLockWaitsInProgress(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalLockWaitTime",
-            memberMxBean.getTotalLockWaitTime(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalNumberOfLockService",
-            memberMxBean.getTotalNumberOfLockService(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "requestQueues", memberMxBean.getLockRequestQueues(),
-            csvBuilder);
-      }
-      /*
-       * Eviction
-       */
-      if (categoriesMap.get("eviction")) {
-        writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
-            memberMxBean.getLruEvictionRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "lruDestroyRate", memberMxBean.getLruDestroyRate(),
-            csvBuilder);
-      }
-      /*
-       * Distribution
-       */
-      if (categoriesMap.get("distribution")) {
-        writeToTableAndCsv(metricsTable, "distribution", "getInitialImagesInProgress",
-            memberMxBean.getInitialImagesInProgress(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "getInitialImageTime",
-            memberMxBean.getInitialImageTime(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "getInitialImageKeysReceived",
-            memberMxBean.getInitialImageKeysReceived(), csvBuilder);
-      }
-
-      /*
-       * OffHeap
-       */
-      if (categoriesMap.get("offheap")) {
-        writeToTableAndCsv(metricsTable, "offheap", "maxMemory", memberMxBean.getOffHeapMaxMemory(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "freeMemory", memberMxBean.getOffHeapFreeMemory(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "usedMemory", memberMxBean.getOffHeapUsedMemory(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "objects", memberMxBean.getOffHeapObjects(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "fragmentation",
-            memberMxBean.getOffHeapFragmentation(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "compactionTime",
-            memberMxBean.getOffHeapCompactionTime(), csvBuilder);
-      }
-
-      /*
-       * CacheServer stats
-       */
-      if (csMxBean != null) {
-        writeToTableAndCsv(metricsTable, "cache-server", "clientConnectionCount",
-            csMxBean.getClientConnectionCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "hostnameForClients", csMxBean.getHostNameForClients(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "getRequestAvgLatency",
-            csMxBean.getGetRequestAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putRequestAvgLatency",
-            csMxBean.getPutRequestAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalConnectionsTimedOut",
-            csMxBean.getTotalConnectionsTimedOut(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "threadQueueSize", csMxBean.getPutRequestAvgLatency(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "connectionThreads", csMxBean.getConnectionThreads(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "connectionLoad", csMxBean.getConnectionLoad(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "loadPerConnection", csMxBean.getLoadPerConnection(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "queueLoad", csMxBean.getQueueLoad(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "loadPerQueue", csMxBean.getLoadPerQueue(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "getRequestRate", csMxBean.getGetRequestRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putRequestRate", csMxBean.getPutRequestRate(),
-            csvBuilder);
-
-        /*
-         * Notification
-         */
-        writeToTableAndCsv(metricsTable, "notification", "numClientNotificationRequests",
-            csMxBean.getNumClientNotificationRequests(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "clientNotificationRate",
-            csMxBean.getClientNotificationRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "clientNotificationAvgLatency",
-            csMxBean.getClientNotificationAvgLatency(), csvBuilder);
-
-        /*
-         * Query
-         */
-        writeToTableAndCsv(metricsTable, "query", "activeCQCount", csMxBean.getActiveCQCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "query", "queryRequestRate",
-            csMxBean.getQueryRequestRate(), csvBuilder);
-
-        writeToTableAndCsv(metricsTable, "", "indexCount", csMxBean.getIndexCount(), csvBuilder);
-
-        String[] indexList = csMxBean.getIndexList();
-        writeToTableAndCsv(metricsTable, "", "index list", indexList, csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalIndexMaintenanceTime",
-            csMxBean.getTotalIndexMaintenanceTime(), csvBuilder);
-      }
-
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        crd.addAsFile(export_to_report_to, csvBuilder.toString(), "Member metrics exported to {0}.",
-            false);
-      }
-      return crd;
-
-    } else {
-      ErrorResultData erd = ResultBuilder.createErrorResultData();
-      String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Member MBean for "
-          + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
-      return ResultBuilder.createErrorResultData().addLine(errorMessage);
-    }
-  }
-
-  /**
-   * Gets the Cluster-wide metrics for a region
-   *
-   * @return ResultData containing the table
-   * @throws ResultDataException if building result fails
-   */
-  private ResultData getDistributedRegionMetrics(String regionName, String export_to_report_to,
-      String[] categoriesArr) throws ResultDataException {
-
-    final InternalCache cache = getCache();
-    final ManagementService managementService = ManagementService.getManagementService(cache);
-
-    DistributedRegionMXBean regionMxBean = managementService.getDistributedRegionMXBean(regionName);
-
-    if (regionMxBean != null) {
-      CompositeResultData crd = ResultBuilder.createCompositeResultData();
-      SectionResultData section = crd.addSection();
-      TabularResultData metricsTable = section.addTable();
-      metricsTable.setHeader("Cluster-wide Region Metrics");
-      StringBuilder csvBuilder = null;
-
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        csvBuilder = new StringBuilder();
-        csvBuilder.append("Category");
-        csvBuilder.append(',');
-        csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
-        csvBuilder.append(',');
-        csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
-        csvBuilder.append('\n');
-      }
-
-      Map<String, Boolean> categoriesMap = getSystemRegionMetricsCategories();
-
-      if (categoriesArr != null && categoriesArr.length != 0) {
-        Set<String> categories = createSet(categoriesArr);
-        Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
-        Set<String> userCategories = getSetDifference(categories, checkSet);
-
-        // Checking if the categories specified by the user are valid or not
-        if (userCategories.isEmpty()) {
-          for (String category : checkSet) {
-            categoriesMap.put(category, false);
-          }
-          for (String category : categories) {
-            categoriesMap.put(category.toLowerCase(), true);
-          }
-        } else {
-          StringBuilder sb = new StringBuilder();
-          sb.append("Invalid Categories\n");
-
-          for (String category : userCategories) {
-            sb.append(category);
-            sb.append('\n');
-          }
-          return ResultBuilder.createErrorResultData().addLine(sb.toString());
-        }
-      }
-      /*
-       * General System metrics
-       */
-      // cluster, region, partition , diskstore, callback, eviction
-      if (categoriesMap.get("cluster")) {
-        writeToTableAndCsv(metricsTable, "cluster", "member count", regionMxBean.getMemberCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "region entry count",
-            regionMxBean.getSystemRegionEntryCount(), csvBuilder);
-      }
-
-      if (categoriesMap.get("region")) {
-        writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
-            regionMxBean.getLastModifiedTime(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(),
-            csvBuilder);
-      }
-
-      if (categoriesMap.get("partition")) {
-        writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
-            regionMxBean.getPutLocalRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency",
-            regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
-
-        writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "primaryBucketCount",
-            regionMxBean.getPrimaryBucketCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy",
-            regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "averageBucketSize", regionMxBean.getAvgBucketSize(),
-            csvBuilder);
-      }
-      /*
-       * Disk store
-       */
-      if (categoriesMap.get("diskstore")) {
-        writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
-            regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "diskReadsRate", regionMxBean.getDiskReadsRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress",
-            regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(),
-            csvBuilder);
-
-      }
-      /*
-       * LISTENER
-       */
-      if (categoriesMap.get("callback")) {
-        writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
-            regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
-            regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
-      }
-
-      /*
-       * Eviction
-       */
-      if (categoriesMap.get("eviction")) {
-        writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
-            regionMxBean.getLruEvictionRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
-            csvBuilder);
-      }
-
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        crd.addAsFile(export_to_report_to, csvBuilder.toString(),
-            "Aggregate Region Metrics exported to {0}.", false);
-      }
-
-      return crd;
-    } else {
-      ErrorResultData erd = ResultBuilder.createErrorResultData();
-      String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR,
-          "Distributed Region MBean for " + regionName + " not found");
-      erd.addLine(errorMessage);
-      return erd;
-    }
-  }
-
-  /**
-   * Gets the metrics of region on a given member
-   *
-   * @return ResultData with required Region statistics or ErrorResultData if Region MBean is not
-   *         found to gather metrics
-   * @throws ResultDataException if building result fails
-   */
-  private ResultData getRegionMetricsFromMember(String regionName,
-      DistributedMember distributedMember, String export_to_report_to, String[] categoriesArr)
-      throws ResultDataException {
-
-    final InternalCache cache = getCache();
-    final SystemManagementService managementService =
-        (SystemManagementService) ManagementService.getManagementService(cache);
-
-    ObjectName regionMBeanName =
-        managementService.getRegionMBeanName(distributedMember, regionName);
-    RegionMXBean regionMxBean =
-        managementService.getMBeanInstance(regionMBeanName, RegionMXBean.class);
-
-    if (regionMxBean != null) {
-      CompositeResultData crd = ResultBuilder.createCompositeResultData();
-      SectionResultData section = crd.addSection();
-      TabularResultData metricsTable = section.addTable();
-      metricsTable.setHeader("Metrics for region:" + regionName + " On Member "
-          + MBeanJMXAdapter.getMemberNameOrId(distributedMember));
-      StringBuilder csvBuilder = null;
-
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        csvBuilder = new StringBuilder();
-        csvBuilder.append("Category");
-        csvBuilder.append(',');
-        csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
-        csvBuilder.append(',');
-        csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
-        csvBuilder.append('\n');
-      }
-
-      /*
-       * Region Metrics
-       */
-      Map<String, Boolean> categoriesMap = getRegionMetricsCategories();
-
-      if (categoriesArr != null && categoriesArr.length != 0) {
-        Set<String> categories = createSet(categoriesArr);
-        Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
-        Set<String> userCategories = getSetDifference(categories, checkSet);
-
-        // Checking if the categories specified by the user are valid or not
-        if (userCategories.isEmpty()) {
-          for (String category : checkSet) {
-            categoriesMap.put(category, false);
-          }
-          for (String category : categories) {
-            categoriesMap.put(category.toLowerCase(), true);
-          }
-        } else {
-          StringBuilder sb = new StringBuilder();
-          sb.append("Invalid Categories\n");
-
-          for (String category : userCategories) {
-            sb.append(category);
-            sb.append('\n');
-          }
-          return ResultBuilder.createErrorResultData().addLine(sb.toString());
-        }
-      }
-
-      if (categoriesMap.get("region")) {
-        writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
-            regionMxBean.getLastModifiedTime(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(),
-            csvBuilder);
-      }
-
-      if (categoriesMap.get("partition")) {
-        writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
-            regionMxBean.getPutLocalRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency",
-            regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
-
-        writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "primaryBucketCount",
-            regionMxBean.getPrimaryBucketCount(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "configuredRedundancy",
-            regionMxBean.getConfiguredRedundancy(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "actualRedundancy", regionMxBean.getActualRedundancy(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy",
-            regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(),
-            csvBuilder);
-      }
-      /*
-       * Disk store
-       */
-      if (categoriesMap.get("diskstore")) {
-        writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
-            regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "diskReadsRate", "" + regionMxBean.getDiskReadsRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(),
-            csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress",
-            regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(),
-            csvBuilder);
-      }
-      /*
-       * LISTENER
-       */
-      if (categoriesMap.get("callback")) {
-        writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
-            regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
-            regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
-      }
-
-      /*
-       * Eviction
-       */
-      if (categoriesMap.get("eviction")) {
-        writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
-            regionMxBean.getLruEvictionRate(), csvBuilder);
-        writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
-            csvBuilder);
-      }
-      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
-        crd.addAsFile(export_to_report_to, csvBuilder.toString(), "Region Metrics exported to {0}.",
-            false);
-      }
-
-      return crd;
-    } else {
-      ErrorResultData erd = ResultBuilder.createErrorResultData();
-      String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR,
-          "Region MBean for " + regionName + " on member "
-              + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
-      erd.addLine(errorMessage);
-      return erd;
-    }
-  }
-
-  /***
-   * Writes an entry to a TabularResultData and writes a comma separated entry to a string builder
-   */
-  private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
-      long metricValue, StringBuilder csvBuilder) {
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
-
-    if (csvBuilder != null) {
-      csvBuilder.append(type);
-      csvBuilder.append(',');
-      csvBuilder.append(metricName);
-      csvBuilder.append(',');
-      csvBuilder.append(metricValue);
-      csvBuilder.append('\n');
-    }
-  }
-
-  private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
-      double metricValue, StringBuilder csvBuilder) {
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
-
-    if (csvBuilder != null) {
-      csvBuilder.append(type);
-      csvBuilder.append(',');
-      csvBuilder.append(metricName);
-      csvBuilder.append(',');
-      csvBuilder.append(metricValue);
-      csvBuilder.append('\n');
-    }
-  }
-
-  private Set<String> createSet(String[] categories) {
-    Set<String> categoriesSet = new HashSet<>();
-    Collections.addAll(categoriesSet, categories);
-    return categoriesSet;
-  }
-
-  /**
-   * Defines and returns map of categories for System metrics.
-   *
-   * @return map with categories for system metrics and display flag set to true
-   */
-  private Map<String, Boolean> getSystemMetricsCategories() {
-    Map<String, Boolean> categories = new HashMap<>();
-    categories.put("cluster", true);
-    categories.put("cache", true);
-    categories.put("diskstore", true);
-    categories.put("query", true);
-    return categories;
-  }
-
-  /**
-   * Defines and returns map of categories for Region Metrics
-   *
-   * @return map with categories for region metrics and display flag set to true
-   */
-  private Map<String, Boolean> getRegionMetricsCategories() {
-    Map<String, Boolean> categories = new HashMap<>();
-
-    categories.put("region", true);
-    categories.put("partition", true);
-    categories.put("diskstore", true);
-    categories.put("callback", true);
-    categories.put("gatewayreceiver", true);
-    categories.put("distribution", true);
-    categories.put("query", true);
-    categories.put("eviction", true);
-    return categories;
-  }
-
-  /**
-   * Defines and returns map of categories for system-wide region metrics
-   *
-   * @return map with categories for system wide region metrics and display flag set to true
-   */
-  private Map<String, Boolean> getSystemRegionMetricsCategories() {
-    Map<String, Boolean> categories = getRegionMetricsCategories();
-    categories.put("cluster", true);
-    return categories;
-  }
-
-  /**
-   * Defines and returns map of categories for member metrics
-   *
-   * @return map with categories for member metrics and display flag set to true
-   */
-  private Map<String, Boolean> getMemberMetricsCategories() {
-    Map<String, Boolean> categories = new HashMap<>();
-    categories.put("member", true);
-    categories.put("jvm", true);
-    categories.put("region", true);
-    categories.put("serialization", true);
-    categories.put("communication", true);
-    categories.put("function", true);
-    categories.put("transaction", true);
-    categories.put("diskstore", true);
-    categories.put("lock", true);
-    categories.put("eviction", true);
-    categories.put("distribution", true);
-    categories.put("offheap", true);
-    return categories;
-  }
-
-  /**
-   * Converts an array of strings to a String delimited by a new line character for display purposes
-   *
-   * @return a String delimited by a new line character for display purposes
-   */
-  private String formatNames(String[] names, int startIndex) {
-    StringBuilder sb = new StringBuilder();
-
-    if (names != null) {
-      for (String name : names) {
-        sb.append(name.substring(startIndex));
-        sb.append('\n');
-      }
-    }
-    return sb.toString();
-  }
-
-  private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
-      String metricValue[], StringBuilder csvBuilder) {
-    if (metricValue != null) {
-      for (int i = 0; i < metricValue.length; i++) {
-        if (i == 0) {
-          writeToTableAndCsv(metricsTable, type, metricName, metricValue[i], csvBuilder);
-        } else {
-          writeToTableAndCsv(metricsTable, "", "", metricValue[i], csvBuilder);
-        }
-      }
-    }
-  }
-
-  /**
-   * Writes to a TabularResultData and also appends a CSV string to a String builder
-   */
-  private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
-      String metricValue, StringBuilder csvBuilder) {
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
-    metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
-
-    if (csvBuilder != null) {
-      csvBuilder.append(type);
-      csvBuilder.append(',');
-      csvBuilder.append(metricName);
-      csvBuilder.append(',');
-      csvBuilder.append(metricValue);
-      csvBuilder.append('\n');
-    }
-  }
-
-  @CliCommand(value = CliStrings.CHANGE_LOGLEVEL, help = CliStrings.CHANGE_LOGLEVEL__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_LOGS},
-      interceptor = "org.apache.geode.management.internal.cli.commands.MiscellaneousCommands$ChangeLogLevelInterceptor")
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.WRITE)
-  public Result changeLogLevel(
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          help = CliStrings.CHANGE_LOGLEVEL__MEMBER__HELP) String[] memberIds,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, unspecifiedDefaultValue = "",
-          help = CliStrings.CHANGE_LOGLEVEL__GROUPS__HELP) String[] grps,
-      @CliOption(key = CliStrings.CHANGE_LOGLEVEL__LOGLEVEL,
-          optionContext = ConverterHint.LOG_LEVEL, mandatory = true, unspecifiedDefaultValue = "",
-          help = CliStrings.CHANGE_LOGLEVEL__LOGLEVEL__HELP) String logLevel) {
-    try {
-      if ((memberIds == null || memberIds.length == 0) && (grps == null || grps.length == 0)) {
-        return ResultBuilder
-            .createUserErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG__SPECIFY_GRP_OR_MEMBER);
-      }
-
-      InternalCache cache = GemFireCacheImpl.getInstance();
-      LogWriter logger = cache.getLogger();
-
-      Set<DistributedMember> dsMembers = new HashSet<>();
-      Set<DistributedMember> ds = CliUtil.getAllMembers(cache);
-
-      if (grps != null && grps.length > 0) {
-        for (String grp : grps) {
-          dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
-        }
-      }
-
-      if (memberIds != null && memberIds.length > 0) {
-        for (String member : memberIds) {
-          for (DistributedMember mem : ds) {
-            if (mem.getName() != null
-                && (mem.getName().equals(member) || mem.getId().equals(member))) {
-              dsMembers.add(mem);
-              break;
-            }
-          }
-        }
-      }
-
-      if (dsMembers.size() == 0) {
-        return ResultBuilder.createGemFireErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG_NO_MEMBERS);
-      }
-
-      Function logFunction = new ChangeLogLevelFunction();
-      FunctionService.registerFunction(logFunction);
-      Object[] functionArgs = new Object[1];
-      functionArgs[0] = logLevel;
-
-      CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
-      SectionResultData section = compositeResultData.addSection("section");
-      TabularResultData resultTable = section.addTable("ChangeLogLevel");
-      resultTable = resultTable.setHeader("Summary");
-
-      Execution execution = FunctionService.onMembers(dsMembers).setArguments(functionArgs);
-      if (execution == null) {
-        return ResultBuilder.createUserErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG__CANNOT_EXECUTE);
-      }
-      List<?> resultList = (List<?>) execution.execute(logFunction).getResult();
-
-      for (Object object : resultList) {
-        try {
-          if (object instanceof Throwable) {
-            logger.warning(
-                "Exception in ChangeLogLevelFunction " + ((Throwable) object).getMessage(),
-                ((Throwable) object));
-            continue;
-          }
-
-          if (object != null) {
-            Map<String, String> resultMap = (Map<String, String>) object;
-            Entry<String, String> entry = resultMap.entrySet().iterator().next();
-
-            if (entry.getValue().contains("ChangeLogLevelFunction exception")) {
-              resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_MEMBER, entry.getKey());
-              resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_STATUS, "false");
-            } else {
-              resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_MEMBER, entry.getKey());
-              resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_STATUS, "true");
-            }
-
-          }
-        } catch (Exception ex) {
-          LogWrapper.getInstance().warning("change log level command exception " + ex);
-        }
-      }
-
-      Result result = ResultBuilder.buildResult(compositeResultData);
-      logger.info("change log-level command result=" + result);
-      return result;
-    } catch (Exception ex) {
-      GemFireCacheImpl.getInstance().getLogger().error("GFSH Changeloglevel exception: " + ex);
-      return ResultBuilder.createUserErrorResult(ex.getMessage());
-    }
-  }
-
-  public static class ChangeLogLevelInterceptor extends AbstractCliAroundInterceptor {
-    @Override
-    public Result preExecution(GfshParseResult parseResult) {
-      Map<String, String> arguments = parseResult.getParamValueStrings();
-      // validate log level
-      String logLevel = arguments.get("loglevel");
-      if (StringUtils.isBlank(logLevel) || LogLevel.getLevel(logLevel) == null) {
-        return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
-      }
-
-      return ResultBuilder.createInfoResult("");
-    }
-  }
-
-  private Set<String> getSetDifference(Set<String> set1, Set<String> set2) {
-    Set<String> setDifference = new HashSet<>();
-    for (String element : set1) {
-      if (!(set2.contains(element.toLowerCase()))) {
-        setDifference.add(element);
-      }
-    }
-    return setDifference;
-  }
-}


[13/47] geode git commit: GEODE-3436: Restore refactoring of CreateAlterDestroyRegionCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
new file mode 100644
index 0000000..294e4f3
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
@@ -0,0 +1,725 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.management.ObjectName;
+
+import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.PartitionResolver;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionAttributes;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.compression.Compressor;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.DistributionManager;
+import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
+import org.apache.geode.internal.ClassPathLoader;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.i18n.LocalizedStrings;
+import org.apache.geode.management.DistributedRegionMXBean;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.RegionAttributesData;
+import org.apache.geode.management.RegionMXBean;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction;
+import org.apache.geode.management.internal.cli.functions.RegionCreateFunction;
+import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.cli.util.RegionPath;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CreateRegionCommand implements GfshCommand {
+
+  @CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+  @ResourceOperation(resource = ResourcePermission.Resource.DATA,
+      operation = ResourcePermission.Operation.MANAGE)
+  public Result createRegion(
+      @CliOption(key = CliStrings.CREATE_REGION__REGION, mandatory = true,
+          help = CliStrings.CREATE_REGION__REGION__HELP) String regionPath,
+      @CliOption(key = CliStrings.CREATE_REGION__REGIONSHORTCUT,
+          help = CliStrings.CREATE_REGION__REGIONSHORTCUT__HELP) RegionShortcut regionShortcut,
+      @CliOption(key = CliStrings.CREATE_REGION__USEATTRIBUTESFROM,
+          optionContext = ConverterHint.REGION_PATH,
+          help = CliStrings.CREATE_REGION__USEATTRIBUTESFROM__HELP) String useAttributesFrom,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.CREATE_REGION__GROUP__HELP) String[] groups,
+      @CliOption(key = CliStrings.CREATE_REGION__SKIPIFEXISTS, unspecifiedDefaultValue = "true",
+          specifiedDefaultValue = "true",
+          help = CliStrings.CREATE_REGION__SKIPIFEXISTS__HELP) boolean skipIfExists,
+
+      // the following should all be in alphabetical order according to
+      // their key string
+      @CliOption(key = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID,
+          help = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
+      @CliOption(key = CliStrings.CREATE_REGION__CACHELISTENER,
+          help = CliStrings.CREATE_REGION__CACHELISTENER__HELP) String[] cacheListener,
+      @CliOption(key = CliStrings.CREATE_REGION__CACHELOADER,
+          help = CliStrings.CREATE_REGION__CACHELOADER__HELP) String cacheLoader,
+      @CliOption(key = CliStrings.CREATE_REGION__CACHEWRITER,
+          help = CliStrings.CREATE_REGION__CACHEWRITER__HELP) String cacheWriter,
+      @CliOption(key = CliStrings.CREATE_REGION__COLOCATEDWITH,
+          optionContext = ConverterHint.REGION_PATH,
+          help = CliStrings.CREATE_REGION__COLOCATEDWITH__HELP) String prColocatedWith,
+      @CliOption(key = CliStrings.CREATE_REGION__COMPRESSOR,
+          help = CliStrings.CREATE_REGION__COMPRESSOR__HELP) String compressor,
+      @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYLEVEL,
+          help = CliStrings.CREATE_REGION__CONCURRENCYLEVEL__HELP) Integer concurrencyLevel,
+      @CliOption(key = CliStrings.CREATE_REGION__DISKSTORE,
+          help = CliStrings.CREATE_REGION__DISKSTORE__HELP) String diskStore,
+      @CliOption(key = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION,
+          help = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION__HELP) Boolean enableAsyncConflation,
+      @CliOption(key = CliStrings.CREATE_REGION__CLONINGENABLED,
+          help = CliStrings.CREATE_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
+      @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED,
+          help = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED__HELP) Boolean concurrencyChecksEnabled,
+      @CliOption(key = CliStrings.CREATE_REGION__MULTICASTENABLED,
+          help = CliStrings.CREATE_REGION__MULTICASTENABLED__HELP) Boolean mcastEnabled,
+      @CliOption(key = CliStrings.CREATE_REGION__STATISTICSENABLED,
+          help = CliStrings.CREATE_REGION__STATISTICSENABLED__HELP) Boolean statisticsEnabled,
+      @CliOption(key = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION,
+          help = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION__HELP) Boolean enableSubscriptionConflation,
+      @CliOption(key = CliStrings.CREATE_REGION__DISKSYNCHRONOUS,
+          help = CliStrings.CREATE_REGION__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
+      @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME,
+          help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
+      @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
+          help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
+      @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE,
+          help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
+      @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION,
+          help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
+      @CliOption(key = CliStrings.CREATE_REGION__GATEWAYSENDERID,
+          help = CliStrings.CREATE_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
+      @CliOption(key = CliStrings.CREATE_REGION__KEYCONSTRAINT,
+          help = CliStrings.CREATE_REGION__KEYCONSTRAINT__HELP) String keyConstraint,
+      @CliOption(key = CliStrings.CREATE_REGION__LOCALMAXMEMORY,
+          help = CliStrings.CREATE_REGION__LOCALMAXMEMORY__HELP) Integer prLocalMaxMemory,
+      @CliOption(key = CliStrings.CREATE_REGION__OFF_HEAP, specifiedDefaultValue = "true",
+          help = CliStrings.CREATE_REGION__OFF_HEAP__HELP) Boolean offHeap,
+      @CliOption(key = CliStrings.CREATE_REGION__PARTITION_RESOLVER,
+          help = CliStrings.CREATE_REGION__PARTITION_RESOLVER__HELP) String partitionResolver,
+      @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME,
+          help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
+      @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION,
+          help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
+      @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL,
+          help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
+      @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION,
+          help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
+      @CliOption(key = CliStrings.CREATE_REGION__RECOVERYDELAY,
+          help = CliStrings.CREATE_REGION__RECOVERYDELAY__HELP) Long prRecoveryDelay,
+      @CliOption(key = CliStrings.CREATE_REGION__REDUNDANTCOPIES,
+          help = CliStrings.CREATE_REGION__REDUNDANTCOPIES__HELP) Integer prRedundantCopies,
+      @CliOption(key = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY,
+          help = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY__HELP) Long prStartupRecoveryDelay,
+      @CliOption(key = CliStrings.CREATE_REGION__TOTALMAXMEMORY,
+          help = CliStrings.CREATE_REGION__TOTALMAXMEMORY__HELP) Long prTotalMaxMemory,
+      @CliOption(key = CliStrings.CREATE_REGION__TOTALNUMBUCKETS,
+          help = CliStrings.CREATE_REGION__TOTALNUMBUCKETS__HELP) Integer prTotalNumBuckets,
+      @CliOption(key = CliStrings.CREATE_REGION__VALUECONSTRAINT,
+          help = CliStrings.CREATE_REGION__VALUECONSTRAINT__HELP) String valueConstraint
+  // NOTICE: keep the region attributes params in alphabetical order
+  ) {
+    Result result;
+    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+
+    try {
+      InternalCache cache = getCache();
+
+      if (regionShortcut != null && useAttributesFrom != null) {
+        throw new IllegalArgumentException(
+            CliStrings.CREATE_REGION__MSG__ONLY_ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_CAN_BE_SPECIFIED);
+      } else if (regionShortcut == null && useAttributesFrom == null) {
+        throw new IllegalArgumentException(
+            CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUTESFROM_IS_REQUIRED);
+      }
+
+      validateRegionPathAndParent(cache, regionPath);
+      RegionCommandsUtils.validateGroups(cache, groups);
+
+      RegionFunctionArgs.ExpirationAttrs entryIdle = null;
+      if (entryExpirationIdleTime != null) {
+        entryIdle = new RegionFunctionArgs.ExpirationAttrs(
+            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
+            entryExpirationIdleTimeAction);
+      }
+      RegionFunctionArgs.ExpirationAttrs entryTTL = null;
+      if (entryExpirationTTL != null) {
+        entryTTL = new RegionFunctionArgs.ExpirationAttrs(
+            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
+            entryExpirationTTLAction);
+      }
+      RegionFunctionArgs.ExpirationAttrs regionIdle = null;
+      if (regionExpirationIdleTime != null) {
+        regionIdle = new RegionFunctionArgs.ExpirationAttrs(
+            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
+            regionExpirationIdleTimeAction);
+      }
+      RegionFunctionArgs.ExpirationAttrs regionTTL = null;
+      if (regionExpirationTTL != null) {
+        regionTTL = new RegionFunctionArgs.ExpirationAttrs(
+            RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
+            regionExpirationTTLAction);
+      }
+
+      RegionFunctionArgs regionFunctionArgs;
+      if (useAttributesFrom != null) {
+        if (!regionExists(cache, useAttributesFrom)) {
+          throw new IllegalArgumentException(CliStrings.format(
+              CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
+              new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
+        }
+
+        FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult =
+            getRegionAttributes(cache, useAttributesFrom);
+        RegionAttributes<?, ?> regionAttributes = regionAttributesResult.getRegionAttributes();
+
+        // give preference to user specified plugins than the ones retrieved from other region
+        String[] cacheListenerClasses = cacheListener != null && cacheListener.length != 0
+            ? cacheListener : regionAttributesResult.getCacheListenerClasses();
+        String cacheLoaderClass =
+            cacheLoader != null ? cacheLoader : regionAttributesResult.getCacheLoaderClass();
+        String cacheWriterClass =
+            cacheWriter != null ? cacheWriter : regionAttributesResult.getCacheWriterClass();
+
+        regionFunctionArgs = new RegionFunctionArgs(regionPath, useAttributesFrom, skipIfExists,
+            keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle,
+            regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
+            enableSubscriptionConflation, cacheListenerClasses, cacheLoaderClass, cacheWriterClass,
+            asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
+            concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
+            prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, offHeap, mcastEnabled,
+            regionAttributes, partitionResolver);
+
+        if (regionAttributes.getPartitionAttributes() == null
+            && regionFunctionArgs.hasPartitionAttributes()) {
+          throw new IllegalArgumentException(CliStrings.format(
+              CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
+              regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
+              + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
+                  useAttributesFrom));
+        }
+      } else {
+        regionFunctionArgs = new RegionFunctionArgs(regionPath, regionShortcut, useAttributesFrom,
+            skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL,
+            regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
+            enableSubscriptionConflation, cacheListener, cacheLoader, cacheWriter,
+            asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
+            concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
+            prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, null, compressor, offHeap,
+            mcastEnabled, partitionResolver);
+
+        if (!regionShortcut.name().startsWith("PARTITION")
+            && regionFunctionArgs.hasPartitionAttributes()) {
+          throw new IllegalArgumentException(CliStrings.format(
+              CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
+              regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
+              + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
+                  useAttributesFrom));
+        }
+      }
+
+      // Do we prefer to validate or authorize first?
+      validateRegionFunctionArgs(cache, regionFunctionArgs);
+      if (isPersistentShortcut(regionFunctionArgs.getRegionShortcut())
+          || isAttributePersistent(regionFunctionArgs.getRegionAttributes())) {
+        getSecurityService().authorize(ResourcePermission.Resource.CLUSTER,
+            ResourcePermission.Operation.WRITE, ResourcePermission.Target.DISK);
+      }
+
+      Set<DistributedMember> membersToCreateRegionOn;
+      if (groups != null && groups.length != 0) {
+        membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups);
+        // have only normal members from the group
+        membersToCreateRegionOn
+            .removeIf(distributedMember -> ((InternalDistributedMember) distributedMember)
+                .getVmKind() == DistributionManager.LOCATOR_DM_TYPE);
+      } else {
+        membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache);
+      }
+
+      if (membersToCreateRegionOn.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
+      }
+
+      ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionCreateFunction.INSTANCE,
+          regionFunctionArgs, membersToCreateRegionOn);
+      @SuppressWarnings("unchecked")
+      List<CliFunctionResult> regionCreateResults =
+          (List<CliFunctionResult>) resultCollector.getResult();
+
+      TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
+      final String errorPrefix = "ERROR: ";
+      for (CliFunctionResult regionCreateResult : regionCreateResults) {
+        boolean success = regionCreateResult.isSuccessful();
+        tabularResultData.accumulate("Member", regionCreateResult.getMemberIdOrName());
+        tabularResultData.accumulate("Status",
+            (success ? "" : errorPrefix) + regionCreateResult.getMessage());
+
+        if (success) {
+          xmlEntity.set(regionCreateResult.getXmlEntity());
+        }
+      }
+      result = ResultBuilder.buildResult(tabularResultData);
+      verifyDistributedRegionMbean(cache, regionPath);
+
+    } catch (IllegalArgumentException | IllegalStateException e) {
+      LogWrapper.getInstance().info(e.getMessage());
+      result = ResultBuilder.createUserErrorResult(e.getMessage());
+    }
+    if (xmlEntity.get() != null) {
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
+    }
+
+    return result;
+  }
+
+  private boolean verifyDistributedRegionMbean(InternalCache cache, String regionName) {
+    int federationInterval =
+        cache.getInternalDistributedSystem().getConfig().getJmxManagerUpdateRate();
+    long timeEnd = System.currentTimeMillis() + federationInterval + 50;
+
+    for (; System.currentTimeMillis() <= timeEnd;) {
+      try {
+        DistributedRegionMXBean bean =
+            ManagementService.getManagementService(cache).getDistributedRegionMXBean(regionName);
+        if (bean == null) {
+          bean = ManagementService.getManagementService(cache)
+              .getDistributedRegionMXBean(Region.SEPARATOR + regionName);
+        }
+        if (bean != null) {
+          return true;
+        } else {
+          Thread.sleep(2);
+        }
+      } catch (Exception ignored) {
+      }
+    }
+    return false;
+  }
+
+  void validateRegionFunctionArgs(InternalCache cache, RegionFunctionArgs regionFunctionArgs) {
+    if (regionFunctionArgs.getRegionPath() == null) {
+      throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
+    }
+
+    DistributedSystemMXBean dsMBean = getDSMBean(cache);
+
+    String useAttributesFrom = regionFunctionArgs.getUseAttributesFrom();
+    if (useAttributesFrom != null && !useAttributesFrom.isEmpty()
+        && regionExists(cache, useAttributesFrom)) {
+      if (!regionExists(cache, useAttributesFrom)) { // check already done in createRegion !!!
+        throw new IllegalArgumentException(CliStrings.format(
+            CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
+            new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
+      }
+      if (!regionFunctionArgs.isSetUseAttributesFrom()
+          || regionFunctionArgs.getRegionAttributes() == null) {
+        throw new IllegalArgumentException(CliStrings.format(
+            CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS,
+            useAttributesFrom));
+      }
+    }
+
+    if (regionFunctionArgs.hasPartitionAttributes()) {
+      RegionFunctionArgs.PartitionArgs partitionArgs = regionFunctionArgs.getPartitionArgs();
+      String colocatedWith = partitionArgs.getPrColocatedWith();
+      if (colocatedWith != null && !colocatedWith.isEmpty()) {
+        String[] listAllRegionPaths = dsMBean.listAllRegionPaths();
+        String foundRegionPath = null;
+        for (String regionPath : listAllRegionPaths) {
+          if (regionPath.equals(colocatedWith)) {
+            foundRegionPath = regionPath;
+            break;
+          }
+        }
+        if (foundRegionPath == null) {
+          throw new IllegalArgumentException(CliStrings.format(
+              CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
+              new Object[] {CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith}));
+        }
+        ManagementService mgmtService = ManagementService.getExistingManagementService(cache);
+        DistributedRegionMXBean distributedRegionMXBean =
+            mgmtService.getDistributedRegionMXBean(foundRegionPath);
+        String regionType = distributedRegionMXBean.getRegionType();
+        if (!(DataPolicy.PARTITION.toString().equals(regionType)
+            || DataPolicy.PERSISTENT_PARTITION.toString().equals(regionType))) {
+          throw new IllegalArgumentException(CliStrings.format(
+              CliStrings.CREATE_REGION__MSG__COLOCATEDWITH_REGION_0_IS_NOT_PARTITIONEDREGION,
+              new Object[] {colocatedWith}));
+        }
+      }
+      if (partitionArgs.isSetPRLocalMaxMemory()) {
+        int prLocalMaxMemory = partitionArgs.getPrLocalMaxMemory();
+        if (prLocalMaxMemory < 0) {
+          throw new IllegalArgumentException(
+              LocalizedStrings.AttributesFactory_PARTITIONATTRIBUTES_LOCALMAXMEMORY_MUST_NOT_BE_NEGATIVE
+                  .toLocalizedString());
+        }
+      }
+      if (partitionArgs.isSetPRTotalMaxMemory()) {
+        long prTotalMaxMemory = partitionArgs.getPrTotalMaxMemory();
+        if (prTotalMaxMemory <= 0) {
+          throw new IllegalArgumentException(
+              LocalizedStrings.AttributesFactory_TOTAL_SIZE_OF_PARTITION_REGION_MUST_BE_0
+                  .toLocalizedString());
+        }
+      }
+      if (partitionArgs.isSetPRRedundantCopies()) {
+        int prRedundantCopies = partitionArgs.getPrRedundantCopies();
+        switch (prRedundantCopies) {
+          case 0:
+          case 1:
+          case 2:
+          case 3:
+            break;
+          default:
+            throw new IllegalArgumentException(CliStrings.format(
+                CliStrings.CREATE_REGION__MSG__REDUNDANT_COPIES_SHOULD_BE_ONE_OF_0123,
+                new Object[] {prRedundantCopies}));
+        }
+      }
+    }
+
+    String keyConstraint = regionFunctionArgs.getKeyConstraint();
+    if (keyConstraint != null && !RegionCommandsUtils.isClassNameValid(keyConstraint)) {
+      throw new IllegalArgumentException(CliStrings.format(
+          CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_KEYCONSTRAINT_0_IS_INVALID,
+          new Object[] {keyConstraint}));
+    }
+
+    String valueConstraint = regionFunctionArgs.getValueConstraint();
+    if (valueConstraint != null && !RegionCommandsUtils.isClassNameValid(valueConstraint)) {
+      throw new IllegalArgumentException(CliStrings.format(
+          CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_VALUECONSTRAINT_0_IS_INVALID,
+          new Object[] {valueConstraint}));
+    }
+
+    Set<String> cacheListeners = regionFunctionArgs.getCacheListeners();
+    if (cacheListeners != null && !cacheListeners.isEmpty()) {
+      for (String cacheListener : cacheListeners) {
+        if (!RegionCommandsUtils.isClassNameValid(cacheListener)) {
+          throw new IllegalArgumentException(CliStrings.format(
+              CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
+              new Object[] {cacheListener}));
+        }
+      }
+    }
+
+    String cacheLoader = regionFunctionArgs.getCacheLoader();
+    if (cacheLoader != null && !RegionCommandsUtils.isClassNameValid(cacheLoader)) {
+      throw new IllegalArgumentException(CliStrings.format(
+          CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
+          new Object[] {cacheLoader}));
+    }
+
+    String cacheWriter = regionFunctionArgs.getCacheWriter();
+    if (cacheWriter != null && !RegionCommandsUtils.isClassNameValid(cacheWriter)) {
+      throw new IllegalArgumentException(CliStrings.format(
+          CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
+          new Object[] {cacheWriter}));
+    }
+
+    Set<String> gatewaySenderIds = regionFunctionArgs.getGatewaySenderIds();
+    if (gatewaySenderIds != null && !gatewaySenderIds.isEmpty()) {
+      String[] gatewaySenders = dsMBean.listGatewaySenders();
+      if (gatewaySenders.length == 0) {
+        throw new IllegalArgumentException(
+            CliStrings.CREATE_REGION__MSG__NO_GATEWAYSENDERS_IN_THE_SYSTEM);
+      } else {
+        List<String> gatewaySendersList = new ArrayList<>(Arrays.asList(gatewaySenders));
+        gatewaySenderIds = new HashSet<>(gatewaySenderIds);
+        gatewaySenderIds.removeAll(gatewaySendersList);
+        if (!gatewaySenderIds.isEmpty()) {
+          throw new IllegalArgumentException(CliStrings.format(
+              CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_GATEWAYSENDER_ID_UNKNOWN_0,
+              new Object[] {gatewaySenderIds}));
+        }
+      }
+    }
+
+    if (regionFunctionArgs.isSetConcurrencyLevel()) {
+      int concurrencyLevel = regionFunctionArgs.getConcurrencyLevel();
+      if (concurrencyLevel < 0) {
+        throw new IllegalArgumentException(CliStrings.format(
+            CliStrings.CREATE_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_CONCURRENCYLEVEL_0_IS_NOT_VALID,
+            new Object[] {concurrencyLevel}));
+      }
+    }
+
+    String diskStore = regionFunctionArgs.getDiskStore();
+    if (diskStore != null) {
+      RegionShortcut regionShortcut = regionFunctionArgs.getRegionShortcut();
+      if (regionShortcut != null
+          && !RegionCommandsUtils.PERSISTENT_OVERFLOW_SHORTCUTS.contains(regionShortcut)) {
+        String subMessage =
+            LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
+        String message = subMessage + ". "
+            + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0,
+                new Object[] {String.valueOf(RegionCommandsUtils.PERSISTENT_OVERFLOW_SHORTCUTS)});
+
+        throw new IllegalArgumentException(message);
+      }
+
+      RegionAttributes<?, ?> regionAttributes = regionFunctionArgs.getRegionAttributes();
+      if (regionAttributes != null && !regionAttributes.getDataPolicy().withPersistence()) {
+        String subMessage =
+            LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
+        String message = subMessage + ". "
+            + CliStrings.format(
+                CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FROM_REGION_0_IS_NOT_WITH_PERSISTENCE,
+                new Object[] {String.valueOf(regionFunctionArgs.getUseAttributesFrom())});
+
+        throw new IllegalArgumentException(message);
+      }
+
+      if (!diskStoreExists(cache, diskStore)) {
+        throw new IllegalArgumentException(CliStrings.format(
+            CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_DISKSTORE_UNKNOWN_DISKSTORE_0,
+            new Object[] {diskStore}));
+      }
+    }
+
+    RegionFunctionArgs.ExpirationAttrs entryExpirationIdleTime =
+        regionFunctionArgs.getEntryExpirationIdleTime();
+    RegionFunctionArgs.ExpirationAttrs entryExpirationTTL =
+        regionFunctionArgs.getEntryExpirationTTL();
+    RegionFunctionArgs.ExpirationAttrs regionExpirationIdleTime =
+        regionFunctionArgs.getRegionExpirationIdleTime();
+    RegionFunctionArgs.ExpirationAttrs regionExpirationTTL =
+        regionFunctionArgs.getRegionExpirationTTL();
+
+    if ((!regionFunctionArgs.isSetStatisticsEnabled() || !regionFunctionArgs.isStatisticsEnabled())
+        && (entryExpirationIdleTime != null || entryExpirationTTL != null
+            || regionExpirationIdleTime != null || regionExpirationTTL != null)) {
+      String message = LocalizedStrings.AttributesFactory_STATISTICS_MUST_BE_ENABLED_FOR_EXPIRATION
+          .toLocalizedString();
+      throw new IllegalArgumentException(message + ".");
+    }
+
+    boolean compressorFailure = false;
+    if (regionFunctionArgs.isSetCompressor()) {
+      String compressorClassName = regionFunctionArgs.getCompressor();
+      Object compressor = null;
+      try {
+        Class<?> compressorClass = ClassPathLoader.getLatest().forName(compressorClassName);
+        compressor = compressorClass.newInstance();
+      } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
+        compressorFailure = true;
+      }
+
+      if (compressorFailure || !(compressor instanceof Compressor)) {
+        throw new IllegalArgumentException(
+            CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_COMPRESSOR,
+                new Object[] {regionFunctionArgs.getCompressor()}));
+      }
+    }
+
+    if (regionFunctionArgs.hasPartitionAttributes()) {
+      if (regionFunctionArgs.isPartitionResolverSet()) {
+        String partitionResolverClassName = regionFunctionArgs.getPartitionResolver();
+        try {
+          Class<PartitionResolver> resolverClass = (Class<PartitionResolver>) ClassPathLoader
+              .getLatest().forName(partitionResolverClassName);
+          PartitionResolver partitionResolver = resolverClass.newInstance();
+        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
+          throw new IllegalArgumentException(
+              CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER,
+                  new Object[] {regionFunctionArgs.getPartitionResolver()}),
+              e);
+        }
+      }
+    }
+  }
+
+  private static <K, V> FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> getRegionAttributes(
+      InternalCache cache, String regionPath) {
+    if (!isClusterWideSameConfig(cache, regionPath)) {
+      throw new IllegalStateException(CliStrings.format(
+          CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FORM_REGIONS_EXISTS_BUT_DIFFERENT_SCOPE_OR_DATAPOLICY_USE_DESCRIBE_REGION_FOR_0,
+          regionPath));
+    }
+    FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> attributes = null;
+
+    // First check whether the region exists on a this manager, if yes then no
+    // need to use FetchRegionAttributesFunction to fetch RegionAttributes
+    try {
+      attributes = FetchRegionAttributesFunction.getRegionAttributes(regionPath);
+    } catch (IllegalArgumentException e) {
+      /* region doesn't exist on the manager */
+    }
+
+    if (attributes == null) {
+      // find first member which has the region
+      Set<DistributedMember> regionAssociatedMembers =
+          CliUtil.getRegionAssociatedMembers(regionPath, cache, false);
+      if (regionAssociatedMembers != null && !regionAssociatedMembers.isEmpty()) {
+        DistributedMember distributedMember = regionAssociatedMembers.iterator().next();
+        ResultCollector<?, ?> resultCollector = CliUtil
+            .executeFunction(FetchRegionAttributesFunction.INSTANCE, regionPath, distributedMember);
+        List<?> resultsList = (List<?>) resultCollector.getResult();
+
+        if (resultsList != null && !resultsList.isEmpty()) {
+          for (Object object : resultsList) {
+            if (object instanceof IllegalArgumentException) {
+              throw (IllegalArgumentException) object;
+            } else if (object instanceof Throwable) {
+              Throwable th = (Throwable) object;
+              LogWrapper.getInstance().info(CliUtil.stackTraceAsString((th)));
+              throw new IllegalArgumentException(CliStrings.format(
+                  CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1,
+                  new Object[] {regionPath, th.getMessage()}));
+            } else { // has to be RegionAttributes
+              @SuppressWarnings("unchecked") // to avoid warning :(
+              FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> regAttr =
+                  ((FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V>) object);
+              if (attributes == null) {
+                attributes = regAttr;
+                break;
+              } // attributes null check
+            } // not IllegalArgumentException or other throwable
+          } // iterate over list - there should be only one result in the list
+        } // result list is not null or empty
+      } // regionAssociatedMembers is not-empty
+    } // attributes are null because do not exist on local member
+
+    return attributes;
+  }
+
+  private static boolean isClusterWideSameConfig(InternalCache cache, String regionPath) {
+    ManagementService managementService = ManagementService.getExistingManagementService(cache);
+
+    DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
+
+    Set<DistributedMember> allMembers = CliUtil.getAllNormalMembers(cache);
+
+    RegionAttributesData regionAttributesToValidateAgainst = null;
+    for (DistributedMember distributedMember : allMembers) {
+      ObjectName regionObjectName;
+      try {
+        regionObjectName = dsMXBean
+            .fetchRegionObjectName(CliUtil.getMemberNameOrId(distributedMember), regionPath);
+        RegionMXBean regionMBean =
+            managementService.getMBeanInstance(regionObjectName, RegionMXBean.class);
+        RegionAttributesData regionAttributes = regionMBean.listRegionAttributes();
+
+        if (regionAttributesToValidateAgainst == null) {
+          regionAttributesToValidateAgainst = regionAttributes;
+        } else if (!(regionAttributesToValidateAgainst.getScope()
+            .equals(regionAttributes.getScope())
+            || regionAttributesToValidateAgainst.getDataPolicy()
+                .equals(regionAttributes.getDataPolicy()))) {
+          return false;
+        }
+      } catch (Exception e) {
+        // ignore
+      }
+    }
+
+    return true;
+  }
+
+  static boolean regionExists(InternalCache cache, String regionPath) {
+    if (regionPath == null || Region.SEPARATOR.equals(regionPath)) {
+      return false;
+    }
+
+    ManagementService managementService = ManagementService.getExistingManagementService(cache);
+    DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean();
+
+    String[] allRegionPaths = dsMBean.listAllRegionPaths();
+    return Arrays.stream(allRegionPaths).anyMatch(regionPath::equals);
+  }
+
+  private boolean diskStoreExists(InternalCache cache, String diskStoreName) {
+    ManagementService managementService = ManagementService.getExistingManagementService(cache);
+    DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
+    Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
+
+    Set<Map.Entry<String, String[]>> entrySet = diskstore.entrySet();
+
+    for (Map.Entry<String, String[]> entry : entrySet) {
+      String[] value = entry.getValue();
+      if (CliUtil.contains(value, diskStoreName)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  private void validateRegionPathAndParent(InternalCache cache, String regionPath) {
+    if (StringUtils.isEmpty(regionPath)) {
+      throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
+    }
+    // If a region path indicates a sub-region, check whether the parent region exists
+    RegionPath regionPathData = new RegionPath(regionPath);
+    String parentRegionPath = regionPathData.getParent();
+    if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) {
+      if (!regionExists(cache, parentRegionPath)) {
+        throw new IllegalArgumentException(
+            CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOES_NOT_EXIST,
+                new Object[] {regionPath}));
+      }
+    }
+  }
+
+  private boolean isPersistentShortcut(RegionShortcut shortcut) {
+    return shortcut == RegionShortcut.LOCAL_PERSISTENT
+        || shortcut == RegionShortcut.LOCAL_PERSISTENT_OVERFLOW
+        || shortcut == RegionShortcut.PARTITION_PERSISTENT
+        || shortcut == RegionShortcut.PARTITION_PERSISTENT_OVERFLOW
+        || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT
+        || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW
+        || shortcut == RegionShortcut.REPLICATE_PERSISTENT
+        || shortcut == RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW;
+  }
+
+  private boolean isAttributePersistent(RegionAttributes attributes) {
+    return attributes != null && attributes.getDataPolicy() != null
+        && attributes.getDataPolicy().toString().contains("PERSISTENT");
+  }
+
+  DistributedSystemMXBean getDSMBean(InternalCache cache) {
+    ManagementService managementService = ManagementService.getExistingManagementService(cache);
+    return managementService.getDistributedSystemMXBean();
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommand.java
new file mode 100644
index 0000000..12b6dc1
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommand.java
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.management.internal.cli.commands;
+
+import java.text.MessageFormat;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.LogWriter;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.Scope;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.RegionAttributesData;
+import org.apache.geode.management.RegionMXBean;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.MBeanJMXAdapter;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.RegionDestroyFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DestroyRegionCommand implements GfshCommand {
+  @CliCommand(value = {CliStrings.DESTROY_REGION}, help = CliStrings.DESTROY_REGION__HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+  @ResourceOperation(resource = ResourcePermission.Resource.DATA,
+      operation = ResourcePermission.Operation.MANAGE)
+  public Result destroyRegion(
+      @CliOption(key = CliStrings.DESTROY_REGION__REGION, optionContext = ConverterHint.REGION_PATH,
+          mandatory = true, help = CliStrings.DESTROY_REGION__REGION__HELP) String regionPath) {
+
+    if (regionPath == null) {
+      return ResultBuilder
+          .createInfoResult(CliStrings.DESTROY_REGION__MSG__SPECIFY_REGIONPATH_TO_DESTROY);
+    }
+
+    if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
+      return ResultBuilder.createInfoResult(CliStrings.format(
+          CliStrings.DESTROY_REGION__MSG__REGIONPATH_0_NOT_VALID, new Object[] {regionPath}));
+    }
+
+    Result result;
+    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+    try {
+      InternalCache cache = getCache();
+      ManagementService managementService = ManagementService.getExistingManagementService(cache);
+      String regionPathToUse = regionPath;
+
+      if (!regionPathToUse.startsWith(Region.SEPARATOR)) {
+        regionPathToUse = Region.SEPARATOR + regionPathToUse;
+      }
+
+      Set<DistributedMember> regionMembersList =
+          findMembersForRegion(cache, managementService, regionPathToUse);
+
+      if (regionMembersList.size() == 0) {
+        return ResultBuilder.createUserErrorResult(
+            CliStrings.format(CliStrings.DESTROY_REGION__MSG__COULD_NOT_FIND_REGIONPATH_0_IN_GEODE,
+                regionPath, "jmx-manager-update-rate milliseconds"));
+      }
+
+      CliFunctionResult destroyRegionResult;
+
+      ResultCollector<?, ?> resultCollector =
+          CliUtil.executeFunction(RegionDestroyFunction.INSTANCE, regionPath, regionMembersList);
+      List<CliFunctionResult> resultsList = (List<CliFunctionResult>) resultCollector.getResult();
+      String message =
+          CliStrings.format(CliStrings.DESTROY_REGION__MSG__REGION_0_1_DESTROYED, regionPath, "");
+
+      // Only if there is an error is this set to false
+      boolean isRegionDestroyed = true;
+      for (CliFunctionResult aResultsList : resultsList) {
+        destroyRegionResult = aResultsList;
+        if (destroyRegionResult.isSuccessful()) {
+          xmlEntity.set(destroyRegionResult.getXmlEntity());
+        } else if (destroyRegionResult.getThrowable() != null) {
+          Throwable t = destroyRegionResult.getThrowable();
+          LogWrapper.getInstance().info(t.getMessage(), t);
+          message = CliStrings.format(
+              CliStrings.DESTROY_REGION__MSG__ERROR_OCCURRED_WHILE_DESTROYING_0_REASON_1,
+              regionPath, t.getMessage());
+          isRegionDestroyed = false;
+        } else {
+          message = CliStrings.format(
+              CliStrings.DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1,
+              regionPath, destroyRegionResult.getMessage());
+          isRegionDestroyed = false;
+        }
+      }
+      if (isRegionDestroyed) {
+        result = ResultBuilder.createInfoResult(message);
+      } else {
+        result = ResultBuilder.createUserErrorResult(message);
+      }
+    } catch (IllegalStateException e) {
+      result = ResultBuilder.createUserErrorResult(CliStrings.format(
+          CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, regionPath,
+          e.getMessage()));
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(CliStrings.format(
+          CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, regionPath,
+          e.getMessage()));
+    }
+
+    if (xmlEntity.get() != null) {
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null));
+    }
+
+    return result;
+  }
+
+  private Set<DistributedMember> findMembersForRegion(InternalCache cache,
+      ManagementService managementService, String regionPath) {
+    Set<DistributedMember> membersList = new HashSet<>();
+    Set<String> regionMemberIds = new HashSet<>();
+    MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
+
+    // needs to be escaped with quotes if it contains a hyphen
+    if (regionPath.contains("-")) {
+      regionPath = "\"" + regionPath + "\"";
+    }
+
+    String queryExp =
+        MessageFormat.format(MBeanJMXAdapter.OBJECTNAME__REGION_MXBEAN, regionPath, "*");
+
+    try {
+      ObjectName queryExpON = new ObjectName(queryExp);
+      Set<ObjectName> queryNames = mbeanServer.queryNames(null, queryExpON);
+      if (queryNames == null || queryNames.isEmpty()) {
+        return membersList; // protects against null pointer exception below
+      }
+
+      boolean addedOneRemote = false;
+      for (ObjectName regionMBeanObjectName : queryNames) {
+        try {
+          RegionMXBean regionMXBean =
+              managementService.getMBeanInstance(regionMBeanObjectName, RegionMXBean.class);
+          if (regionMXBean != null) {
+            RegionAttributesData regionAttributes = regionMXBean.listRegionAttributes();
+            String scope = regionAttributes.getScope();
+            // For Scope.LOCAL regions we need to identify each hosting member, but for
+            // other scopes we just need a single member as the region destroy will be
+            // propagated.
+            if (Scope.LOCAL.equals(Scope.fromString(scope))) {
+              regionMemberIds.add(regionMXBean.getMember());
+            } else {
+              if (!addedOneRemote) {
+                regionMemberIds.add(regionMXBean.getMember());
+                addedOneRemote = true;
+              }
+            }
+          }
+        } catch (ClassCastException e) {
+          LogWriter logger = cache.getLogger();
+          if (logger.finerEnabled()) {
+            logger.finer(regionMBeanObjectName + " is not a " + RegionMXBean.class.getSimpleName(),
+                e);
+          }
+        }
+      }
+
+      if (!regionMemberIds.isEmpty()) {
+        membersList = getMembersByIds(cache, regionMemberIds);
+      }
+    } catch (MalformedObjectNameException | NullPointerException e) {
+      LogWrapper.getInstance().info(e.getMessage(), e);
+    }
+
+    return membersList;
+  }
+
+  private Set<DistributedMember> getMembersByIds(InternalCache cache, Set<String> memberIds) {
+    Set<DistributedMember> foundMembers = Collections.emptySet();
+    if (memberIds != null && !memberIds.isEmpty()) {
+      foundMembers = new HashSet<>();
+      Set<DistributedMember> allNormalMembers = CliUtil.getAllNormalMembers(cache);
+
+      for (String memberId : memberIds) {
+        for (DistributedMember distributedMember : allNormalMembers) {
+          if (memberId.equals(distributedMember.getId())
+              || memberId.equals(distributedMember.getName())) {
+            foundMembers.add(distributedMember);
+          }
+        }
+      }
+    }
+    return foundMembers;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommandsUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommandsUtils.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommandsUtils.java
new file mode 100644
index 0000000..1885b92
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommandsUtils.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.regex.Pattern;
+
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+
+public class RegionCommandsUtils {
+
+  public static final Set<RegionShortcut> PERSISTENT_OVERFLOW_SHORTCUTS = new TreeSet<>();
+
+  static {
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_OVERFLOW);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_OVERFLOW);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_OVERFLOW);
+    PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
+  }
+
+  static void validateGroups(InternalCache cache, String[] groups) {
+    if (groups != null && groups.length != 0) {
+      Set<String> existingGroups = new HashSet<>();
+      Set<DistributedMember> members = CliUtil.getAllNormalMembers(cache);
+      for (DistributedMember distributedMember : members) {
+        List<String> memberGroups = distributedMember.getGroups();
+        existingGroups.addAll(memberGroups);
+      }
+      List<String> groupsList = new ArrayList<>(Arrays.asList(groups));
+      groupsList.removeAll(existingGroups);
+
+      if (!groupsList.isEmpty()) {
+        throw new IllegalArgumentException(
+            CliStrings.format(CliStrings.CREATE_REGION__MSG__GROUPS_0_ARE_INVALID,
+                new Object[] {String.valueOf(groupsList)}));
+      }
+    }
+  }
+
+  static boolean isClassNameValid(String fqcn) {
+    if (fqcn.isEmpty()) {
+      return true;
+    }
+    String regex = "([\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*";
+    return Pattern.matches(regex, fqcn);
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
index 6ae10a3..45cb104 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
@@ -43,7 +43,7 @@ import org.apache.geode.internal.cache.xmlcache.CacheXml;
 import org.apache.geode.internal.i18n.LocalizedStrings;
 import org.apache.geode.internal.logging.LogService;
 import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.commands.CreateAlterDestroyRegionCommands;
+import org.apache.geode.management.internal.cli.commands.RegionCommandsUtils;
 import org.apache.geode.management.internal.cli.exceptions.CreateSubregionException;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.util.RegionPath;
@@ -100,9 +100,9 @@ public class RegionCreateFunction extends FunctionAdapter implements InternalEnt
       String localizedString =
           LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
       if (localizedString.equals(e.getMessage())) {
-        exceptionMsg = exceptionMsg + " " + CliStrings
-            .format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0, new Object[] {
-                String.valueOf(CreateAlterDestroyRegionCommands.PERSISTENT_OVERFLOW_SHORTCUTS)});
+        exceptionMsg = exceptionMsg + " "
+            + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0,
+                new Object[] {String.valueOf(RegionCommandsUtils.PERSISTENT_OVERFLOW_SHORTCUTS)});
       }
       resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, null/* do not log */));
     } catch (IllegalArgumentException e) {

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java b/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
index 94ff50c..a626c62 100644
--- a/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
+++ b/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
@@ -40,14 +40,14 @@ import org.apache.geode.cache.query.QueryInvalidException;
 import org.apache.geode.cache.query.QueryService;
 import org.apache.geode.cache.query.RegionNotFoundException;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.redis.internal.executor.ExpirationExecutor;
-import org.apache.geode.redis.internal.executor.ListQuery;
-import org.apache.geode.redis.internal.executor.SortedSetQuery;
 import org.apache.geode.internal.hll.HyperLogLogPlus;
 import org.apache.geode.management.cli.Result;
 import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.commands.CreateAlterDestroyRegionCommands;
+import org.apache.geode.management.internal.cli.commands.CreateRegionCommand;
 import org.apache.geode.redis.GeodeRedisServer;
+import org.apache.geode.redis.internal.executor.ExpirationExecutor;
+import org.apache.geode.redis.internal.executor.ListQuery;
+import org.apache.geode.redis.internal.executor.SortedSetQuery;
 
 /**
  * This class stands between {@link Executor} and {@link Cache#getRegion(String)}. This is needed
@@ -85,8 +85,7 @@ public class RegionProvider implements Closeable {
   private final ConcurrentMap<ByteArrayWrapper, ScheduledFuture<?>> expirationsMap;
   private final ScheduledExecutorService expirationExecutor;
   private final RegionShortcut defaultRegionType;
-  private static final CreateAlterDestroyRegionCommands cliCmds =
-      new CreateAlterDestroyRegionCommands();
+  private static final CreateRegionCommand createRegionCmd = new CreateRegionCommand();
   private final ConcurrentHashMap<String, Lock> locks;
 
   public RegionProvider(Region<ByteArrayWrapper, ByteArrayWrapper> stringsRegion,
@@ -400,10 +399,10 @@ public class RegionProvider implements Closeable {
     if (r != null)
       return r;
     do {
-      Result result = cliCmds.createRegion(key, defaultRegionType, null, null, true, null, null,
+      Result result = createRegionCmd.createRegion(key, defaultRegionType, null, null, true, null,
           null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
           null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
-          null, null);
+          null, null, null);
       r = cache.getRegion(key);
       if (result.getStatus() == Status.ERROR && r == null) {
         String err = "";


[24/47] geode git commit: GEODE-3436: Restore refactoring of DiskStoreCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java
new file mode 100644
index 0000000..eb2b544
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java
@@ -0,0 +1,149 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.execute.AbstractExecution;
+import org.apache.geode.internal.cache.partitioned.ColocatedRegionDetails;
+import org.apache.geode.internal.cache.persistence.PersistentMemberPattern;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.functions.ShowMissingDiskStoresFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.ResultDataException;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ShowMissingDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.SHOW_MISSING_DISK_STORE,
+      help = CliStrings.SHOW_MISSING_DISK_STORE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result showMissingDiskStore() {
+
+    try {
+      Set<DistributedMember> dataMembers = DiskStoreCommandsUtils.getNormalMembers(getCache());
+
+      if (dataMembers.isEmpty()) {
+        return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
+      }
+      List<Object> results = getMissingDiskStoresList(dataMembers);
+      return toMissingDiskStoresTabularResult(results);
+    } catch (FunctionInvocationTargetException ignore) {
+      return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+          CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.SHOW_MISSING_DISK_STORE));
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable t) {
+      SystemFailure.checkFailure();
+      if (t.getMessage() == null) {
+        return ResultBuilder.createGemFireErrorResult(
+            String.format(CliStrings.SHOW_MISSING_DISK_STORE__ERROR_MESSAGE, t));
+      }
+      return ResultBuilder.createGemFireErrorResult(
+          String.format(CliStrings.SHOW_MISSING_DISK_STORE__ERROR_MESSAGE, t.getMessage()));
+    }
+  }
+
+  private List<Object> getMissingDiskStoresList(Set<DistributedMember> members) {
+    final Execution membersFunctionExecutor = getMembersFunctionExecutor(members);
+    if (membersFunctionExecutor instanceof AbstractExecution) {
+      ((AbstractExecution) membersFunctionExecutor).setIgnoreDepartedMembers(true);
+    }
+
+    final ResultCollector<?, ?> resultCollector =
+        membersFunctionExecutor.execute(new ShowMissingDiskStoresFunction());
+
+    final List<?> results = (List<?>) resultCollector.getResult();
+    final List<Object> distributedPersistentRecoveryDetails = new ArrayList<>(results.size());
+    for (final Object result : results) {
+      if (result instanceof Set) {
+        distributedPersistentRecoveryDetails.addAll((Set<Object>) result);
+      }
+    }
+    return distributedPersistentRecoveryDetails;
+  }
+
+  private Result toMissingDiskStoresTabularResult(final List<Object> resultDetails)
+      throws ResultDataException {
+    CompositeResultData crd = ResultBuilder.createCompositeResultData();
+    List<PersistentMemberPattern> missingDiskStores = new ArrayList<>();
+    List<ColocatedRegionDetails> missingColocatedRegions = new ArrayList<>();
+
+    for (Object detail : resultDetails) {
+      if (detail instanceof PersistentMemberPattern) {
+        missingDiskStores.add((PersistentMemberPattern) detail);
+      } else if (detail instanceof ColocatedRegionDetails) {
+        missingColocatedRegions.add((ColocatedRegionDetails) detail);
+      } else {
+        throw new ResultDataException("Unknown type of PersistentRecoveryFailures result");
+      }
+    }
+
+    boolean hasMissingDiskStores = !missingDiskStores.isEmpty();
+    boolean hasMissingColocatedRegions = !missingColocatedRegions.isEmpty();
+    if (hasMissingDiskStores) {
+      CompositeResultData.SectionResultData missingDiskStoresSection = crd.addSection();
+      missingDiskStoresSection.setHeader("Missing Disk Stores");
+      TabularResultData missingDiskStoreData = missingDiskStoresSection.addTable();
+
+      for (PersistentMemberPattern persistentMemberDetails : missingDiskStores) {
+        missingDiskStoreData.accumulate("Disk Store ID", persistentMemberDetails.getUUID());
+        missingDiskStoreData.accumulate("Host", persistentMemberDetails.getHost());
+        missingDiskStoreData.accumulate("Directory", persistentMemberDetails.getDirectory());
+      }
+    } else {
+      CompositeResultData.SectionResultData noMissingDiskStores = crd.addSection();
+      noMissingDiskStores.setHeader("No missing disk store found");
+    }
+    if (hasMissingDiskStores || hasMissingColocatedRegions) {
+      // For clarity, separate disk store and colocated region information
+      crd.addSection().setHeader("\n");
+    }
+
+    if (hasMissingColocatedRegions) {
+      CompositeResultData.SectionResultData missingRegionsSection = crd.addSection();
+      missingRegionsSection.setHeader("Missing Colocated Regions");
+      TabularResultData missingRegionData = missingRegionsSection.addTable();
+
+      for (ColocatedRegionDetails colocatedRegionDetails : missingColocatedRegions) {
+        missingRegionData.accumulate("Host", colocatedRegionDetails.getHost());
+        missingRegionData.accumulate("Distributed Member", colocatedRegionDetails.getMember());
+        missingRegionData.accumulate("Parent Region", colocatedRegionDetails.getParent());
+        missingRegionData.accumulate("Missing Colocated Region", colocatedRegionDetails.getChild());
+      }
+    } else {
+      CompositeResultData.SectionResultData noMissingColocatedRegions = crd.addSection();
+      noMissingColocatedRegions.setHeader("No missing colocated region found");
+    }
+    return ResultBuilder.buildResult(crd);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UpgradeOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UpgradeOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UpgradeOfflineDiskStoreCommand.java
new file mode 100644
index 0000000..85b86db
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UpgradeOfflineDiskStoreCommand.java
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.GemFireIOException;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParser;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
+import org.apache.geode.management.internal.cli.util.DiskStoreUpgrader;
+
+public class UpgradeOfflineDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.UPGRADE_OFFLINE_DISK_STORE,
+      help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  public Result upgradeOfflineDiskStore(
+      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME, mandatory = true,
+          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
+      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
+          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
+          unspecifiedDefaultValue = "-1",
+          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
+      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J,
+          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps)
+      throws InterruptedException {
+
+    Result result;
+    LogWrapper logWrapper = LogWrapper.getInstance();
+
+    StringBuilder output = new StringBuilder();
+    StringBuilder error = new StringBuilder();
+    StringBuilder errorMessage = new StringBuilder();
+    Process upgraderProcess = null;
+
+    try {
+      String validatedDirectories = DiskStoreCommandsUtils.validatedDirectories(diskDirs);
+      if (validatedDirectories != null) {
+        throw new IllegalArgumentException(
+            "Could not find " + CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + ": \""
+                + validatedDirectories + "\"");
+      }
+
+      List<String> commandList = new ArrayList<>();
+      commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+          + File.separatorChar + "java");
+
+      DiskStoreCommandsUtils.configureLogging(commandList);
+
+      if (jvmProps != null && jvmProps.length != 0) {
+        commandList.addAll(Arrays.asList(jvmProps));
+      }
+      commandList.add("-classpath");
+      commandList.add(System.getProperty("java.class.path", "."));
+      commandList.add(DiskStoreUpgrader.class.getName());
+
+      commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);
+
+      if (diskDirs != null && diskDirs.length != 0) {
+        StringBuilder builder = new StringBuilder();
+        int arrayLength = diskDirs.length;
+        for (int i = 0; i < arrayLength; i++) {
+          if (File.separatorChar == '\\') {
+            builder.append(diskDirs[i].replace("\\", "/")); // see 46120
+          } else {
+            builder.append(diskDirs[i]);
+          }
+          if (i + 1 != arrayLength) {
+            builder.append(',');
+          }
+        }
+        commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder.toString());
+      }
+      // -1 is ignore as maxOplogSize
+      commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);
+
+      ProcessBuilder procBuilder = new ProcessBuilder(commandList);
+      // procBuilder.redirectErrorStream(true);
+      upgraderProcess = procBuilder.start();
+      InputStream inputStream = upgraderProcess.getInputStream();
+      InputStream errorStream = upgraderProcess.getErrorStream();
+      BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
+      BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
+
+      String line;
+      while ((line = inputReader.readLine()) != null) {
+        output.append(line).append(GfshParser.LINE_SEPARATOR);
+      }
+
+      boolean switchToStackTrace = false;
+      while ((line = errorReader.readLine()) != null) {
+        if (!switchToStackTrace && DiskStoreUpgrader.STACKTRACE_START.equals(line)) {
+          switchToStackTrace = true;
+        } else if (switchToStackTrace) {
+          error.append(line).append(GfshParser.LINE_SEPARATOR);
+        } else {
+          errorMessage.append(line);
+        }
+      }
+
+      if (errorMessage.length() > 0) {
+        throw new GemFireIOException(errorMessage.toString());
+      }
+
+      upgraderProcess.destroy();
+      result = ResultBuilder.createInfoResult(output.toString());
+    } catch (IOException e) {
+      if (output.length() != 0) {
+        Gfsh.println(output.toString());
+      }
+      String fieldsMessage = (maxOplogSize != -1
+          ? CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize + "," : "");
+      fieldsMessage += CliUtil.arrayToString(diskDirs);
+      String errorString = CliStrings.format(
+          CliStrings.UPGRADE_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2,
+          diskStoreName, fieldsMessage);
+      result = ResultBuilder.createUserErrorResult(errorString);
+      if (logWrapper.fineEnabled()) {
+        logWrapper.fine(e.getMessage(), e);
+      }
+    } catch (GemFireIOException e) {
+      if (output.length() != 0) {
+        Gfsh.println(output.toString());
+      }
+      result = ResultBuilder.createUserErrorResult(errorMessage.toString());
+      if (logWrapper.fineEnabled()) {
+        logWrapper.fine(error.toString());
+      }
+    } catch (IllegalArgumentException e) {
+      if (output.length() != 0) {
+        Gfsh.println(output.toString());
+      }
+      result = ResultBuilder.createUserErrorResult(e.getMessage());
+    } finally {
+      if (upgraderProcess != null) {
+        try {
+          // just to check whether the process has exited
+          // Process.exitValue() throws IllegalStateException if Process is alive
+          upgraderProcess.exitValue();
+        } catch (IllegalThreadStateException itse) {
+          // not yet terminated, destroy the process
+          upgraderProcess.destroy();
+        }
+      }
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ValidateDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ValidateDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ValidateDiskStoreCommand.java
new file mode 100644
index 0000000..029b384
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ValidateDiskStoreCommand.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.GfshParser;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.util.DiskStoreValidater;
+
+public class ValidateDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.VALIDATE_DISK_STORE, help = CliStrings.VALIDATE_DISK_STORE__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  public Result validateDiskStore(
+      @CliOption(key = CliStrings.VALIDATE_DISK_STORE__NAME, mandatory = true,
+          help = CliStrings.VALIDATE_DISK_STORE__NAME__HELP) String diskStoreName,
+      @CliOption(key = CliStrings.VALIDATE_DISK_STORE__DISKDIRS, mandatory = true,
+          help = CliStrings.VALIDATE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+      @CliOption(key = CliStrings.VALIDATE_DISK_STORE__J,
+          help = CliStrings.VALIDATE_DISK_STORE__J__HELP) String[] jvmProps) {
+    try {
+      // create a new process ...bug 46075
+      StringBuilder dirList = new StringBuilder();
+      for (String diskDir : diskDirs) {
+        dirList.append(diskDir);
+        dirList.append(";");
+      }
+
+      List<String> commandList = new ArrayList<>();
+      commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+          + File.separatorChar + "java");
+
+      DiskStoreCommandsUtils.configureLogging(commandList);
+
+      if (jvmProps != null && jvmProps.length != 0) {
+        commandList.addAll(Arrays.asList(jvmProps));
+      }
+
+      // Pass any java options on to the command
+      String opts = System.getenv("JAVA_OPTS");
+      if (opts != null) {
+        commandList.add(opts);
+      }
+      commandList.add("-classpath");
+      commandList.add(System.getProperty("java.class.path", "."));
+      commandList.add(DiskStoreValidater.class.getName());
+      commandList.add(diskStoreName);
+      commandList.add(dirList.toString());
+
+      ProcessBuilder procBuilder = new ProcessBuilder(commandList);
+      StringBuilder output = new StringBuilder();
+      String errorString = "";
+
+      Process validateDiskStoreProcess = procBuilder.redirectErrorStream(true).start();
+      InputStream inputStream = validateDiskStoreProcess.getInputStream();
+      BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
+      String line;
+
+      while ((line = br.readLine()) != null) {
+        output.append(line).append(GfshParser.LINE_SEPARATOR);
+      }
+      validateDiskStoreProcess.destroy();
+
+      output.append(errorString).append(GfshParser.LINE_SEPARATOR);
+      String resultString =
+          "Validating " + diskStoreName + GfshParser.LINE_SEPARATOR + output.toString();
+      return ResultBuilder.createInfoResult(resultString);
+    } catch (IOException ex) {
+      return ResultBuilder.createGemFireErrorResult(CliStrings
+          .format(CliStrings.VALIDATE_DISK_STORE__MSG__IO_ERROR, diskStoreName, ex.getMessage()));
+    } catch (Exception ex) {
+      // StringPrintWriter s = new StringPrintWriter();
+      // ex.printStackTrace(s);
+      return ResultBuilder.createGemFireErrorResult(CliStrings
+          .format(CliStrings.VALIDATE_DISK_STORE__MSG__ERROR, diskStoreName, ex.getMessage()));
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java
index 2e06811..1f646d6 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java
@@ -25,6 +25,7 @@ import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
 import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.commands.ListDiskStoresCommand;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 
@@ -32,8 +33,21 @@ import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
  * The DiskStoreCommandsController class implements GemFire Management REST API web service
  * endpoints for the Gfsh Disk Store Commands.
  * <p/>
- * 
- * @see org.apache.geode.management.internal.cli.commands.DiskStoreCommands
+ *
+ * @see org.apache.geode.management.internal.cli.commands.AlterOfflineDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.BackupDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.CompactDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.CompactOfflineDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.CreateDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.DescribeOfflineDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.DestroyDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.ExportOfflineDiskStoreCommand
+ * @see ListDiskStoresCommand
+ * @see org.apache.geode.management.internal.cli.commands.RevokeMissingDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.ShowMissingDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.UpgradeOfflineDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.ValidateDiskStoreCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.PathVariable

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
index 07cdb11..1002f5d 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
@@ -36,7 +36,23 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+
 import org.apache.commons.io.FileUtils;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.DataPolicy;
@@ -76,28 +92,26 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.StringTokenizer;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.TimeUnit;
 
 /**
  * The DiskStoreCommandsDUnitTest class is a distributed test suite of test cases for testing the
  * disk store commands that are part of Gfsh.
  * </p>
  *
- * @see org.apache.geode.management.internal.cli.commands.DiskStoreCommands
+ * @see org.apache.geode.management.internal.cli.commands.AlterOfflineDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.BackupDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.CompactDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.CompactOfflineDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.CreateDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.DescribeOfflineDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.DestroyDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.ExportOfflineDiskStoreCommand
+ * @see ListDiskStoresCommand
+ * @see org.apache.geode.management.internal.cli.commands.RevokeMissingDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.ShowMissingDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.UpgradeOfflineDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.ValidateDiskStoreCommand
  * @see org.junit.Assert
  * @see org.junit.Test
  * @since GemFire 7.0

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
index 1902656..f8cd657 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
@@ -14,7 +14,10 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -49,10 +52,11 @@ import org.apache.geode.test.junit.categories.UnitTest;
 
 /**
  * The DiskStoreCommandsJUnitTest class is a test suite of test cases testing the contract and
- * functionality of the DiskStoreCommands class implementing commands in the GemFire shell (gfsh)
- * that access and modify disk stores in GemFire.
+ * functionality of the command classes relating to disk stores that implement commands in the
+ * GemFire shell (gfsh) that access and modify disk stores in GemFire.
  *
- * @see org.apache.geode.management.internal.cli.commands.DiskStoreCommands
+ * @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
+ * @see ListDiskStoresCommand
  * @see org.apache.geode.management.internal.cli.domain.DiskStoreDetails
  * @see org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction
  * @see org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction
@@ -61,6 +65,7 @@ import org.apache.geode.test.junit.categories.UnitTest;
  * @see org.jmock.lib.legacy.ClassImposteriser
  * @see org.junit.Assert
  * @see org.junit.Test
+ *
  * @since GemFire 7.0
  */
 @Category(UnitTest.class)
@@ -84,9 +89,14 @@ public class DiskStoreCommandsJUnitTest {
     mockContext = null;
   }
 
-  private DiskStoreCommands createDiskStoreCommands(final InternalCache cache,
+  private DescribeDiskStoreCommand createDescribeDiskStoreCommand(final InternalCache cache,
+      final DistributedMember distributedMember, final Execution functionExecutor) {
+    return new TestDescribeDiskStoreCommand(cache, distributedMember, functionExecutor);
+  }
+
+  private ListDiskStoresCommand createListDiskStoreCommand(final InternalCache cache,
       final DistributedMember distributedMember, final Execution functionExecutor) {
-    return new TestDiskStoreCommands(cache, distributedMember, functionExecutor);
+    return new TestListDiskStoresCommand(cache, distributedMember, functionExecutor);
   }
 
   private DiskStoreDetails createDiskStoreDetails(final String memberId,
@@ -123,15 +133,15 @@ public class DiskStoreCommandsJUnitTest {
         oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
         will(returnValue(mockResultCollector));
         oneOf(mockResultCollector).getResult();
-        will(returnValue(Arrays.asList(expectedDiskStoredDetails)));
+        will(returnValue(Collections.singletonList(expectedDiskStoredDetails)));
       }
     });
 
-    final DiskStoreCommands commands =
-        createDiskStoreCommands(mockCache, mockMember, mockFunctionExecutor);
+    final DescribeDiskStoreCommand describeCommand =
+        createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
 
     final DiskStoreDetails actualDiskStoreDetails =
-        commands.getDiskStoreDescription(memberId, diskStoreName);
+        describeCommand.getDiskStoreDescription(memberId, diskStoreName);
 
     assertNotNull(actualDiskStoreDetails);
     assertEquals(expectedDiskStoredDetails, actualDiskStoreDetails);
@@ -156,10 +166,11 @@ public class DiskStoreCommandsJUnitTest {
       }
     });
 
-    final DiskStoreCommands commands = createDiskStoreCommands(mockCache, mockMember, null);
+    final DescribeDiskStoreCommand describeCommand =
+        createDescribeDiskStoreCommand(mockCache, mockMember, null);
 
     try {
-      commands.getDiskStoreDescription(memberId, diskStoreName);
+      describeCommand.getDiskStoreDescription(memberId, diskStoreName);
     } catch (MemberNotFoundException expected) {
       assertEquals(CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberId),
           expected.getMessage());
@@ -192,11 +203,11 @@ public class DiskStoreCommandsJUnitTest {
       }
     });
 
-    final DiskStoreCommands commands =
-        createDiskStoreCommands(mockCache, mockMember, mockFunctionExecutor);
+    final DescribeDiskStoreCommand describeCommand =
+        createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
 
     try {
-      commands.getDiskStoreDescription(memberId, diskStoreName);
+      describeCommand.getDiskStoreDescription(memberId, diskStoreName);
     } catch (DiskStoreNotFoundException expected) {
       assertEquals("expected", expected.getMessage());
       throw expected;
@@ -228,11 +239,11 @@ public class DiskStoreCommandsJUnitTest {
       }
     });
 
-    final DiskStoreCommands commands =
-        createDiskStoreCommands(mockCache, mockMember, mockFunctionExecutor);
+    final DescribeDiskStoreCommand describeCommand =
+        createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
 
     try {
-      commands.getDiskStoreDescription(memberId, diskStoreName);
+      describeCommand.getDiskStoreDescription(memberId, diskStoreName);
     } catch (RuntimeException expected) {
       assertEquals("expected", expected.getMessage());
       throw expected;
@@ -265,15 +276,15 @@ public class DiskStoreCommandsJUnitTest {
         oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
         will(returnValue(mockResultCollector));
         oneOf(mockResultCollector).getResult();
-        will(returnValue(Arrays.asList(new Object())));
+        will(returnValue(Collections.singletonList(new Object())));
       }
     });
 
-    final DiskStoreCommands commands =
-        createDiskStoreCommands(mockCache, mockMember, mockFunctionExecutor);
+    final DescribeDiskStoreCommand describeCommand =
+        createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
 
     try {
-      commands.getDiskStoreDescription(memberId, diskStoreName);
+      describeCommand.getDiskStoreDescription(memberId, diskStoreName);
     } catch (RuntimeException expected) {
       assertEquals(
           CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
@@ -308,7 +319,7 @@ public class DiskStoreCommandsJUnitTest {
     final List<DiskStoreDetails> expectedDiskStores =
         Arrays.asList(diskStoreDetails1, diskStoreDetails2, diskStoreDetails3, diskStoreDetails4);
 
-    final List<Set<DiskStoreDetails>> results = new ArrayList<Set<DiskStoreDetails>>();
+    final List<Set<DiskStoreDetails>> results = new ArrayList<>();
 
     results.add(CollectionUtils.asSet(diskStoreDetails4, diskStoreDetails3));
     results.add(CollectionUtils.asSet(diskStoreDetails1, diskStoreDetails2));
@@ -323,11 +334,11 @@ public class DiskStoreCommandsJUnitTest {
       }
     });
 
-    final DiskStoreCommands commands =
-        createDiskStoreCommands(mockCache, mockDistributedMember, mockFunctionExecutor);
+    final ListDiskStoresCommand listCommand =
+        createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
 
     final List<DiskStoreDetails> actualDiskStores =
-        commands.getDiskStoreListing(commands.getNormalMembers(mockCache));
+        listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
 
     Assert.assertNotNull(actualDiskStores);
     assertEquals(expectedDiskStores, actualDiskStores);
@@ -349,11 +360,11 @@ public class DiskStoreCommandsJUnitTest {
       }
     });
 
-    final DiskStoreCommands commands =
-        createDiskStoreCommands(mockCache, mockDistributedMember, mockFunctionExecutor);
+    final ListDiskStoresCommand listCommand =
+        createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
 
     try {
-      commands.getDiskStoreListing(commands.getNormalMembers(mockCache));
+      listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
     } catch (RuntimeException expected) {
       assertEquals("expected", expected.getMessage());
       throw expected;
@@ -376,9 +387,9 @@ public class DiskStoreCommandsJUnitTest {
     final DiskStoreDetails diskStoreDetails =
         createDiskStoreDetails("memberOne", "cacheServerDiskStore");
 
-    final List<DiskStoreDetails> expectedDiskStores = Arrays.asList(diskStoreDetails);
+    final List<DiskStoreDetails> expectedDiskStores = Collections.singletonList(diskStoreDetails);
 
-    final List<Object> results = new ArrayList<Object>();
+    final List<Object> results = new ArrayList<>();
 
     results.add(CollectionUtils.asSet(diskStoreDetails));
     results.add(new FunctionInvocationTargetException("expected"));
@@ -393,23 +404,23 @@ public class DiskStoreCommandsJUnitTest {
       }
     });
 
-    final DiskStoreCommands commands =
-        createDiskStoreCommands(mockCache, mockDistributedMember, mockFunctionExecutor);
+    final ListDiskStoresCommand listCommand =
+        createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
 
     final List<DiskStoreDetails> actualDiskStores =
-        commands.getDiskStoreListing(commands.getNormalMembers(mockCache));
+        listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
 
     Assert.assertNotNull(actualDiskStores);
     assertEquals(expectedDiskStores, actualDiskStores);
   }
 
-  private static class TestDiskStoreCommands extends DiskStoreCommands {
+  private static class TestDescribeDiskStoreCommand extends DescribeDiskStoreCommand {
 
     private final InternalCache cache;
     private final DistributedMember distributedMember;
     private final Execution functionExecutor;
 
-    public TestDiskStoreCommands(final InternalCache cache,
+    TestDescribeDiskStoreCommand(final InternalCache cache,
         final DistributedMember distributedMember, final Execution functionExecutor) {
       assert cache != null : "The Cache cannot be null!";
       this.cache = cache;
@@ -433,12 +444,37 @@ public class DiskStoreCommandsJUnitTest {
       Assert.assertNotNull(members);
       return this.functionExecutor;
     }
+  }
+
+  private static class TestListDiskStoresCommand extends ListDiskStoresCommand {
+
+    private final InternalCache cache;
+    private final DistributedMember distributedMember;
+    private final Execution functionExecutor;
+
+    TestListDiskStoresCommand(final InternalCache cache, final DistributedMember distributedMember,
+        final Execution functionExecutor) {
+      assert cache != null : "The Cache cannot be null!";
+      this.cache = cache;
+      this.distributedMember = distributedMember;
+      this.functionExecutor = functionExecutor;
+    }
 
     @Override
-    protected Set<DistributedMember> getNormalMembers(final InternalCache cache) {
+    public InternalCache getCache() {
+      return this.cache;
+    }
+
+    @Override
+    public Set<DistributedMember> getMembers(final InternalCache cache) {
       assertSame(getCache(), cache);
       return Collections.singleton(this.distributedMember);
     }
-  }
 
+    @Override
+    public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
+      Assert.assertNotNull(members);
+      return this.functionExecutor;
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
index 8d4be8b..1fe0bd1 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
@@ -14,7 +14,25 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import org.apache.geode.cache.*;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertNotNull;
+import static org.apache.geode.test.dunit.Host.getHost;
+import static org.apache.geode.test.dunit.LogWriterUtils.getDUnitLogLevel;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+
+import java.io.Serializable;
+import java.util.Properties;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.DiskStore;
+import org.apache.geode.cache.DiskStoreFactory;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.Scope;
 import org.apache.geode.distributed.ConfigurationProperties;
 import org.apache.geode.management.cli.Result;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
@@ -22,18 +40,6 @@ import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.SerializableRunnableIF;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.Serializable;
-import java.util.Properties;
-
-import static org.apache.geode.test.dunit.Assert.assertEquals;
-import static org.apache.geode.test.dunit.Assert.assertNotNull;
-import static org.apache.geode.test.dunit.Host.getHost;
-import static org.apache.geode.test.dunit.LogWriterUtils.getDUnitLogLevel;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.distributed.ConfigurationProperties.*;
 
 /**
  * The ListAndDescribeDiskStoreCommandsDUnitTest class is a test suite of functional tests cases
@@ -41,7 +47,9 @@ import static org.apache.geode.distributed.ConfigurationProperties.*;
  * </p>
  *
  * @see org.apache.geode.management.internal.cli.commands.CliCommandTestBase
- * @see org.apache.geode.management.internal.cli.commands.DiskStoreCommands
+ * @see ListDiskStoresCommand
+ * @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
+ *
  * @since GemFire 7.0
  */
 @Category(DistributedTest.class)


[25/47] geode git commit: GEODE-3436: Restore refactoring of DiskStoreCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
deleted file mode 100644
index 84326c0..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
+++ /dev/null
@@ -1,1433 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.GemFireIOException;
-import org.apache.geode.SystemFailure;
-import org.apache.geode.admin.BackupStatus;
-import org.apache.geode.admin.internal.AdminDistributedSystemImpl;
-import org.apache.geode.cache.CacheExistsException;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.cache.persistence.PersistentID;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.DM;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
-import org.apache.geode.internal.cache.DiskStoreAttributes;
-import org.apache.geode.internal.cache.DiskStoreImpl;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.cache.execute.AbstractExecution;
-import org.apache.geode.internal.cache.partitioned.ColocatedRegionDetails;
-import org.apache.geode.internal.cache.persistence.PersistentMemberPattern;
-import org.apache.geode.internal.lang.ClassUtils;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParser;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.CreateDiskStoreFunction;
-import org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction;
-import org.apache.geode.management.internal.cli.functions.DestroyDiskStoreFunction;
-import org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction;
-import org.apache.geode.management.internal.cli.functions.ShowMissingDiskStoresFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.ResultDataException;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
-import org.apache.geode.management.internal.cli.util.DiskStoreCompacter;
-import org.apache.geode.management.internal.cli.util.DiskStoreNotFoundException;
-import org.apache.geode.management.internal.cli.util.DiskStoreUpgrader;
-import org.apache.geode.management.internal.cli.util.DiskStoreValidater;
-import org.apache.geode.management.internal.cli.util.MemberNotFoundException;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.messages.CompactRequest;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.geode.security.ResourcePermission.Target;
-
-/**
- * The DiskStoreCommands class encapsulates all GemFire Disk Store commands in Gfsh.
- *
- * @see GfshCommand
- * @since GemFire 7.0
- */
-@SuppressWarnings("unused")
-public class DiskStoreCommands implements GfshCommand {
-
-  protected Set<DistributedMember> getNormalMembers(final InternalCache cache) {
-    // TODO determine what this does (as it is untested and unmockable!)
-    return CliUtil.getAllNormalMembers(cache);
-  }
-
-  /**
-   * Internally, we also verify the resource operation permissions CLUSTER:WRITE:DISK if the region
-   * is persistent
-   */
-  @CliCommand(value = CliStrings.BACKUP_DISK_STORE, help = CliStrings.BACKUP_DISK_STORE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  @ResourceOperation(resource = Resource.DATA, operation = Operation.READ)
-  public Result backupDiskStore(
-      @CliOption(key = CliStrings.BACKUP_DISK_STORE__DISKDIRS,
-          help = CliStrings.BACKUP_DISK_STORE__DISKDIRS__HELP, mandatory = true) String targetDir,
-      @CliOption(key = CliStrings.BACKUP_DISK_STORE__BASELINEDIR,
-          help = CliStrings.BACKUP_DISK_STORE__BASELINEDIR__HELP) String baselineDir) {
-
-    getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
-    Result result;
-    try {
-      InternalCache cache = getCache();
-      DM dm = cache.getDistributionManager();
-      BackupStatus backupStatus;
-
-      if (baselineDir != null && !baselineDir.isEmpty()) {
-        backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir),
-            new File(baselineDir));
-      } else {
-        backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir), null);
-      }
-
-      Map<DistributedMember, Set<PersistentID>> backedupMemberDiskstoreMap =
-          backupStatus.getBackedUpDiskStores();
-
-      Set<DistributedMember> backedupMembers = backedupMemberDiskstoreMap.keySet();
-      CompositeResultData crd = ResultBuilder.createCompositeResultData();
-
-      if (!backedupMembers.isEmpty()) {
-        SectionResultData backedupDiskStoresSection = crd.addSection();
-        backedupDiskStoresSection.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_BACKED_UP_DISK_STORES);
-        TabularResultData backedupDiskStoresTable = backedupDiskStoresSection.addTable();
-
-        for (DistributedMember member : backedupMembers) {
-          Set<PersistentID> backedupDiskStores = backedupMemberDiskstoreMap.get(member);
-          boolean printMember = true;
-          String memberName = member.getName();
-
-          if (memberName == null || memberName.isEmpty()) {
-            memberName = member.getId();
-          }
-          for (PersistentID persistentId : backedupDiskStores) {
-            if (persistentId != null) {
-
-              String UUID = persistentId.getUUID().toString();
-              String hostName = persistentId.getHost().getHostName();
-              String directory = persistentId.getDirectory();
-
-              if (printMember) {
-                writeToBackupDiskStoreTable(backedupDiskStoresTable, memberName, UUID, hostName,
-                    directory);
-                printMember = false;
-              } else {
-                writeToBackupDiskStoreTable(backedupDiskStoresTable, "", UUID, hostName, directory);
-              }
-            }
-          }
-        }
-      } else {
-        SectionResultData noMembersBackedUp = crd.addSection();
-        noMembersBackedUp.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_NO_DISKSTORES_BACKED_UP);
-      }
-
-      Set<PersistentID> offlineDiskStores = backupStatus.getOfflineDiskStores();
-
-      if (!offlineDiskStores.isEmpty()) {
-        SectionResultData offlineDiskStoresSection = crd.addSection();
-        TabularResultData offlineDiskStoresTable = offlineDiskStoresSection.addTable();
-
-        offlineDiskStoresSection.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_OFFLINE_DISK_STORES);
-        for (PersistentID offlineDiskStore : offlineDiskStores) {
-          offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID,
-              offlineDiskStore.getUUID().toString());
-          offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_HOST,
-              offlineDiskStore.getHost().getHostName());
-          offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY,
-              offlineDiskStore.getDirectory());
-        }
-      }
-      result = ResultBuilder.buildResult(crd);
-
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-    return result;
-  }
-
-  private void writeToBackupDiskStoreTable(TabularResultData backedupDiskStoreTable,
-      String memberId, String UUID, String host, String directory) {
-    backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_MEMBER, memberId);
-    backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID, UUID);
-    backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY, directory);
-    backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_HOST, host);
-  }
-
-  @CliCommand(value = CliStrings.LIST_DISK_STORE, help = CliStrings.LIST_DISK_STORE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result listDiskStore() {
-    try {
-      Set<DistributedMember> dataMembers = getNormalMembers(getCache());
-
-      if (dataMembers.isEmpty()) {
-        return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
-      }
-
-      return toTabularResult(getDiskStoreListing(dataMembers));
-    } catch (FunctionInvocationTargetException ignore) {
-      return ResultBuilder.createGemFireErrorResult(CliStrings
-          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_DISK_STORE));
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable t) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult(
-          String.format(CliStrings.LIST_DISK_STORE__ERROR_MESSAGE, toString(t, isDebugging())));
-    }
-  }
-
-  @SuppressWarnings("unchecked")
-  protected List<DiskStoreDetails> getDiskStoreListing(Set<DistributedMember> members) {
-    final Execution membersFunctionExecutor = getMembersFunctionExecutor(members);
-    if (membersFunctionExecutor instanceof AbstractExecution) {
-      ((AbstractExecution) membersFunctionExecutor).setIgnoreDepartedMembers(true);
-    }
-
-    final ResultCollector<?, ?> resultCollector =
-        membersFunctionExecutor.execute(new ListDiskStoresFunction());
-
-    final List<?> results = (List<?>) resultCollector.getResult();
-    final List<DiskStoreDetails> distributedSystemMemberDiskStores =
-        new ArrayList<>(results.size());
-
-    for (final Object result : results) {
-      if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other
-                                   // Exceptions...
-        distributedSystemMemberDiskStores.addAll((Set<DiskStoreDetails>) result);
-      }
-    }
-
-    Collections.sort(distributedSystemMemberDiskStores);
-
-    return distributedSystemMemberDiskStores;
-  }
-
-  protected Result toTabularResult(final List<DiskStoreDetails> diskStoreList)
-      throws ResultDataException {
-    if (!diskStoreList.isEmpty()) {
-      final TabularResultData diskStoreData = ResultBuilder.createTabularResultData();
-
-      for (final DiskStoreDetails diskStoreDetails : diskStoreList) {
-        diskStoreData.accumulate("Member Name", diskStoreDetails.getMemberName());
-        diskStoreData.accumulate("Member Id", diskStoreDetails.getMemberId());
-        diskStoreData.accumulate("Disk Store Name", diskStoreDetails.getName());
-        diskStoreData.accumulate("Disk Store ID", diskStoreDetails.getId());
-      }
-
-      return ResultBuilder.buildResult(diskStoreData);
-    } else {
-      return ResultBuilder
-          .createInfoResult(CliStrings.LIST_DISK_STORE__DISK_STORES_NOT_FOUND_MESSAGE);
-    }
-  }
-
-  @CliCommand(value = CliStrings.CREATE_DISK_STORE, help = CliStrings.CREATE_DISK_STORE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.DISK)
-  public Result createDiskStore(
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__NAME, mandatory = true,
-          optionContext = ConverterHint.DISKSTORE,
-          help = CliStrings.CREATE_DISK_STORE__NAME__HELP) String name,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__ALLOW_FORCE_COMPACTION,
-          specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
-          help = CliStrings.CREATE_DISK_STORE__ALLOW_FORCE_COMPACTION__HELP) boolean allowForceCompaction,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__AUTO_COMPACT, specifiedDefaultValue = "true",
-          unspecifiedDefaultValue = "true",
-          help = CliStrings.CREATE_DISK_STORE__AUTO_COMPACT__HELP) boolean autoCompact,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__COMPACTION_THRESHOLD,
-          unspecifiedDefaultValue = "50",
-          help = CliStrings.CREATE_DISK_STORE__COMPACTION_THRESHOLD__HELP) int compactionThreshold,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__MAX_OPLOG_SIZE,
-          unspecifiedDefaultValue = "1024",
-          help = CliStrings.CREATE_DISK_STORE__MAX_OPLOG_SIZE__HELP) int maxOplogSize,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__QUEUE_SIZE, unspecifiedDefaultValue = "0",
-          help = CliStrings.CREATE_DISK_STORE__QUEUE_SIZE__HELP) int queueSize,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__TIME_INTERVAL,
-          unspecifiedDefaultValue = "1000",
-          help = CliStrings.CREATE_DISK_STORE__TIME_INTERVAL__HELP) long timeInterval,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__WRITE_BUFFER_SIZE,
-          unspecifiedDefaultValue = "32768",
-          help = CliStrings.CREATE_DISK_STORE__WRITE_BUFFER_SIZE__HELP) int writeBufferSize,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE, mandatory = true,
-          help = CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE__HELP) String[] directoriesAndSizes,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.CREATE_DISK_STORE__GROUP__HELP,
-          optionContext = ConverterHint.MEMBERGROUP) String[] groups,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__DISK_USAGE_WARNING_PCT,
-          unspecifiedDefaultValue = "90",
-          help = CliStrings.CREATE_DISK_STORE__DISK_USAGE_WARNING_PCT__HELP) float diskUsageWarningPercentage,
-      @CliOption(key = CliStrings.CREATE_DISK_STORE__DISK_USAGE_CRITICAL_PCT,
-          unspecifiedDefaultValue = "99",
-          help = CliStrings.CREATE_DISK_STORE__DISK_USAGE_CRITICAL_PCT__HELP) float diskUsageCriticalPercentage) {
-
-    try {
-      DiskStoreAttributes diskStoreAttributes = new DiskStoreAttributes();
-      diskStoreAttributes.allowForceCompaction = allowForceCompaction;
-      diskStoreAttributes.autoCompact = autoCompact;
-      diskStoreAttributes.compactionThreshold = compactionThreshold;
-      diskStoreAttributes.maxOplogSizeInBytes = maxOplogSize * (1024 * 1024);
-      diskStoreAttributes.queueSize = queueSize;
-      diskStoreAttributes.timeInterval = timeInterval;
-      diskStoreAttributes.writeBufferSize = writeBufferSize;
-
-      File[] directories = new File[directoriesAndSizes.length];
-      int[] sizes = new int[directoriesAndSizes.length];
-      for (int i = 0; i < directoriesAndSizes.length; i++) {
-        final int hashPosition = directoriesAndSizes[i].indexOf('#');
-        if (hashPosition == -1) {
-          directories[i] = new File(directoriesAndSizes[i]);
-          sizes[i] = Integer.MAX_VALUE;
-        } else {
-          directories[i] = new File(directoriesAndSizes[i].substring(0, hashPosition));
-          sizes[i] = Integer.parseInt(directoriesAndSizes[i].substring(hashPosition + 1));
-        }
-      }
-      diskStoreAttributes.diskDirs = directories;
-      diskStoreAttributes.diskDirSizes = sizes;
-
-      diskStoreAttributes.setDiskUsageWarningPercentage(diskUsageWarningPercentage);
-      diskStoreAttributes.setDiskUsageCriticalPercentage(diskUsageCriticalPercentage);
-
-      TabularResultData tabularData = ResultBuilder.createTabularResultData();
-      boolean accumulatedData = false;
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      ResultCollector<?, ?> rc = CliUtil.executeFunction(new CreateDiskStoreFunction(),
-          new Object[] {name, diskStoreAttributes}, targetMembers);
-      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
-      AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-      for (CliFunctionResult result : results) {
-        if (result.getThrowable() != null) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
-              + ": " + result.getThrowable().getMessage());
-          accumulatedData = true;
-          tabularData.setStatus(Status.ERROR);
-        } else if (result.isSuccessful()) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Result", result.getMessage());
-          accumulatedData = true;
-
-          if (xmlEntity.get() == null) {
-            xmlEntity.set(result.getXmlEntity());
-          }
-        }
-      }
-
-      if (!accumulatedData) {
-        return ResultBuilder.createInfoResult("Unable to create disk store(s).");
-      }
-
-      Result result = ResultBuilder.buildResult(tabularData);
-
-      if (xmlEntity.get() != null) {
-        persistClusterConfiguration(result,
-            () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
-      }
-
-      return ResultBuilder.buildResult(tabularData);
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult(
-          CliStrings.format(CliStrings.CREATE_DISK_STORE__ERROR_WHILE_CREATING_REASON_0,
-              new Object[] {th.getMessage()}));
-    }
-  }
-
-  @CliCommand(value = CliStrings.COMPACT_DISK_STORE, help = CliStrings.COMPACT_DISK_STORE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.DISK)
-  public Result compactDiskStore(
-      @CliOption(key = CliStrings.COMPACT_DISK_STORE__NAME, mandatory = true,
-          optionContext = ConverterHint.DISKSTORE,
-          help = CliStrings.COMPACT_DISK_STORE__NAME__HELP) String diskStoreName,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.COMPACT_DISK_STORE__GROUP__HELP) String[] groups) {
-    Result result;
-
-    try {
-      // disk store exists validation
-      if (!diskStoreExists(diskStoreName)) {
-        result = ResultBuilder.createUserErrorResult(
-            CliStrings.format(CliStrings.COMPACT_DISK_STORE__DISKSTORE_0_DOES_NOT_EXIST,
-                new Object[] {diskStoreName}));
-      } else {
-        InternalDistributedSystem ds = getCache().getInternalDistributedSystem();
-
-        Map<DistributedMember, PersistentID> overallCompactInfo = new HashMap<>();
-
-        Set<?> otherMembers = ds.getDistributionManager().getOtherNormalDistributionManagerIds();
-        Set<InternalDistributedMember> allMembers = new HashSet<>();
-
-        for (Object member : otherMembers) {
-          allMembers.add((InternalDistributedMember) member);
-        }
-        allMembers.add(ds.getDistributedMember());
-
-        String groupInfo = "";
-        // if groups are specified, find members in the specified group
-        if (groups != null && groups.length > 0) {
-          groupInfo = CliStrings.format(CliStrings.COMPACT_DISK_STORE__MSG__FOR_GROUP,
-              new Object[] {Arrays.toString(groups) + "."});
-          final Set<InternalDistributedMember> selectedMembers = new HashSet<>();
-          List<String> targetedGroups = Arrays.asList(groups);
-          for (InternalDistributedMember member : allMembers) {
-            List<String> memberGroups = member.getGroups();
-            if (!Collections.disjoint(targetedGroups, memberGroups)) {
-              selectedMembers.add(member);
-            }
-          }
-
-          allMembers = selectedMembers;
-        }
-
-        // allMembers should not be empty when groups are not specified - it'll
-        // have at least one member
-        if (allMembers.isEmpty()) {
-          result = ResultBuilder.createUserErrorResult(
-              CliStrings.format(CliStrings.COMPACT_DISK_STORE__NO_MEMBERS_FOUND_IN_SPECIFED_GROUP,
-                  new Object[] {Arrays.toString(groups)}));
-        } else {
-          // first invoke on local member if it exists in the targeted set
-          if (allMembers.remove(ds.getDistributedMember())) {
-            PersistentID compactedDiskStoreId = CompactRequest.compactDiskStore(diskStoreName);
-            if (compactedDiskStoreId != null) {
-              overallCompactInfo.put(ds.getDistributedMember(), compactedDiskStoreId);
-            }
-          }
-
-          // was this local member the only one? Then don't try to send
-          // CompactRequest. Otherwise, send the request to others
-          if (!allMembers.isEmpty()) {
-            // Invoke compact on all 'other' members
-            Map<DistributedMember, PersistentID> memberCompactInfo =
-                CompactRequest.send(ds.getDistributionManager(), diskStoreName, allMembers);
-            if (memberCompactInfo != null && !memberCompactInfo.isEmpty()) {
-              overallCompactInfo.putAll(memberCompactInfo);
-              memberCompactInfo.clear();
-            }
-            String notExecutedMembers = CompactRequest.getNotExecutedMembers();
-            if (notExecutedMembers != null && !notExecutedMembers.isEmpty()) {
-              LogWrapper.getInstance()
-                  .info("compact disk-store \"" + diskStoreName
-                      + "\" message was scheduled to be sent to but was not send to "
-                      + notExecutedMembers);
-            }
-          }
-
-          // If compaction happened at all, then prepare the summary
-          if (overallCompactInfo != null && !overallCompactInfo.isEmpty()) {
-            CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
-            SectionResultData section;
-
-            Set<Entry<DistributedMember, PersistentID>> entries = overallCompactInfo.entrySet();
-
-            for (Entry<DistributedMember, PersistentID> entry : entries) {
-              String memberId = entry.getKey().getId();
-              section = compositeResultData.addSection(memberId);
-              section.addData("On Member", memberId);
-
-              PersistentID persistentID = entry.getValue();
-              if (persistentID != null) {
-                SectionResultData subSection = section.addSection("DiskStore" + memberId);
-                subSection.addData("UUID", persistentID.getUUID());
-                subSection.addData("Host", persistentID.getHost().getHostName());
-                subSection.addData("Directory", persistentID.getDirectory());
-              }
-            }
-            compositeResultData.setHeader("Compacted " + diskStoreName + groupInfo);
-            result = ResultBuilder.buildResult(compositeResultData);
-          } else {
-            result = ResultBuilder.createInfoResult(
-                CliStrings.COMPACT_DISK_STORE__COMPACTION_ATTEMPTED_BUT_NOTHING_TO_COMPACT);
-          }
-        } // all members' if
-      } // disk store exists' if
-    } catch (RuntimeException e) {
-      LogWrapper.getInstance().info(e.getMessage(), e);
-      result = ResultBuilder.createGemFireErrorResult(
-          CliStrings.format(CliStrings.COMPACT_DISK_STORE__ERROR_WHILE_COMPACTING_REASON_0,
-              new Object[] {e.getMessage()}));
-    }
-
-    return result;
-  }
-
-  private boolean diskStoreExists(String diskStoreName) {
-    InternalCache cache = getCache();
-    ManagementService managementService = ManagementService.getExistingManagementService(cache);
-    DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
-    Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
-
-    Set<Entry<String, String[]>> entrySet = diskstore.entrySet();
-
-    for (Entry<String, String[]> entry : entrySet) {
-      String[] value = entry.getValue();
-      if (CliUtil.contains(value, diskStoreName)) {
-        return true;
-      }
-    }
-
-    return false;
-  }
-
-  @CliCommand(value = CliStrings.COMPACT_OFFLINE_DISK_STORE,
-      help = CliStrings.COMPACT_OFFLINE_DISK_STORE__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  public Result compactOfflineDiskStore(
-      @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME, mandatory = true,
-          help = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
-      @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
-          help = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
-      @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
-          unspecifiedDefaultValue = "-1",
-          help = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
-      @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__J,
-          help = CliStrings.COMPACT_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps) {
-    Result result;
-    LogWrapper logWrapper = LogWrapper.getInstance();
-
-    StringBuilder output = new StringBuilder();
-    StringBuilder error = new StringBuilder();
-    StringBuilder errorMessage = new StringBuilder();
-    Process compacterProcess = null;
-
-    try {
-      String validatedDirectories = validatedDirectories(diskDirs);
-      if (validatedDirectories != null) {
-        throw new IllegalArgumentException(
-            "Could not find " + CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS + ": \""
-                + validatedDirectories + "\"");
-      }
-
-      List<String> commandList = new ArrayList<>();
-      commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
-          + File.separatorChar + "java");
-
-      configureLogging(commandList);
-
-      if (jvmProps != null && jvmProps.length != 0) {
-        commandList.addAll(Arrays.asList(jvmProps));
-      }
-      commandList.add("-classpath");
-      commandList.add(System.getProperty("java.class.path", "."));
-      commandList.add(DiskStoreCompacter.class.getName());
-
-      commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);
-
-      if (diskDirs != null && diskDirs.length != 0) {
-        StringBuilder builder = new StringBuilder();
-        int arrayLength = diskDirs.length;
-        for (int i = 0; i < arrayLength; i++) {
-          if (File.separatorChar == '\\') {
-            builder.append(diskDirs[i].replace("\\", "/")); // see 46120
-          } else {
-            builder.append(diskDirs[i]);
-          }
-          if (i + 1 != arrayLength) {
-            builder.append(',');
-          }
-        }
-        commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder.toString());
-      }
-      // -1 is ignore as maxOplogSize
-      commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);
-
-      ProcessBuilder procBuilder = new ProcessBuilder(commandList);
-      compacterProcess = procBuilder.start();
-      InputStream inputStream = compacterProcess.getInputStream();
-      InputStream errorStream = compacterProcess.getErrorStream();
-      BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
-      BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
-
-      String line;
-      while ((line = inputReader.readLine()) != null) {
-        output.append(line).append(GfshParser.LINE_SEPARATOR);
-      }
-
-      boolean switchToStackTrace = false;
-      while ((line = errorReader.readLine()) != null) {
-        if (!switchToStackTrace && DiskStoreCompacter.STACKTRACE_START.equals(line)) {
-          switchToStackTrace = true;
-        } else if (switchToStackTrace) {
-          error.append(line).append(GfshParser.LINE_SEPARATOR);
-        } else {
-          errorMessage.append(line);
-        }
-      }
-
-      if (errorMessage.length() > 0) {
-        throw new GemFireIOException(errorMessage.toString());
-      }
-
-      // do we have to waitFor??
-      compacterProcess.destroy();
-      result = ResultBuilder.createInfoResult(output.toString());
-    } catch (IOException e) {
-      if (output.length() != 0) {
-        Gfsh.println(output.toString());
-      }
-      String fieldsMessage = (maxOplogSize != -1
-          ? CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize + "," : "");
-      fieldsMessage += CliUtil.arrayToString(diskDirs);
-      String errorString = CliStrings.format(
-          CliStrings.COMPACT_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2,
-          diskStoreName, fieldsMessage);
-      result = ResultBuilder.createUserErrorResult(errorString);
-      if (logWrapper.fineEnabled()) {
-        logWrapper.fine(e.getMessage(), e);
-      }
-    } catch (GemFireIOException e) {
-      if (output.length() != 0) {
-        Gfsh.println(output.toString());
-      }
-      result = ResultBuilder.createUserErrorResult(errorMessage.toString());
-      if (logWrapper.fineEnabled()) {
-        logWrapper.fine(error.toString());
-      }
-    } catch (IllegalArgumentException e) {
-      if (output.length() != 0) {
-        Gfsh.println(output.toString());
-      }
-      result = ResultBuilder.createUserErrorResult(e.getMessage());
-    } finally {
-      if (compacterProcess != null) {
-        try {
-          // just to check whether the process has exited
-          // Process.exitValue() throws IllegalThreadStateException if Process
-          // is alive
-          compacterProcess.exitValue();
-        } catch (IllegalThreadStateException ise) {
-          // not yet terminated, destroy the process
-          compacterProcess.destroy();
-        }
-      }
-    }
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.UPGRADE_OFFLINE_DISK_STORE,
-      help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  public Result upgradeOfflineDiskStore(
-      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME, mandatory = true,
-          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
-      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
-          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
-      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
-          unspecifiedDefaultValue = "-1",
-          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
-      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J,
-          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps)
-      throws InterruptedException {
-
-    Result result;
-    LogWrapper logWrapper = LogWrapper.getInstance();
-
-    StringBuilder output = new StringBuilder();
-    StringBuilder error = new StringBuilder();
-    StringBuilder errorMessage = new StringBuilder();
-    Process upgraderProcess = null;
-
-    try {
-      String validatedDirectories = validatedDirectories(diskDirs);
-      if (validatedDirectories != null) {
-        throw new IllegalArgumentException(
-            "Could not find " + CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + ": \""
-                + validatedDirectories + "\"");
-      }
-
-      List<String> commandList = new ArrayList<>();
-      commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
-          + File.separatorChar + "java");
-
-      configureLogging(commandList);
-
-      if (jvmProps != null && jvmProps.length != 0) {
-        commandList.addAll(Arrays.asList(jvmProps));
-      }
-      commandList.add("-classpath");
-      commandList.add(System.getProperty("java.class.path", "."));
-      commandList.add(DiskStoreUpgrader.class.getName());
-
-      commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);
-
-      if (diskDirs != null && diskDirs.length != 0) {
-        StringBuilder builder = new StringBuilder();
-        int arrayLength = diskDirs.length;
-        for (int i = 0; i < arrayLength; i++) {
-          if (File.separatorChar == '\\') {
-            builder.append(diskDirs[i].replace("\\", "/")); // see 46120
-          } else {
-            builder.append(diskDirs[i]);
-          }
-          if (i + 1 != arrayLength) {
-            builder.append(',');
-          }
-        }
-        commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder.toString());
-      }
-      // -1 is ignore as maxOplogSize
-      commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);
-
-      ProcessBuilder procBuilder = new ProcessBuilder(commandList);
-      // procBuilder.redirectErrorStream(true);
-      upgraderProcess = procBuilder.start();
-      InputStream inputStream = upgraderProcess.getInputStream();
-      InputStream errorStream = upgraderProcess.getErrorStream();
-      BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
-      BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
-
-      String line;
-      while ((line = inputReader.readLine()) != null) {
-        output.append(line).append(GfshParser.LINE_SEPARATOR);
-      }
-
-      boolean switchToStackTrace = false;
-      while ((line = errorReader.readLine()) != null) {
-        if (!switchToStackTrace && DiskStoreUpgrader.STACKTRACE_START.equals(line)) {
-          switchToStackTrace = true;
-        } else if (switchToStackTrace) {
-          error.append(line).append(GfshParser.LINE_SEPARATOR);
-        } else {
-          errorMessage.append(line);
-        }
-      }
-
-      if (errorMessage.length() > 0) {
-        throw new GemFireIOException(errorMessage.toString());
-      }
-
-      upgraderProcess.destroy();
-      result = ResultBuilder.createInfoResult(output.toString());
-    } catch (IOException e) {
-      if (output.length() != 0) {
-        Gfsh.println(output.toString());
-      }
-      String fieldsMessage = (maxOplogSize != -1
-          ? CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize + "," : "");
-      fieldsMessage += CliUtil.arrayToString(diskDirs);
-      String errorString = CliStrings.format(
-          CliStrings.UPGRADE_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2,
-          diskStoreName, fieldsMessage);
-      result = ResultBuilder.createUserErrorResult(errorString);
-      if (logWrapper.fineEnabled()) {
-        logWrapper.fine(e.getMessage(), e);
-      }
-    } catch (GemFireIOException e) {
-      if (output.length() != 0) {
-        Gfsh.println(output.toString());
-      }
-      result = ResultBuilder.createUserErrorResult(errorMessage.toString());
-      if (logWrapper.fineEnabled()) {
-        logWrapper.fine(error.toString());
-      }
-    } catch (IllegalArgumentException e) {
-      if (output.length() != 0) {
-        Gfsh.println(output.toString());
-      }
-      result = ResultBuilder.createUserErrorResult(e.getMessage());
-    } finally {
-      if (upgraderProcess != null) {
-        try {
-          // just to check whether the process has exited
-          // Process.exitValue() throws IllegalStateException if Process is alive
-          upgraderProcess.exitValue();
-        } catch (IllegalThreadStateException itse) {
-          // not yet terminated, destroy the process
-          upgraderProcess.destroy();
-        }
-      }
-    }
-    return result;
-  }
-
-  private String validatedDirectories(String[] diskDirs) {
-    String invalidDirectories = null;
-    StringBuilder builder = null;
-    File diskDir;
-    for (String diskDirPath : diskDirs) {
-      diskDir = new File(diskDirPath);
-      if (!diskDir.exists()) {
-        if (builder == null) {
-          builder = new StringBuilder();
-        } else if (builder.length() != 0) {
-          builder.append(", ");
-        }
-        builder.append(diskDirPath);
-      }
-    }
-    if (builder != null) {
-      invalidDirectories = builder.toString();
-    }
-
-    return invalidDirectories;
-  }
-
-  @CliCommand(value = CliStrings.DESCRIBE_DISK_STORE, help = CliStrings.DESCRIBE_DISK_STORE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result describeDiskStore(
-      @CliOption(key = CliStrings.MEMBER, mandatory = true,
-          optionContext = ConverterHint.MEMBERIDNAME,
-          help = CliStrings.DESCRIBE_DISK_STORE__MEMBER__HELP) final String memberName,
-      @CliOption(key = CliStrings.DESCRIBE_DISK_STORE__NAME, mandatory = true,
-          optionContext = ConverterHint.DISKSTORE,
-          help = CliStrings.DESCRIBE_DISK_STORE__NAME__HELP) final String diskStoreName) {
-    try {
-      return toCompositeResult(getDiskStoreDescription(memberName, diskStoreName));
-    } catch (DiskStoreNotFoundException | MemberNotFoundException e) {
-      return ResultBuilder.createShellClientErrorResult(e.getMessage());
-    } catch (FunctionInvocationTargetException ignore) {
-      return ResultBuilder.createGemFireErrorResult(CliStrings
-          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_DISK_STORE));
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable t) {
-      SystemFailure.checkFailure();
-      return ResultBuilder
-          .createGemFireErrorResult(String.format(CliStrings.DESCRIBE_DISK_STORE__ERROR_MESSAGE,
-              memberName, diskStoreName, toString(t, isDebugging())));
-    }
-  }
-
-  protected DiskStoreDetails getDiskStoreDescription(final String memberName,
-      final String diskStoreName) {
-    final DistributedMember member = getMember(getCache(), memberName); // may throw a
-                                                                        // MemberNotFoundException
-
-    final ResultCollector<?, ?> resultCollector =
-        getMembersFunctionExecutor(Collections.singleton(member)).setArguments(diskStoreName)
-            .execute(new DescribeDiskStoreFunction());
-
-    final Object result = ((List<?>) resultCollector.getResult()).get(0);
-
-    if (result instanceof DiskStoreDetails) { // disk store details in hand...
-      return (DiskStoreDetails) result;
-    } else if (result instanceof DiskStoreNotFoundException) { // bad disk store name...
-      throw (DiskStoreNotFoundException) result;
-    } else { // unknown and unexpected return type...
-      final Throwable cause = (result instanceof Throwable ? (Throwable) result : null);
-
-      if (isLogging()) {
-        if (cause != null) {
-          getGfsh().logSevere(String.format(
-              "Exception (%1$s) occurred while executing '%2$s' on member (%3$s) with disk store (%4$s).",
-              ClassUtils.getClassName(cause), CliStrings.DESCRIBE_DISK_STORE, memberName,
-              diskStoreName), cause);
-        } else {
-          getGfsh().logSevere(String.format(
-              "Received an unexpected result of type (%1$s) while executing '%2$s' on member (%3$s) with disk store (%4$s).",
-              ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE, memberName,
-              diskStoreName), null);
-        }
-      }
-
-      throw new RuntimeException(
-          CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
-              ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE),
-          cause);
-    }
-  }
-
-  protected Result toCompositeResult(final DiskStoreDetails diskStoreDetails) {
-    final CompositeResultData diskStoreData = ResultBuilder.createCompositeResultData();
-
-    final CompositeResultData.SectionResultData diskStoreSection = diskStoreData.addSection();
-
-    diskStoreSection.addData("Disk Store ID", diskStoreDetails.getId());
-    diskStoreSection.addData("Disk Store Name", diskStoreDetails.getName());
-    diskStoreSection.addData("Member ID", diskStoreDetails.getMemberId());
-    diskStoreSection.addData("Member Name", diskStoreDetails.getMemberName());
-    diskStoreSection.addData("Allow Force Compaction",
-        toString(diskStoreDetails.isAllowForceCompaction(), "Yes", "No"));
-    diskStoreSection.addData("Auto Compaction",
-        toString(diskStoreDetails.isAutoCompact(), "Yes", "No"));
-    diskStoreSection.addData("Compaction Threshold", diskStoreDetails.getCompactionThreshold());
-    diskStoreSection.addData("Max Oplog Size", diskStoreDetails.getMaxOplogSize());
-    diskStoreSection.addData("Queue Size", diskStoreDetails.getQueueSize());
-    diskStoreSection.addData("Time Interval", diskStoreDetails.getTimeInterval());
-    diskStoreSection.addData("Write Buffer Size", diskStoreDetails.getWriteBufferSize());
-    diskStoreSection.addData("Disk Usage Warning Percentage",
-        diskStoreDetails.getDiskUsageWarningPercentage());
-    diskStoreSection.addData("Disk Usage Critical Percentage",
-        diskStoreDetails.getDiskUsageCriticalPercentage());
-    diskStoreSection.addData("PDX Serialization Meta-Data Stored",
-        toString(diskStoreDetails.isPdxSerializationMetaDataStored(), "Yes", "No"));
-
-    final TabularResultData diskDirTable = diskStoreData.addSection().addTable();
-
-    for (DiskStoreDetails.DiskDirDetails diskDirDetails : diskStoreDetails) {
-      diskDirTable.accumulate("Disk Directory", diskDirDetails.getAbsolutePath());
-      diskDirTable.accumulate("Size", diskDirDetails.getSize());
-    }
-
-    final TabularResultData regionTable = diskStoreData.addSection().addTable();
-
-    for (DiskStoreDetails.RegionDetails regionDetails : diskStoreDetails.iterateRegions()) {
-      regionTable.accumulate("Region Path", regionDetails.getFullPath());
-      regionTable.accumulate("Region Name", regionDetails.getName());
-      regionTable.accumulate("Persistent", toString(regionDetails.isPersistent(), "Yes", "No"));
-      regionTable.accumulate("Overflow To Disk",
-          toString(regionDetails.isOverflowToDisk(), "Yes", "No"));
-    }
-
-    final TabularResultData cacheServerTable = diskStoreData.addSection().addTable();
-
-    for (DiskStoreDetails.CacheServerDetails cacheServerDetails : diskStoreDetails
-        .iterateCacheServers()) {
-      cacheServerTable.accumulate("Bind Address", cacheServerDetails.getBindAddress());
-      cacheServerTable.accumulate("Hostname for Clients", cacheServerDetails.getHostName());
-      cacheServerTable.accumulate("Port", cacheServerDetails.getPort());
-    }
-
-    final TabularResultData gatewayTable = diskStoreData.addSection().addTable();
-
-    for (DiskStoreDetails.GatewayDetails gatewayDetails : diskStoreDetails.iterateGateways()) {
-      gatewayTable.accumulate("Gateway ID", gatewayDetails.getId());
-      gatewayTable.accumulate("Persistent", toString(gatewayDetails.isPersistent(), "Yes", "No"));
-    }
-
-    final TabularResultData asyncEventQueueTable = diskStoreData.addSection().addTable();
-
-    for (DiskStoreDetails.AsyncEventQueueDetails asyncEventQueueDetails : diskStoreDetails
-        .iterateAsyncEventQueues()) {
-      asyncEventQueueTable.accumulate("Async Event Queue ID", asyncEventQueueDetails.getId());
-    }
-
-    return ResultBuilder.buildResult(diskStoreData);
-  }
-
-  @CliCommand(value = CliStrings.REVOKE_MISSING_DISK_STORE,
-      help = CliStrings.REVOKE_MISSING_DISK_STORE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.DISK)
-  public Result revokeMissingDiskStore(@CliOption(key = CliStrings.REVOKE_MISSING_DISK_STORE__ID,
-      mandatory = true, help = CliStrings.REVOKE_MISSING_DISK_STORE__ID__HELP) String id) {
-
-    try {
-      DistributedSystemMXBean dsMXBean =
-          ManagementService.getManagementService(getCache()).getDistributedSystemMXBean();
-      if (dsMXBean.revokeMissingDiskStores(id)) {
-        return ResultBuilder.createInfoResult("Missing disk store successfully revoked");
-      }
-
-      return ResultBuilder.createUserErrorResult("Unable to find missing disk store to revoke");
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      if (th.getMessage() == null) {
-        return ResultBuilder.createGemFireErrorResult(
-            "An error occurred while revoking missing disk stores: " + th);
-      }
-      return ResultBuilder.createGemFireErrorResult(
-          "An error occurred while revoking missing disk stores: " + th.getMessage());
-    }
-  }
-
-  @CliCommand(value = CliStrings.SHOW_MISSING_DISK_STORE,
-      help = CliStrings.SHOW_MISSING_DISK_STORE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result showMissingDiskStore() {
-
-    try {
-      Set<DistributedMember> dataMembers = getNormalMembers(getCache());
-
-      if (dataMembers.isEmpty()) {
-        return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
-      }
-      List<Object> results = getMissingDiskStoresList(dataMembers);
-      return toMissingDiskStoresTabularResult(results);
-    } catch (FunctionInvocationTargetException ignore) {
-      return ResultBuilder.createGemFireErrorResult(CliStrings.format(
-          CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.SHOW_MISSING_DISK_STORE));
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable t) {
-      SystemFailure.checkFailure();
-      if (t.getMessage() == null) {
-        return ResultBuilder.createGemFireErrorResult(
-            String.format(CliStrings.SHOW_MISSING_DISK_STORE__ERROR_MESSAGE, t));
-      }
-      return ResultBuilder.createGemFireErrorResult(
-          String.format(CliStrings.SHOW_MISSING_DISK_STORE__ERROR_MESSAGE, t.getMessage()));
-    }
-  }
-
-  protected List<Object> getMissingDiskStoresList(Set<DistributedMember> members) {
-    final Execution membersFunctionExecutor = getMembersFunctionExecutor(members);
-    if (membersFunctionExecutor instanceof AbstractExecution) {
-      ((AbstractExecution) membersFunctionExecutor).setIgnoreDepartedMembers(true);
-    }
-
-    final ResultCollector<?, ?> resultCollector =
-        membersFunctionExecutor.execute(new ShowMissingDiskStoresFunction());
-
-    final List<?> results = (List<?>) resultCollector.getResult();
-    final List<Object> distributedPersistentRecoveryDetails = new ArrayList<>(results.size());
-    for (final Object result : results) {
-      if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other
-                                   // Exceptions...
-        distributedPersistentRecoveryDetails.addAll((Set<Object>) result);
-      }
-    }
-    return distributedPersistentRecoveryDetails;
-  }
-
-  protected Result toMissingDiskStoresTabularResult(final List<Object> resultDetails)
-      throws ResultDataException {
-    CompositeResultData crd = ResultBuilder.createCompositeResultData();
-    List<PersistentMemberPattern> missingDiskStores = new ArrayList<>();
-    List<ColocatedRegionDetails> missingColocatedRegions = new ArrayList<>();
-
-    for (Object detail : resultDetails) {
-      if (detail instanceof PersistentMemberPattern) {
-        missingDiskStores.add((PersistentMemberPattern) detail);
-      } else if (detail instanceof ColocatedRegionDetails) {
-        missingColocatedRegions.add((ColocatedRegionDetails) detail);
-      } else {
-        throw new ResultDataException("Unknown type of PersistentRecoveryFailures result");
-      }
-    }
-
-    boolean hasMissingDiskStores = !missingDiskStores.isEmpty();
-    boolean hasMissingColocatedRegions = !missingColocatedRegions.isEmpty();
-    if (hasMissingDiskStores) {
-      SectionResultData missingDiskStoresSection = crd.addSection();
-      missingDiskStoresSection.setHeader("Missing Disk Stores");
-      TabularResultData missingDiskStoreData = missingDiskStoresSection.addTable();
-
-      for (PersistentMemberPattern persistentMemberDetails : missingDiskStores) {
-        missingDiskStoreData.accumulate("Disk Store ID", persistentMemberDetails.getUUID());
-        missingDiskStoreData.accumulate("Host", persistentMemberDetails.getHost());
-        missingDiskStoreData.accumulate("Directory", persistentMemberDetails.getDirectory());
-      }
-    } else {
-      SectionResultData noMissingDiskStores = crd.addSection();
-      noMissingDiskStores.setHeader("No missing disk store found");
-    }
-    if (hasMissingDiskStores || hasMissingColocatedRegions) {
-      // For clarity, separate disk store and colocated region information
-      crd.addSection().setHeader("\n");
-    }
-
-    if (hasMissingColocatedRegions) {
-      SectionResultData missingRegionsSection = crd.addSection();
-      missingRegionsSection.setHeader("Missing Colocated Regions");
-      TabularResultData missingRegionData = missingRegionsSection.addTable();
-
-      for (ColocatedRegionDetails colocatedRegionDetails : missingColocatedRegions) {
-        missingRegionData.accumulate("Host", colocatedRegionDetails.getHost());
-        missingRegionData.accumulate("Distributed Member", colocatedRegionDetails.getMember());
-        missingRegionData.accumulate("Parent Region", colocatedRegionDetails.getParent());
-        missingRegionData.accumulate("Missing Colocated Region", colocatedRegionDetails.getChild());
-      }
-    } else {
-      SectionResultData noMissingColocatedRegions = crd.addSection();
-      noMissingColocatedRegions.setHeader("No missing colocated region found");
-    }
-
-    return ResultBuilder.buildResult(crd);
-  }
-
-  @CliCommand(value = CliStrings.DESCRIBE_OFFLINE_DISK_STORE,
-      help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  public Result describeOfflineDiskStore(
-      @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME, mandatory = true,
-          help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
-      @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
-          help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
-      @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES,
-          help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES__HELP) Boolean listPdxTypes,
-      @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME,
-          help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME__HELP) String regionName) {
-
-    try {
-      final File[] dirs = new File[diskDirs.length];
-      for (int i = 0; i < diskDirs.length; i++) {
-        dirs[i] = new File((diskDirs[i]));
-      }
-
-      if (Region.SEPARATOR.equals(regionName)) {
-        return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
-      }
-
-      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
-      PrintStream printStream = new PrintStream(outputStream);
-
-      DiskStoreImpl.dumpInfo(printStream, diskStoreName, dirs, regionName, listPdxTypes);
-      return ResultBuilder.createInfoResult(outputStream.toString());
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      if (th.getMessage() == null) {
-        return ResultBuilder.createGemFireErrorResult(
-            "An error occurred while describing offline disk stores: " + th);
-      }
-      return ResultBuilder.createGemFireErrorResult(
-          "An error occurred while describing offline disk stores: " + th.getMessage());
-    }
-  }
-
-  @CliCommand(value = CliStrings.EXPORT_OFFLINE_DISK_STORE,
-      help = CliStrings.EXPORT_OFFLINE_DISK_STORE__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  public Result exportOfflineDiskStore(
-      @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME, mandatory = true,
-          help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
-      @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
-          help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
-      @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DIR, mandatory = true,
-          help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DIR__HELP) String dir) {
-
-    try {
-      final File[] dirs = new File[diskDirs.length];
-      for (int i = 0; i < diskDirs.length; i++) {
-        dirs[i] = new File((diskDirs[i]));
-      }
-
-      File output = new File(dir);
-
-      // Note, this can consume a lot of memory, so this should
-      // not be moved to a separate process unless we provide a way for the user
-      // to configure the size of that process.
-      DiskStoreImpl.exportOfflineSnapshot(diskStoreName, dirs, output);
-      String resultString =
-          CliStrings.format(CliStrings.EXPORT_OFFLINE_DISK_STORE__SUCCESS, diskStoreName, dir);
-      return ResultBuilder.createInfoResult(resultString);
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      LogWrapper.getInstance().warning(th.getMessage(), th);
-      return ResultBuilder.createGemFireErrorResult(CliStrings
-          .format(CliStrings.EXPORT_OFFLINE_DISK_STORE__ERROR, diskStoreName, th.toString()));
-    }
-  }
-
-  private void configureLogging(final List<String> commandList) {
-    URL configUrl = LogService.class.getResource(LogService.CLI_CONFIG);
-    String configFilePropertyValue = configUrl.toString();
-    commandList.add("-Dlog4j.configurationFile=" + configFilePropertyValue);
-  }
-
-  @CliCommand(value = CliStrings.VALIDATE_DISK_STORE, help = CliStrings.VALIDATE_DISK_STORE__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE}) // offline
-                                                                                    // command
-  public Result validateDiskStore(
-      @CliOption(key = CliStrings.VALIDATE_DISK_STORE__NAME, mandatory = true,
-          help = CliStrings.VALIDATE_DISK_STORE__NAME__HELP) String diskStoreName,
-      @CliOption(key = CliStrings.VALIDATE_DISK_STORE__DISKDIRS, mandatory = true,
-          help = CliStrings.VALIDATE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
-      @CliOption(key = CliStrings.VALIDATE_DISK_STORE__J,
-          help = CliStrings.VALIDATE_DISK_STORE__J__HELP) String[] jvmProps) {
-    try {
-      // create a new process ...bug 46075
-      StringBuilder dirList = new StringBuilder();
-      for (String diskDir : diskDirs) {
-        dirList.append(diskDir);
-        dirList.append(";");
-      }
-
-      List<String> commandList = new ArrayList<>();
-      commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
-          + File.separatorChar + "java");
-
-      configureLogging(commandList);
-
-      if (jvmProps != null && jvmProps.length != 0) {
-        commandList.addAll(Arrays.asList(jvmProps));
-      }
-
-      // Pass any java options on to the command
-      String opts = System.getenv("JAVA_OPTS");
-      if (opts != null) {
-        commandList.add(opts);
-      }
-      commandList.add("-classpath");
-      commandList.add(System.getProperty("java.class.path", "."));
-      commandList.add(DiskStoreValidater.class.getName());
-      commandList.add(diskStoreName);
-      commandList.add(dirList.toString());
-
-      ProcessBuilder procBuilder = new ProcessBuilder(commandList);
-      StringBuilder output = new StringBuilder();
-      String errorString = "";
-
-      Process validateDiskStoreProcess = procBuilder.redirectErrorStream(true).start();
-      InputStream inputStream = validateDiskStoreProcess.getInputStream();
-      BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
-      String line;
-
-      while ((line = br.readLine()) != null) {
-        output.append(line).append(GfshParser.LINE_SEPARATOR);
-      }
-      validateDiskStoreProcess.destroy();
-
-      output.append(errorString).append(GfshParser.LINE_SEPARATOR);
-      String resultString =
-          "Validating " + diskStoreName + GfshParser.LINE_SEPARATOR + output.toString();
-      return ResultBuilder.createInfoResult(resultString);
-    } catch (IOException ex) {
-      return ResultBuilder.createGemFireErrorResult(CliStrings
-          .format(CliStrings.VALIDATE_DISK_STORE__MSG__IO_ERROR, diskStoreName, ex.getMessage()));
-    } catch (Exception ex) {
-      // StringPrintWriter s = new StringPrintWriter();
-      // ex.printStackTrace(s);
-      return ResultBuilder.createGemFireErrorResult(CliStrings
-          .format(CliStrings.VALIDATE_DISK_STORE__MSG__ERROR, diskStoreName, ex.getMessage()));
-    }
-  }
-
-  @CliCommand(value = CliStrings.ALTER_DISK_STORE, help = CliStrings.ALTER_DISK_STORE__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  public Result alterOfflineDiskStore(
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__DISKSTORENAME, mandatory = true,
-          help = CliStrings.ALTER_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__REGIONNAME, mandatory = true,
-          help = CliStrings.ALTER_DISK_STORE__REGIONNAME__HELP) String regionName,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__DISKDIRS,
-          help = CliStrings.ALTER_DISK_STORE__DISKDIRS__HELP, mandatory = true) String[] diskDirs,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__COMPRESSOR, specifiedDefaultValue = "none",
-          help = CliStrings.ALTER_DISK_STORE__COMPRESSOR__HELP) String compressorClassName,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL,
-          help = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL__HELP) Integer concurrencyLevel,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED,
-          help = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED__HELP) Boolean statisticsEnabled,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY,
-          help = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY__HELP) Integer initialCapacity,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR,
-          help = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR__HELP) Float loadFactor,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION,
-          help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION__HELP) String lruEvictionAction,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM,
-          help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM__HELP) String lruEvictionAlgo,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT,
-          help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT__HELP) Integer lruEvictionLimit,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__OFF_HEAP,
-          help = CliStrings.ALTER_DISK_STORE__OFF_HEAP__HELP) Boolean offHeap,
-      @CliOption(key = CliStrings.ALTER_DISK_STORE__REMOVE,
-          help = CliStrings.ALTER_DISK_STORE__REMOVE__HELP, specifiedDefaultValue = "true",
-          unspecifiedDefaultValue = "false") boolean remove) {
-
-    Result result;
-
-    try {
-      File[] dirs = null;
-
-      if (diskDirs != null) {
-        dirs = new File[diskDirs.length];
-        for (int i = 0; i < diskDirs.length; i++) {
-          dirs[i] = new File((diskDirs[i]));
-        }
-      }
-
-      if (regionName.equals(Region.SEPARATOR)) {
-        return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
-      }
-
-      if ((lruEvictionAlgo != null) || (lruEvictionAction != null) || (lruEvictionLimit != null)
-          || (concurrencyLevel != null) || (initialCapacity != null) || (loadFactor != null)
-          || (compressorClassName != null) || (offHeap != null) || (statisticsEnabled != null)) {
-        if (!remove) {
-          String lruEvictionLimitString =
-              lruEvictionLimit == null ? null : lruEvictionLimit.toString();
-          String concurrencyLevelString =
-              concurrencyLevel == null ? null : concurrencyLevel.toString();
-          String initialCapacityString =
-              initialCapacity == null ? null : initialCapacity.toString();
-          String loadFactorString = loadFactor == null ? null : loadFactor.toString();
-          String statisticsEnabledString =
-              statisticsEnabled == null ? null : statisticsEnabled.toString();
-          String offHeapString = offHeap == null ? null : offHeap.toString();
-
-          if ("none".equals(compressorClassName)) {
-            compressorClassName = "";
-          }
-
-          String resultMessage = DiskStoreImpl.modifyRegion(diskStoreName, dirs, "/" + regionName,
-              lruEvictionAlgo, lruEvictionAction, lruEvictionLimitString, concurrencyLevelString,
-              initialCapacityString, loadFactorString, compressorClassName, statisticsEnabledString,
-              offHeapString, false);
-
-          result = ResultBuilder.createInfoResult(resultMessage);
-        } else {
-          result = ResultBuilder.createParsingErrorResult(
-              "Cannot use the --remove=true parameter with any other parameters");
-        }
-      } else {
-        if (remove) {
-          DiskStoreImpl.destroyRegion(diskStoreName, dirs, "/" + regionName);
-          result = ResultBuilder.createInfoResult("The region " + regionName
-              + " was successfully removed from the disk store " + diskStoreName);
-        } else {
-          // Please provide an option
-          result = ResultBuilder.createParsingErrorResult("Please provide a relevant parameter");
-        }
-      }
-      // Catch the IllegalArgumentException thrown by the modifyDiskStore function and sent the
-    } catch (IllegalArgumentException e) {
-      String message = "Please check the parameters";
-      message += "\n" + e.getMessage();
-      result = ResultBuilder.createGemFireErrorResult(message);
-    } catch (IllegalStateException e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    } catch (CacheExistsException e) {
-      // Indicates that the command is being used when a cache is open
-      result = ResultBuilder.createGemFireErrorResult("Cannot execute "
-          + CliStrings.ALTER_DISK_STORE + " when a cache exists (Offline command)");
-    } catch (Exception e) {
-      result = createErrorResult(e.getMessage());
-    }
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.DESTROY_DISK_STORE, help = CliStrings.DESTROY_DISK_STORE__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.DISK)
-  public Result destroyDiskStore(
-      @CliOption(key = CliStrings.DESTROY_DISK_STORE__NAME, mandatory = true,
-          help = CliStrings.DESTROY_DISK_STORE__NAME__HELP) String name,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.DESTROY_DISK_STORE__GROUP__HELP,
-          optionContext = ConverterHint.MEMBERGROUP) String[] groups) {
-    try {
-      TabularResultData tabularData = ResultBuilder.createTabularResultData();
-      boolean accumulatedData = false;
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      ResultCollector<?, ?> rc = CliUtil.executeFunction(new DestroyDiskStoreFunction(),
-          new Object[] {name}, targetMembers);
-      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
-      AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-      for (CliFunctionResult result : results) {
-        if (result.getThrowable() != null) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
-              + ": " + result.getThrowable().getMessage());
-          accumulatedData = true;
-          tabularData.setStatus(Status.ERROR);
-        } else if (result.getMessage() != null) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Result", result.getMessage());
-          accumulatedData = true;
-
-          if (xmlEntity.get() == null) {
-            xmlEntity.set(result.getXmlEntity());
-          }
-        }
-      }
-
-      if (!accumulatedData) {
-        return ResultBuilder.createInfoResult("No matching disk stores found.");
-      }
-
-      Result result = ResultBuilder.buildResult(tabularData);
-      if (xmlEntity.get() != null) {
-        persistClusterConfiguration(result,
-            () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), groups));
-      }
-
-      return result;
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult(
-          CliStrings.format(CliStrings.DESTROY_DISK_STORE__ERROR_WHILE_DESTROYING_REASON_0,
-              new Object[] {th.getMessage()}));
-    }
-  }
-
-  private Result createErrorResult(String message) {
-    ErrorResultData erd = ResultBuilder.createErrorResultData();
-    erd.addLine(message);
-    return ResultBuilder.buildResult(erd);
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsUtils.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsUtils.java
new file mode 100644
index 0000000..14aedf9
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsUtils.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.File;
+import java.net.URL;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.management.internal.cli.CliUtil;
+
+class DiskStoreCommandsUtils {
+  static void configureLogging(final List<String> commandList) {
+    URL configUrl = LogService.class.getResource(LogService.CLI_CONFIG);
+    String configFilePropertyValue = configUrl.toString();
+    commandList.add("-Dlog4j.configurationFile=" + configFilePropertyValue);
+  }
+
+  static String validatedDirectories(String[] diskDirs) {
+    String invalidDirectories = null;
+    StringBuilder builder = null;
+    File diskDir;
+    for (String diskDirPath : diskDirs) {
+      diskDir = new File(diskDirPath);
+      if (!diskDir.exists()) {
+        if (builder == null) {
+          builder = new StringBuilder();
+        } else if (builder.length() != 0) {
+          builder.append(", ");
+        }
+        builder.append(diskDirPath);
+      }
+    }
+    if (builder != null) {
+      invalidDirectories = builder.toString();
+    }
+    return invalidDirectories;
+  }
+
+  static Set<DistributedMember> getNormalMembers(final InternalCache cache) {
+    // TODO determine what this does (as it is untested and unmockable!)
+    return CliUtil.getAllNormalMembers(cache);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportOfflineDiskStoreCommand.java
new file mode 100644
index 0000000..c704364
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportOfflineDiskStoreCommand.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.File;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.internal.cache.DiskStoreImpl;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+
+public class ExportOfflineDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.EXPORT_OFFLINE_DISK_STORE,
+      help = CliStrings.EXPORT_OFFLINE_DISK_STORE__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  public Result exportOfflineDiskStore(
+      @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME, mandatory = true,
+          help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
+      @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
+          help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+      @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DIR, mandatory = true,
+          help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DIR__HELP) String dir) {
+
+    try {
+      final File[] dirs = new File[diskDirs.length];
+      for (int i = 0; i < diskDirs.length; i++) {
+        dirs[i] = new File((diskDirs[i]));
+      }
+
+      File output = new File(dir);
+
+      // Note, this can consume a lot of memory, so this should
+      // not be moved to a separate process unless we provide a way for the user
+      // to configure the size of that process.
+      DiskStoreImpl.exportOfflineSnapshot(diskStoreName, dirs, output);
+      String resultString =
+          CliStrings.format(CliStrings.EXPORT_OFFLINE_DISK_STORE__SUCCESS, diskStoreName, dir);
+      return ResultBuilder.createInfoResult(resultString);
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      LogWrapper.getInstance().warning(th.getMessage(), th);
+      return ResultBuilder.createGemFireErrorResult(CliStrings
+          .format(CliStrings.EXPORT_OFFLINE_DISK_STORE__ERROR, diskStoreName, th.toString()));
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDiskStoresCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDiskStoresCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDiskStoresCommand.java
new file mode 100644
index 0000000..5444c4d
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDiskStoresCommand.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.execute.AbstractExecution;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
+import org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.ResultDataException;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ListDiskStoresCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.LIST_DISK_STORE, help = CliStrings.LIST_DISK_STORE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result listDiskStores() {
+    try {
+      Set<DistributedMember> dataMembers = DiskStoreCommandsUtils.getNormalMembers(getCache());
+
+      if (dataMembers.isEmpty()) {
+        return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
+      }
+
+      return toTabularResult(getDiskStoreListing(dataMembers));
+    } catch (FunctionInvocationTargetException ignore) {
+      return ResultBuilder.createGemFireErrorResult(CliStrings
+          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_DISK_STORE));
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable t) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult(
+          String.format(CliStrings.LIST_DISK_STORE__ERROR_MESSAGE, toString(t, isDebugging())));
+    }
+  }
+
+  @SuppressWarnings("unchecked")
+  List<DiskStoreDetails> getDiskStoreListing(Set<DistributedMember> members) {
+    final Execution membersFunctionExecutor = getMembersFunctionExecutor(members);
+    if (membersFunctionExecutor instanceof AbstractExecution) {
+      ((AbstractExecution) membersFunctionExecutor).setIgnoreDepartedMembers(true);
+    }
+
+    final ResultCollector<?, ?> resultCollector =
+        membersFunctionExecutor.execute(new ListDiskStoresFunction());
+
+    final List<?> results = (List<?>) resultCollector.getResult();
+    final List<DiskStoreDetails> distributedSystemMemberDiskStores =
+        new ArrayList<>(results.size());
+
+    for (final Object result : results) {
+      if (result instanceof Set) {
+        distributedSystemMemberDiskStores.addAll((Set<DiskStoreDetails>) result);
+      }
+    }
+
+    Collections.sort(distributedSystemMemberDiskStores);
+
+    return distributedSystemMemberDiskStores;
+  }
+
+  private Result toTabularResult(final List<DiskStoreDetails> diskStoreList)
+      throws ResultDataException {
+    if (!diskStoreList.isEmpty()) {
+      final TabularResultData diskStoreData = ResultBuilder.createTabularResultData();
+
+      for (final DiskStoreDetails diskStoreDetails : diskStoreList) {
+        diskStoreData.accumulate("Member Name", diskStoreDetails.getMemberName());
+        diskStoreData.accumulate("Member Id", diskStoreDetails.getMemberId());
+        diskStoreData.accumulate("Disk Store Name", diskStoreDetails.getName());
+        diskStoreData.accumulate("Disk Store ID", diskStoreDetails.getId());
+      }
+
+      return ResultBuilder.buildResult(diskStoreData);
+    } else {
+      return ResultBuilder
+          .createInfoResult(CliStrings.LIST_DISK_STORE__DISK_STORES_NOT_FOUND_MESSAGE);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca808714/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RevokeMissingDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RevokeMissingDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RevokeMissingDiskStoreCommand.java
new file mode 100644
index 0000000..98acf55
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RevokeMissingDiskStoreCommand.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class RevokeMissingDiskStoreCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.REVOKE_MISSING_DISK_STORE,
+      help = CliStrings.REVOKE_MISSING_DISK_STORE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.DISK)
+  public Result revokeMissingDiskStore(@CliOption(key = CliStrings.REVOKE_MISSING_DISK_STORE__ID,
+      mandatory = true, help = CliStrings.REVOKE_MISSING_DISK_STORE__ID__HELP) String id) {
+
+    try {
+      DistributedSystemMXBean dsMXBean =
+          ManagementService.getManagementService(getCache()).getDistributedSystemMXBean();
+      if (dsMXBean.revokeMissingDiskStores(id)) {
+        return ResultBuilder.createInfoResult("Missing disk store successfully revoked");
+      }
+
+      return ResultBuilder.createUserErrorResult("Unable to find missing disk store to revoke");
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      if (th.getMessage() == null) {
+        return ResultBuilder.createGemFireErrorResult(
+            "An error occurred while revoking missing disk stores: " + th);
+      }
+      return ResultBuilder.createGemFireErrorResult(
+          "An error occurred while revoking missing disk stores: " + th.getMessage());
+    }
+  }
+}


[17/47] geode git commit: GEODE-3436: Restore refactoring of Refactoring MiscellaneousCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
index f0c2c2f..674a0b6 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
@@ -14,9 +14,34 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertFalse;
+import static org.apache.geode.test.dunit.Assert.assertNotNull;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.Assert.fail;
+import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.test.dunit.Wait.waitForCriterion;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Properties;
 
-import org.apache.geode.cache.*;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.CacheClosedException;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
 import org.apache.geode.distributed.internal.DistributionConfig;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.lang.ThreadUtils;
@@ -24,27 +49,22 @@ import org.apache.geode.management.cli.Result;
 import org.apache.geode.management.cli.Result.Status;
 import org.apache.geode.management.internal.cli.HeadlessGfsh;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.*;
+import org.apache.geode.management.internal.cli.result.CommandResult;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
 import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
-import org.apache.geode.test.dunit.*;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.ResultData;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+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.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Properties;
-
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
-import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.Wait.waitForCriterion;
 
 /**
- * Dunit class for testing gemfire function commands : GC, Shutdown
+ * DUnit class for testing gemfire function commands : GC, Shutdown
  */
 @Category(DistributedTest.class)
 public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
@@ -75,20 +95,15 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     String command = "gc --group=Group1";
     CommandResult cmdResult = executeCommand(command);
     cmdResult.resetToFirstLine();
-    if (cmdResult != null) {
-      String cmdResultStr = commandResultToString(cmdResult);
-      getLogWriter()
-          .info("testGCForGroup cmdResultStr=" + cmdResultStr + "; cmdResult=" + cmdResult);
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-      if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
-        TabularResultData table = (TabularResultData) cmdResult.getResultData();
-        List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
-        assertEquals(true, memberNames.size() == 1);
-      } else {
-        fail("testGCForGroup failed as CommandResult should be table type");
-      }
+    String cmdResultStr = commandResultToString(cmdResult);
+    getLogWriter().info("testGCForGroup cmdResultStr=" + cmdResultStr + "; cmdResult=" + cmdResult);
+    assertEquals(Status.OK, cmdResult.getStatus());
+    if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
+      TabularResultData table = (TabularResultData) cmdResult.getResultData();
+      List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
+      assertEquals(true, memberNames.size() == 1);
     } else {
-      fail("testGCForGroup failed as did not get CommandResult");
+      fail("testGCForGroup failed as CommandResult should be table type");
     }
   }
 
@@ -101,23 +116,19 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
   public void testGCForMemberID() {
     setUpJmxManagerOnVm0ThenConnect(null);
     final VM vm1 = Host.getHost(0).getVM(1);
-    final String vm1MemberId = vm1.invoke(() -> getMemberId());
+    final String vm1MemberId = vm1.invoke(this::getMemberId);
     String command = "gc --member=" + vm1MemberId;
     CommandResult cmdResult = executeCommand(command);
     cmdResult.resetToFirstLine();
-    if (cmdResult != null) {
-      String cmdResultStr = commandResultToString(cmdResult);
-      getLogWriter().info("testGCForMemberID cmdResultStr=" + cmdResultStr);
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-      if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
-        TabularResultData table = (TabularResultData) cmdResult.getResultData();
-        List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
-        assertEquals(true, memberNames.size() == 1);
-      } else {
-        fail("testGCForGroup failed as CommandResult should be table type");
-      }
+    String cmdResultStr = commandResultToString(cmdResult);
+    getLogWriter().info("testGCForMemberID cmdResultStr=" + cmdResultStr);
+    assertEquals(Status.OK, cmdResult.getStatus());
+    if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
+      TabularResultData table = (TabularResultData) cmdResult.getResultData();
+      List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
+      assertEquals(true, memberNames.size() == 1);
     } else {
-      fail("testGCForCluster failed as did not get CommandResult");
+      fail("testGCForGroup failed as CommandResult should be table type");
     }
   }
 
@@ -128,7 +139,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
       props.setProperty(LOG_FILE, "testShowLogDefault.log");
       setUpJmxManagerOnVm0ThenConnect(props);
       final VM vm1 = Host.getHost(0).getVM(0);
-      final String vm1MemberId = vm1.invoke(() -> getMemberId());
+      final String vm1MemberId = vm1.invoke(this::getMemberId);
       String command = "show log --member=" + vm1MemberId;
       CommandResult cmdResult = executeCommand(command);
       if (cmdResult != null) {
@@ -152,7 +163,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     try {
       setUpJmxManagerOnVm0ThenConnect(props);
       final VM vm1 = Host.getHost(0).getVM(0);
-      final String vm1MemberId = vm1.invoke(() -> getMemberId());
+      final String vm1MemberId = vm1.invoke(this::getMemberId);
       String command = "show log --member=" + vm1MemberId + " --lines=50";
       CommandResult cmdResult = executeCommand(command);
       if (cmdResult != null) {
@@ -174,24 +185,20 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     String command = "gc";
     CommandResult cmdResult = executeCommand(command);
     cmdResult.resetToFirstLine();
-    if (cmdResult != null) {
-      String cmdResultStr = commandResultToString(cmdResult);
-      getLogWriter()
-          .info("testGCForEntireCluster cmdResultStr=" + cmdResultStr + "; cmdResult=" + cmdResult);
-      assertEquals(Result.Status.OK, cmdResult.getStatus());
-      if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
-        TabularResultData table = (TabularResultData) cmdResult.getResultData();
-        List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
-        assertEquals(3, memberNames.size());
-      } else {
-        fail("testGCForGroup failed as CommandResult should be table type");
-      }
+    String cmdResultStr = commandResultToString(cmdResult);
+    getLogWriter()
+        .info("testGCForEntireCluster cmdResultStr=" + cmdResultStr + "; cmdResult=" + cmdResult);
+    assertEquals(Status.OK, cmdResult.getStatus());
+    if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
+      TabularResultData table = (TabularResultData) cmdResult.getResultData();
+      List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
+      assertEquals(3, memberNames.size());
     } else {
-      fail("testGCForGroup failed as did not get CommandResult");
+      fail("testGCForGroup failed as CommandResult should be table type");
     }
   }
 
-  void setupForGC() {
+  private void setupForGC() {
     disconnectAllFromDS();
 
     final VM vm1 = Host.getHost(0).getVM(1);
@@ -307,7 +314,6 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
       }
     });
 
-
     String command = "shutdown --time-out=15";
     CommandResult cmdResult = executeCommand(command);
 
@@ -326,7 +332,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     });
   }
 
-  void setupForChangeLogLelvel() {
+  private void setupForChangeLogLevel() {
     final VM vm0 = Host.getHost(0).getVM(0);
     final VM vm1 = Host.getHost(0).getVM(1);
 
@@ -346,7 +352,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     });
   }
 
-  void setupForShutDown() {
+  private void setupForShutDown() {
     final VM vm0 = Host.getHost(0).getVM(0);
     final VM vm1 = Host.getHost(0).getVM(1);
 
@@ -367,7 +373,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     });
   }
 
-  void verifyShutDown() {
+  private void verifyShutDown() {
     final VM vm0 = Host.getHost(0).getVM(0);
     final VM vm1 = Host.getHost(0).getVM(1);
 
@@ -410,7 +416,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     final VM vm0 = Host.getHost(0).getVM(0);
     final VM vm1 = Host.getHost(0).getVM(1);
 
-    setupForChangeLogLelvel();
+    setupForChangeLogLevel();
 
     String serverName1 = (String) vm0.invoke(new SerializableCallable() {
       @Override

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java
index 8635306..43c5e95 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java
@@ -160,8 +160,8 @@ public class GfshCommandsSecurityTest {
         continue;
       }
 
-      assertThat(ResultBuilder.ERRORCODE_UNAUTHORIZED).describedAs(other.getCommand())
-          .isEqualTo(((ErrorResultData) result.getResultData()).getErrorCode());
+      assertThat(((ErrorResultData) result.getResultData()).getErrorCode())
+          .describedAs(other.getCommand()).isEqualTo(ResultBuilder.ERRORCODE_UNAUTHORIZED);
     }
   }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index e0d13b6..038e8cf 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -185,7 +185,14 @@ public class TestCommand {
     createTestCommand("import cluster-configuration --zip-file-name=value.zip", clusterManage);
 
     // DestroyFunctionCommand, ExecuteFunctionCommand, ListFunctionCommand
-    createTestCommand("destroy function --id=InterestCalculations", dataManage);
+    // TODO PSR: the `destroy function` command is interactive (in its interceptor) when both
+    // onGroup == null && onMember == null.
+    // This causes the function to throw
+    // CODE_SHELLCLIENT_ABORT_OP = 110;
+    // instead of the expected
+    // ERRORCODE_UNAUTHORIZED = 415;
+    // TODO: Should authorization occur before the interceptor resolves?
+    // createTestCommand("destroy function --id=InterestCalculations", dataManage);
     createTestCommand("execute function --id=InterestCalculations --groups=Group1", dataWrite);
     createTestCommand("list functions", clusterRead);
 


[37/47] geode git commit: GEODE-3502: Added awaitility clauses.

Posted by ds...@apache.org.
GEODE-3502: Added awaitility clauses.

	* Added awaitility clauses while waiting for the stat comparison checks
	* Replaced the deprecated Wait Criterion with Awaitility clause with increased timeout
	* Replaced the invokeAsync with invoke to make the test identical to the one in ClientHealthStatsDUnitTest
	* Removed the commented out flaky tag

	This closes #749


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

Branch: refs/heads/feature/GEODE-3543
Commit: dd7c45b438eede230ac78d2fe4f0bca88200dec7
Parents: 77a0b9f
Author: nabarun <nn...@pivotal.io>
Authored: Tue Aug 29 11:05:28 2017 -0700
Committer: nabarun <nn...@pivotal.io>
Committed: Tue Aug 29 14:47:00 2017 -0700

----------------------------------------------------------------------
 .../internal/cache/ha/Bug48571DUnitTest.java    | 72 ++++++++++----------
 1 file changed, 35 insertions(+), 37 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/dd7c45b4/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java
index 516275a..00ce44b 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java
@@ -49,12 +49,15 @@ import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
 import org.apache.geode.test.junit.categories.DistributedTest;
+
+import org.awaitility.Awaitility;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.Properties;
+import java.util.concurrent.TimeUnit;
 
 @Category({DistributedTest.class, ClientSubscriptionTest.class})
 public class Bug48571DUnitTest extends JUnit4DistributedTestCase {
@@ -95,32 +98,24 @@ public class Bug48571DUnitTest extends JUnit4DistributedTestCase {
   }
 
   private static void verifyProxyHasBeenPaused() {
-    WaitCriterion criterion = new WaitCriterion() {
-      @Override
-      public boolean done() {
-        CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-        Collection<CacheClientProxy> ccProxies = ccn.getClientProxies();
-
-        Iterator<CacheClientProxy> itr = ccProxies.iterator();
-
-        while (itr.hasNext()) {
-          CacheClientProxy ccp = itr.next();
-          System.out.println("proxy status " + ccp.getState());
-          if (ccp.isPaused())
-            return true;
+    Awaitility.await().atMost(60, TimeUnit.SECONDS).until(() -> {
+      CacheClientNotifier ccn = CacheClientNotifier.getInstance();
+      Collection<CacheClientProxy> ccProxies = ccn.getClientProxies();
+      boolean pausedFlag = false;
+      Iterator<CacheClientProxy> itr = ccProxies.iterator();
+
+      while (itr.hasNext()) {
+        CacheClientProxy ccp = itr.next();
+        System.out.println("proxy status " + ccp.getState());
+        if (ccp.isPaused()) {
+          pausedFlag = true;
+          break;
         }
-        return false;
-      }
-
-      @Override
-      public String description() {
-        return "Proxy has not paused yet";
       }
-    };
-    Wait.waitForCriterion(criterion, 15 * 1000, 200, true);
+      assertEquals("Proxy has not been paused in 1 minute", true, pausedFlag);
+    });
   }
 
-  // @Category(FlakyTest.class) // GEODE-510
   @Test
   public void testStatsMatchWithSize() throws Exception {
     IgnoredException.addIgnoredException("Unexpected IOException||Connection reset");
@@ -135,7 +130,7 @@ public class Bug48571DUnitTest extends JUnit4DistributedTestCase {
 
     server.invoke("verifyProxyHasBeenPaused", () -> verifyProxyHasBeenPaused());
     // resume puts on server, add another 100.
-    server.invokeAsync(() -> Bug48571DUnitTest.resumePuts()); // TODO: join or await result
+    server.invoke(() -> Bug48571DUnitTest.resumePuts());
     // start durable client
     client.invoke(() -> Bug48571DUnitTest.createClientCache(client.getHost(), port));
     // wait for full queue dispatch
@@ -283,19 +278,22 @@ public class Bug48571DUnitTest extends JUnit4DistributedTestCase {
   }
 
   public static void verifyStats() throws Exception {
-    CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-    CacheClientProxy ccp = ccn.getClientProxies().iterator().next();
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getQueueSize() " + ccp.getQueueSize());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getQueueSizeStat() " + ccp.getQueueSizeStat());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getEventsEnqued() " + ccp.getHARegionQueue().getStatistics().getEventsEnqued());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getEventsDispatched() " + ccp.getHARegionQueue().getStatistics().getEventsDispatched());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getEventsRemoved() " + ccp.getHARegionQueue().getStatistics().getEventsRemoved());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getNumVoidRemovals() " + ccp.getHARegionQueue().getStatistics().getNumVoidRemovals());
-    assertEquals(ccp.getQueueSize(), ccp.getQueueSizeStat());
+    Awaitility.await().atMost(60, TimeUnit.SECONDS).until(() -> {
+      CacheClientNotifier ccn = CacheClientNotifier.getInstance();
+      CacheClientProxy ccp = ccn.getClientProxies().iterator().next();
+      cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getQueueSize() " + ccp.getQueueSize());
+      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
+          "getQueueSizeStat() " + ccp.getQueueSizeStat());
+      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
+          "getEventsEnqued() " + ccp.getHARegionQueue().getStatistics().getEventsEnqued());
+      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
+          "getEventsDispatched() " + ccp.getHARegionQueue().getStatistics().getEventsDispatched());
+      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
+          "getEventsRemoved() " + ccp.getHARegionQueue().getStatistics().getEventsRemoved());
+      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
+          "getNumVoidRemovals() " + ccp.getHARegionQueue().getStatistics().getNumVoidRemovals());
+      assertEquals("The queue size did not match the stat value", ccp.getQueueSize(),
+          ccp.getQueueSizeStat());
+    });
   }
 }


[34/47] geode git commit: GEODE-3530: move FlakyTest category to class

Posted by ds...@apache.org.
GEODE-3530: move FlakyTest category to class

* add SuppressWarnings for serial
* organize imports


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

Branch: refs/heads/feature/GEODE-3543
Commit: 77a0b9f8e433465e266edd3a4c13ac8349fdd855
Parents: 1ea3451
Author: Kirk Lund <kl...@apache.org>
Authored: Tue Aug 29 14:12:27 2017 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Tue Aug 29 14:32:53 2017 -0700

----------------------------------------------------------------------
 .../LauncherLifecycleCommandsDUnitTest.java     |  9 +++-
 .../commands/AlterRegionCommandDUnitTest.java   |  6 +--
 .../cli/commands/ConfigCommandsDUnitTest.java   | 38 +++++++--------
 ...eateAlterDestroyRegionCommandsDUnitTest.java |  8 +--
 .../commands/CreateRegionCommandDUnitTest.java  |  8 +--
 .../commands/DestroyRegionCommandDUnitTest.java |  6 ++-
 .../commands/DiskStoreCommandsDUnitTest.java    | 11 ++---
 .../cli/commands/FunctionCommandsDUnitTest.java | 41 +++++++++-------
 .../commands/GemfireDataCommandsDUnitTest.java  | 48 +++++++++---------
 ...WithCacheLoaderDuringCacheMissDUnitTest.java | 46 ++++++++++++------
 ...stAndDescribeDiskStoreCommandsDUnitTest.java |  4 +-
 .../cli/commands/ListIndexCommandDUnitTest.java |  5 +-
 .../MiscellaneousCommandsDUnitTest.java         | 21 +++-----
 .../cli/commands/QueueCommandsDUnitTest.java    | 38 +++++++--------
 .../RebalanceCommandDistributedTest.java        | 15 +++---
 .../cli/commands/ShellCommandsDUnitTest.java    | 29 +++++------
 .../cli/commands/ShowMetricsDUnitTest.java      | 51 ++++++++++++--------
 .../cli/commands/ShowStackTraceDUnitTest.java   | 29 ++++++-----
 .../cli/commands/ClientCommandsTestUtils.java   |  1 -
 .../DescribeClientCommandDUnitTest.java         |  7 ++-
 .../DurableClientCommandsDUnitTest.java         |  3 +-
 .../commands/ListClientCommandDUnitTest.java    |  7 ++-
 .../cli/LuceneIndexCommandsDUnitTest.java       |  2 +-
 .../ClusterConfigurationDUnitTest.java          | 30 ++++++------
 .../ConnectCommandWithHttpAndSSLDUnitTest.java  | 31 ++++++++++--
 ...RebalanceCommandOverHttpDistributedTest.java |  8 +--
 26 files changed, 282 insertions(+), 220 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java
index 6e5d17c..f783c5d 100644
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java
@@ -51,6 +51,7 @@ import javax.management.remote.JMXConnectorFactory;
 import javax.management.remote.JMXServiceURL;
 
 import org.junit.FixMethodOrder;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.junit.runners.MethodSorters;
@@ -84,7 +85,9 @@ import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.dunit.rules.RequiresGeodeHome;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
 
 /**
  * The LauncherLifecycleCommandsDUnitTest class is a test suite of integration tests testing the
@@ -101,10 +104,14 @@ import org.apache.geode.test.junit.categories.DistributedTest;
  * @see org.apache.geode.management.internal.cli.util.CommandStringBuilder
  * @since GemFire 7.0
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3530
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@SuppressWarnings("serial")
 public class LauncherLifecycleCommandsDUnitTest extends CliCommandTestBase {
 
+  @Rule
+  public RequiresGeodeHome requiresGeodeHome = new RequiresGeodeHome();
+
   protected static final DateFormat TIMESTAMP = new SimpleDateFormat("yyyyMMddHHmmssSSS");
 
   private final Queue<Integer> processIds = new ConcurrentLinkedDeque<>();

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
index fa368ab..f1dad7d 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
@@ -12,7 +12,6 @@
  * or implied. See the License for the specific language governing permissions and limitations under
  * the License.
  */
-
 package org.apache.geode.management.internal.cli.commands;
 
 import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
@@ -50,8 +49,10 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
 
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3018 GEODE-3530
+@SuppressWarnings("serial")
 public class AlterRegionCommandDUnitTest extends CliCommandTestBase {
+
   private final String alterRegionName = "testAlterRegionRegion";
   private final String alterAsyncEventQueueId1 = "testAlterRegionQueue1";
   private final String alterAsyncEventQueueId2 = "testAlterRegionQueue2";
@@ -138,7 +139,6 @@ public class AlterRegionCommandDUnitTest extends CliCommandTestBase {
     this.alterVm1.invoke(() -> getCache().getRegion(alterRegionName).destroyRegion());
   }
 
-  @Category(FlakyTest.class) // GEODE-3018
   @Test
   public void testAlterRegionResetCacheListeners() throws IOException {
     setUpJmxManagerOnVm0ThenConnect(null);

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ConfigCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ConfigCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ConfigCommandsDUnitTest.java
index eeec317..a4f523c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ConfigCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ConfigCommandsDUnitTest.java
@@ -41,13 +41,29 @@ import static org.apache.geode.test.dunit.Assert.fail;
 import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
 import static org.apache.geode.test.dunit.Wait.waitForCriterion;
 
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.management.ManagementFactory;
+import java.lang.management.RuntimeMXBean;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.server.CacheServer;
 import org.apache.geode.distributed.Locator;
+import org.apache.geode.distributed.internal.ClusterConfigurationService;
 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.distributed.internal.ClusterConfigurationService;
 import org.apache.geode.internal.AvailablePortHelper;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator;
@@ -66,28 +82,13 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.lang.management.ManagementFactory;
-import java.lang.management.RuntimeMXBean;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Properties;
 
 /**
  * Dunit class for testing GemFire config commands : export config
  *
  * @since GemFire 7.0
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1449 GEODE-3530
 @SuppressWarnings("serial")
 public class ConfigCommandsDUnitTest extends CliCommandTestBase {
 
@@ -186,8 +187,7 @@ public class ConfigCommandsDUnitTest extends CliCommandTestBase {
     }
   }
 
-  @Category(FlakyTest.class) // GEODE-1449
-  @Test
+  @Test // FlakyTest: GEODE-1449
   public void testExportConfig() throws Exception {
     Properties localProps = new Properties();
     localProps.setProperty(NAME, "Manager");

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
index f8644cb..eaf714c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
@@ -73,9 +73,10 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
 
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-973 GEODE-2009 GEODE-3530
+@SuppressWarnings("serial")
 public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBase {
-  private static final long serialVersionUID = 1L;
+
   private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<>();
 
   private void waitForRegionMBeanCreation(final String regionPath) {
@@ -103,8 +104,7 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
    * Asserts that creating, altering and destroying regions correctly updates the shared
    * configuration.
    */
-  @Category(FlakyTest.class) // GEODE-2009
-  @Test
+  @Test // FlakyTest: GEODE-2009
   public void testCreateAlterDestroyUpdatesSharedConfig() throws Exception {
     disconnectAllFromDS();
     final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
index 4c0d2c2..2c0fb06 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
@@ -47,8 +47,10 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
 
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-973 GEODE-3530
+@SuppressWarnings("serial")
 public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
+
   private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<>();
 
   /**
@@ -149,9 +151,7 @@ public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
     assertEquals(Result.Status.OK, cmdResult.getStatus());
   }
 
-  @Category(FlakyTest.class) // GEODE-973: random ports, BindException,
-  // java.rmi.server.ExportException: Port already in use
-  @Test
+  @Test // FlakyTest: GEODE-973
   public void testCreateRegion46391() throws IOException {
     setUpJmxManagerOnVm0ThenConnect(null); // GEODE-973: getRandomAvailablePort
     String region46391 = "region46391";

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
index a3afe33..8598a4c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
@@ -12,7 +12,6 @@
  * or implied. See the License for the specific language governing permissions and limitations under
  * the License.
  */
-
 package org.apache.geode.management.internal.cli.commands;
 
 import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION;
@@ -72,9 +71,12 @@ import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
 
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3530
+@SuppressWarnings("serial")
 public class DestroyRegionCommandDUnitTest extends CliCommandTestBase {
+
   @Test
   public void testDestroyDistributedRegion() {
     setUpJmxManagerOnVm0ThenConnect(null);

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
index 341216c..526a4c1 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
@@ -116,14 +116,13 @@ import org.apache.geode.test.junit.categories.FlakyTest;
  * @see org.junit.Test
  * @since GemFire 7.0
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1206 GEODE-1406 GEODE-2102 GEODE-3530
 @SuppressWarnings("serial")
 public class DiskStoreCommandsDUnitTest extends CliCommandTestBase {
 
   private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<>();
 
-  @Category(FlakyTest.class) // GEODE-2102
-  @Test
+  @Test // FlakyTest: GEODE-2102
   public void testMissingDiskStore() {
     final String regionName = "testShowMissingDiskStoreRegion";
 
@@ -738,8 +737,7 @@ public class DiskStoreCommandsDUnitTest extends CliCommandTestBase {
   /**
    * Asserts that creating and destroying disk stores correctly updates the shared configuration.
    */
-  @Category(FlakyTest.class) // GEODE-1406
-  @Test
+  @Test // FlakyTest: GEODE-1406
   public void testCreateDestroyUpdatesSharedConfig() {
     disconnectAllFromDS();
     final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
@@ -1143,8 +1141,7 @@ public class DiskStoreCommandsDUnitTest extends CliCommandTestBase {
     assertEquals(true, resultAsString.contains(vm1Name));
   }
 
-  @Category(FlakyTest.class) // GEODE-1206: random ports, BindException
-  @Test
+  @Test // FlakyTest: GEODE-1206
   public void testCreateDiskStore() {
     final String diskStore1Name = "testCreateDiskStore1";
     final String diskStore2Name = "testCreateDiskStore2";

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java
index e03447f..a0788a0 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java
@@ -14,6 +14,22 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
+import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertFalse;
+import static org.apache.geode.test.dunit.Assert.assertNotNull;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.Assert.fail;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.test.dunit.Wait.waitForCriterion;
+
+import java.util.List;
+import java.util.Properties;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
@@ -28,29 +44,22 @@ import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.json.GfJsonException;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.test.dunit.*;
+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.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
 
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.util.List;
-import java.util.Properties;
-
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.Wait.waitForCriterion;
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-
 /**
  * Dunit class for testing gemfire function commands : execute function, destroy function, list
  * function
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1563 GEODE-3530
+@SuppressWarnings("serial")
 public class FunctionCommandsDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
   private static final String REGION_NAME = "FunctionCommandsReplicatedRegion";
   private static final String REGION_ONE = "RegionOne";
   private static final String REGION_TWO = "RegionTwo";
@@ -418,9 +427,7 @@ public class FunctionCommandsDUnitTest extends CliCommandTestBase {
     }
   }
 
-  @Category(FlakyTest.class) // GEODE-1563: JMX RMI (java.rmi.NoSuchObjectException: no such object
-                             // in table)
-  @Test
+  @Test // FlakyTest: GEODE-1563
   public void testExecuteFunctionOnGroups() {
     Properties localProps = new Properties();
     localProps.setProperty(NAME, "Manager");

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java
index 9da8072..0247c79 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java
@@ -15,11 +15,17 @@
 
 package org.apache.geode.management.internal.cli.commands;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.IgnoredException.*;
-import static org.apache.geode.test.dunit.LogWriterUtils.*;
-import static org.apache.geode.test.dunit.Wait.*;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertFalse;
+import static org.apache.geode.test.dunit.Assert.assertNotEquals;
+import static org.apache.geode.test.dunit.Assert.assertNotNull;
+import static org.apache.geode.test.dunit.Assert.assertNotSame;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.Assert.fail;
+import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.test.dunit.Wait.waitForCriterion;
 
 import java.io.File;
 import java.io.IOException;
@@ -91,7 +97,9 @@ import org.apache.geode.test.junit.categories.FlakyTest;
 /**
  * Dunit class for testing gemfire data commands : get, put, remove, select, rebalance
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1182 GEODE-1249 GEODE-1404 GEODE-1430
+                                                    // GEODE-1487 GEODE-1496 GEODE-1561 GEODE-1822
+                                                    // GEODE-2006 GEODE-3530
 @SuppressWarnings("serial")
 public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
 
@@ -577,8 +585,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
     validateResult(cmdResult, true);
   }
 
-  @Category(FlakyTest.class) // GEODE-2006
-  @Test
+  @Test // FlakyTest: GEODE-2006
   public void testSelectCommand() {
     setupForSelect();
     doTestGetRegionAssociatedMembersForSelect();
@@ -984,8 +991,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
       fail("Expected CompositeResult Returned Result Type " + cmdResult.getType());
   }
 
-  @Test
-  @Category(FlakyTest.class) // GEODE-1249
+  @Test // FlakyTest: GEODE-1249
   public void testSimplePutIfAbsentCommand() {
     final String keyPrefix = "testKey";
     final String valuePrefix = "testValue";
@@ -1047,8 +1053,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
     vm2.invoke(checkPutIfAbsentKeys);
   }
 
-  @Category(FlakyTest.class) // GEODE-1496 (http)
-  @Test
+  @Test // FlakyTest: GEODE-1496 (http)
   public void testSimpleRemoveCommand() {
     final String keyPrefix = "testKey";
     final String valuePrefix = "testValue";
@@ -1283,8 +1288,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
     }
   }
 
-  @Category(FlakyTest.class) // GEODE-1822
-  @Test
+  @Test // FlakyTest: GEODE-1822
   public void testGetLocateEntryLocationsForPR() {
     final String keyPrefix = "testKey";
     final String valuePrefix = "testValue";
@@ -1380,9 +1384,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
     vm2.invoke(checkPutKeysInVM2);
   }
 
-  @Category(FlakyTest.class) // GEODE-1182: random ports, BindException, HeadlessGFSH,
-                             // waitForCriterion, time sensitive
-  @Test
+  @Test // FlakyTest: GEODE-1182
   public void testGetLocateEntryJsonKeys() {
     final String keyPrefix = "testKey";
 
@@ -1507,8 +1509,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
     }
   }
 
-  @Category(FlakyTest.class) // GEODE-1430
-  @Test
+  @Test // FlakyTest: GEODE-1430
   public void testPutJsonKeys() {
     final String keyPrefix = "testKey";
 
@@ -1718,8 +1719,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
     return regionFactory.create(regionName);
   }
 
-  @Category(FlakyTest.class) // GEODE-1404
-  @Test
+  @Test // FlakyTest: GEODE-1404
   public void testImportExportData() throws InterruptedException, IOException {
     final String regionName = "Region1";
     final String exportFileName = "export.gfd";
@@ -2099,8 +2099,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
     }
   }
 
-  @Category(FlakyTest.class) // GEODE-1561
-  @Test
+  @Test // FlakyTest: GEODE-1561
   public void testSimulateForEntireDS() {
     setupTestRebalanceForEntireDS();
     // check if DistributedRegionMXBean is available so that command will not fail
@@ -2148,8 +2147,7 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
     }
   }
 
-  @Category(FlakyTest.class) // GEODE-1487
-  @Test
+  @Test // FlakyTest: GEODE-1487
   public void testRebalanceForEntireDS() {
     setupTestRebalanceForEntireDS();
     // check if DistributedRegionMXBean is available so that command will not fail

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GetCommandOnRegionWithCacheLoaderDuringCacheMissDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GetCommandOnRegionWithCacheLoaderDuringCacheMissDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GetCommandOnRegionWithCacheLoaderDuringCacheMissDUnitTest.java
index cebb7f1..5956433 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GetCommandOnRegionWithCacheLoaderDuringCacheMissDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GetCommandOnRegionWithCacheLoaderDuringCacheMissDUnitTest.java
@@ -14,7 +14,33 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import org.apache.geode.cache.*;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertFalse;
+import static org.apache.geode.test.dunit.Assert.assertNotNull;
+import static org.apache.geode.test.dunit.Assert.assertNull;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.Assert.fail;
+import static org.apache.geode.test.dunit.Host.getHost;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.test.dunit.Wait.waitForCriterion;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.CacheLoader;
+import org.apache.geode.cache.CacheLoaderException;
+import org.apache.geode.cache.LoaderHelper;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
 import org.apache.geode.management.DistributedRegionMXBean;
 import org.apache.geode.management.ManagementService;
 import org.apache.geode.management.ManagerMXBean;
@@ -30,19 +56,7 @@ import org.apache.geode.test.dunit.SerializableRunnableIF;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.Host.getHost;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.Wait.waitForCriterion;
+import org.apache.geode.test.junit.categories.FlakyTest;
 
 /**
  * The GetCommandOnRegionWithCacheLoaderDuringCacheMissDUnitTest class is test suite of test cases
@@ -53,8 +67,8 @@ import static org.apache.geode.test.dunit.Wait.waitForCriterion;
  * @see org.apache.geode.management.internal.cli.commands.GetCommand
  * @since GemFire 8.0
  */
-@SuppressWarnings("unused")
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3530
+@SuppressWarnings("serial")
 public class GetCommandOnRegionWithCacheLoaderDuringCacheMissDUnitTest extends CliCommandTestBase {
 
   private static final String GEMFIRE_MANAGER_NAME = "GemManagerNode";

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
index 1fe0bd1..bbd0b6c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
@@ -40,6 +40,7 @@ import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.SerializableRunnableIF;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
 
 /**
  * The ListAndDescribeDiskStoreCommandsDUnitTest class is a test suite of functional tests cases
@@ -52,7 +53,8 @@ import org.apache.geode.test.junit.categories.DistributedTest;
  *
  * @since GemFire 7.0
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3530
+@SuppressWarnings("serial")
 public class ListAndDescribeDiskStoreCommandsDUnitTest extends CliCommandTestBase {
 
   @Override

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
index 7b9afc3..226925f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
@@ -58,6 +58,7 @@ import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.SerializableRunnableIF;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
 
 /**
  * The ListIndexCommandDUnitTest class is distributed test suite of test cases for testing the
@@ -72,8 +73,8 @@ import org.apache.geode.test.junit.categories.DistributedTest;
  * @see org.apache.geode.management.internal.cli.commands.ListIndexCommand
  * @since GemFire 7.0
  */
-@SuppressWarnings("unused")
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3530
+@SuppressWarnings("serial")
 public class ListIndexCommandDUnitTest extends CliCommandTestBase {
 
   private static final int DEFAULT_REGION_INITIAL_CAPACITY = 10000;

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
index 674a0b6..3aeff61 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
@@ -66,10 +66,11 @@ import org.apache.geode.test.junit.categories.FlakyTest;
 /**
  * DUnit class for testing gemfire function commands : GC, Shutdown
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1034 GEODE-1385 GEODE-1518 GEODE-1605
+                                                    // GEODE-1706 GEODE-2126 GEODE-3530
+@SuppressWarnings("serial")
 public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
   private static String cachedLogLevel;
 
   @Override
@@ -84,9 +85,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     });
   }
 
-  @Category(FlakyTest.class) // GEODE-1034: random ports, GC sensitive, memory sensitive,
-                             // HeadlessGFSH
-  @Test
+  @Test // FlakyTest: GEODE-1034
   public void testGCForGroup() {
     Properties localProps = new Properties();
     localProps.setProperty(NAME, "Manager");
@@ -155,8 +154,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     }
   }
 
-  @Category(FlakyTest.class) // GEODE-2126
-  @Test
+  @Test // FlakyTest: GEODE-2126
   public void testShowLogNumLines() {
     Properties props = new Properties();
     props.setProperty(LOG_FILE, "testShowLogNumLines.log");
@@ -231,8 +229,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     });
   }
 
-  @Category(FlakyTest.class) // GEODE-1706
-  @Test
+  @Test // FlakyTest: GEODE-1706
   public void testShutDownWithoutTimeout() {
 
     addIgnoredException("EntryDestroyedException");
@@ -302,8 +299,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     assertFalse(defaultShell.isConnectedAndReady());
   }
 
-  @Category(FlakyTest.class) // GEODE-1385, 1518: time sensitive, HeadlessGfsh
-  @Test
+  @Test // FlakyTest: GEODE-1385 GEODE-1518
   public void testShutDownForTIMEOUT() {
     setupForShutDown();
     ThreadUtils.sleep(2500);
@@ -410,8 +406,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
     assertTrue(Boolean.FALSE.equals(vm0.invoke(connectedChecker)));
   }
 
-  @Category(FlakyTest.class) // GEODE-1605
-  @Test
+  @Test // FlakyTest: GEODE-1605
   public void testChangeLogLevelForMembers() {
     final VM vm0 = Host.getHost(0).getVM(0);
     final VM vm1 = Host.getHost(0).getVM(1);

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/QueueCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/QueueCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/QueueCommandsDUnitTest.java
index 163e0b0..8de6f89 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/QueueCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/QueueCommandsDUnitTest.java
@@ -34,7 +34,21 @@ import static org.apache.geode.test.dunit.Assert.fail;
 import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
 import static org.apache.geode.test.dunit.Wait.waitForCriterion;
 
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.nio.file.Files;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.CopyOnWriteArrayList;
+
 import org.apache.commons.io.FileUtils;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.asyncqueue.AsyncEventQueue;
 import org.apache.geode.distributed.Locator;
@@ -53,30 +67,16 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.nio.file.Files;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.CopyOnWriteArrayList;
 
 /**
  * A distributed test suite of test cases for testing the queue commands that are part of Gfsh.
  *
  * @since GemFire 8.0
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1429 GEODE-1976 GEODE-3530
+@SuppressWarnings("serial")
 public class QueueCommandsDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
-
   private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<>();
 
   @Override
@@ -84,8 +84,7 @@ public class QueueCommandsDUnitTest extends CliCommandTestBase {
     disconnectAllFromDS();
   }
 
-  @Category(FlakyTest.class) // GEODE-1429
-  @Test
+  @Test // FlakyTest: GEODE-1429
   public void testAsyncEventQueue() throws IOException {
     final String queue1Name = "testAsyncEventQueue1";
     final String queue2Name = "testAsyncEventQueue2";
@@ -267,8 +266,7 @@ public class QueueCommandsDUnitTest extends CliCommandTestBase {
   /**
    * Asserts that creating async event queues correctly updates the shared configuration.
    */
-  @Category(FlakyTest.class) // GEODE-1976
-  @Test
+  @Test // FlakyTest: GEODE-1976
   public void testCreateUpdatesSharedConfig() throws IOException {
     disconnectAllFromDS();
     final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandDistributedTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandDistributedTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandDistributedTest.java
index d8c3095..19dcfde 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandDistributedTest.java
@@ -18,6 +18,12 @@ import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
 import static org.apache.geode.test.dunit.Wait.waitForCriterion;
 import static org.assertj.core.api.Assertions.assertThat;
 
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.contrib.java.lang.system.ProvideSystemProperty;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
@@ -31,13 +37,10 @@ import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.contrib.java.lang.system.ProvideSystemProperty;
-import org.junit.experimental.categories.Category;
+import org.apache.geode.test.junit.categories.FlakyTest;
 
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3530
+@SuppressWarnings("serial")
 public class RebalanceCommandDistributedTest extends CliCommandTestBase {
 
   private static final String REBALANCE_REGION_NAME =

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShellCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShellCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShellCommandsDUnitTest.java
index 93bba3c..255013e 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShellCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShellCommandsDUnitTest.java
@@ -14,6 +14,18 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertNotNull;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.Assert.fail;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.distributed.AbstractLauncher.Status;
 import org.apache.geode.distributed.LocatorLauncher;
 import org.apache.geode.distributed.LocatorLauncher.LocatorState;
@@ -29,20 +41,11 @@ import org.apache.geode.management.internal.cli.shell.Gfsh;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.File;
-import java.util.concurrent.TimeUnit;
 
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-989 GEODE-3530
+@SuppressWarnings("serial")
 public class ShellCommandsDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
-
   @Override
   public final void postSetUpCliCommandTestBase() throws Exception {
     getDefaultShell();
@@ -53,9 +56,7 @@ public class ShellCommandsDUnitTest extends CliCommandTestBase {
         .addOption(CliStrings.CONNECT__LOCATOR, "localhost[" + locatorPort + "]").toString());
   }
 
-  @Category(FlakyTest.class) // GEODE-989: random ports, suspect string: DiskAccessException, disk
-                             // pollution, HeadlessGfsh, time sensitive
-  @Test
+  @Test // FlakyTest: GEODE-989
   public void testConnectToLocatorBecomesManager() {
     final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
 

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowMetricsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowMetricsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowMetricsDUnitTest.java
index 5c94c3a..b804099 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowMetricsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowMetricsDUnitTest.java
@@ -14,6 +14,22 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.test.dunit.Wait.waitForCriterion;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Properties;
+
+import javax.management.ObjectName;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
@@ -21,35 +37,29 @@ import org.apache.geode.cache.RegionShortcut;
 import org.apache.geode.cache.server.CacheServer;
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.internal.AvailablePortHelper;
-import org.apache.geode.management.*;
+import org.apache.geode.management.CacheServerMXBean;
+import org.apache.geode.management.DistributedRegionMXBean;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.MemberMXBean;
+import org.apache.geode.management.RegionMXBean;
 import org.apache.geode.management.cli.Result;
 import org.apache.geode.management.cli.Result.Status;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.remote.CommandProcessor;
 import org.apache.geode.management.internal.cli.result.CommandResult;
-import org.apache.geode.test.dunit.*;
+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.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import javax.management.ObjectName;
-import java.io.File;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.Properties;
 
-import static org.apache.geode.test.dunit.Assert.assertEquals;
-import static org.apache.geode.test.dunit.Assert.assertTrue;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.Wait.waitForCriterion;
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1764 GEODE-3530
+@SuppressWarnings("serial")
 public class ShowMetricsDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
-
   private void createLocalSetUp() {
     Properties localProps = new Properties();
     localProps.setProperty(NAME, "Controller");
@@ -220,8 +230,7 @@ public class ShowMetricsDUnitTest extends CliCommandTestBase {
     return waitCriterion;
   }
 
-  @Category(FlakyTest.class) // GEODE-1764
-  @Test
+  @Test // FlakyTest: GEODE-1764
   public void testShowMetricsMember()
       throws ClassNotFoundException, IOException, InterruptedException {
     systemSetUp();

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
index 51653a4..b8b96be 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
@@ -14,14 +14,25 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.LogWriterUtils.*;
+import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_TIME_STATISTICS;
+import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLING_ENABLED;
+import static org.apache.geode.test.dunit.Assert.assertFalse;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
 
 import java.io.File;
 import java.io.IOException;
 import java.util.Properties;
 
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
+
 import org.apache.geode.management.cli.Result.Status;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.json.GfJsonException;
@@ -31,20 +42,16 @@ import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
 import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TemporaryFolder;
 
-/***
+/**
  * DUnit test for 'show stack-trace' command
  */
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3530
+@SuppressWarnings("serial")
 public class ShowStackTraceDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
-
   @Rule
   public TemporaryFolder workDirectory = new SerializableTemporaryFolder();
 

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsTestUtils.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsTestUtils.java b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsTestUtils.java
index bf29918..5ab63e8 100644
--- a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsTestUtils.java
+++ b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsTestUtils.java
@@ -12,7 +12,6 @@
  * or implied. See the License for the specific language governing permissions and limitations under
  * the License.
  */
-
 package org.apache.geode.management.internal.cli.commands;
 
 import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_NETWORK_PARTITION_DETECTION;

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DescribeClientCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DescribeClientCommandDUnitTest.java b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DescribeClientCommandDUnitTest.java
index 33527f8..37170b1 100644
--- a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DescribeClientCommandDUnitTest.java
+++ b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DescribeClientCommandDUnitTest.java
@@ -75,10 +75,10 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
 
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-910 GEODE-3530
+@SuppressWarnings("serial")
 public class DescribeClientCommandDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
   private final String regionName = "stocks";
   private final String cq1 = "cq1";
   private final String cq2 = "cq2";
@@ -283,8 +283,7 @@ public class DescribeClientCommandDUnitTest extends CliCommandTestBase {
     ClientCommandsTestUtils.closeCacheServer(Host.getHost(0).getVM(1));
   }
 
-  @Category(FlakyTest.class) // GEODE-910: random ports, HeadlessGfsh
-  @Test
+  @Test // FlakyTest: GEODE-910
   public void testDescribeClientForNonSubscribedClient() throws Exception {
     setUpNonSubscribedClient();
 

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
index ef3b4a7..a6512a6 100644
--- a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
+++ b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
@@ -59,7 +59,8 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
 
-@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1705, GEODE-3404, GEODE-3359
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1705 GEODE-3404 GEODE-3359 GEODE-3530
+@SuppressWarnings("serial")
 public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
 
   private static final String REGION_NAME = "stocks";

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ListClientCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ListClientCommandDUnitTest.java b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ListClientCommandDUnitTest.java
index fb08afa..81e318e 100644
--- a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ListClientCommandDUnitTest.java
+++ b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ListClientCommandDUnitTest.java
@@ -68,16 +68,15 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
 
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-908 GEODE-3530
+@SuppressWarnings("serial")
 public class ListClientCommandDUnitTest extends CliCommandTestBase {
 
-  private static final long serialVersionUID = 1L;
   private final String regionName = "stocks";
   private int port0 = 0;
   private int port1 = 0;
 
-  @Category(FlakyTest.class) // GEODE-908: random ports, BindException, time sensitive, HeadlessGfsh
-  @Test
+  @Test // FlakyTest: GEODE-908
   public void testListClient() throws Exception {
     setupSystemForListClient();
 

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsDUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsDUnitTest.java
index 10409ca..c73952d 100755
--- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsDUnitTest.java
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsDUnitTest.java
@@ -64,9 +64,9 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 
 @Category(DistributedTest.class)
 @RunWith(JUnitParamsRunner.class)
+@SuppressWarnings("serial")
 public class LuceneIndexCommandsDUnitTest extends CliCommandTestBase {
 
-
   @Before
   public void createJMXManager() {
     disconnectAllFromDS();

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
index 9eb423f..ddb8d45 100644
--- a/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
+++ b/geode-wan/src/test/java/org/apache/geode/management/internal/configuration/ClusterConfigurationDUnitTest.java
@@ -39,6 +39,17 @@ import static org.apache.geode.test.dunit.Host.getHost;
 import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
 import static org.apache.geode.test.dunit.Wait.waitForCriterion;
 
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.Region;
@@ -68,18 +79,9 @@ import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
 
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-
-@Category(DistributedTest.class)
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-1333 GEODE-1334 GEODE-3530
+@SuppressWarnings("serial")
 public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
 
   private static final int TIMEOUT = 10000;
@@ -113,8 +115,7 @@ public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
    * 
    * @since GemFire 8.1
    */
-  @Category(FlakyTest.class) // GEODE-1334
-  @Test
+  @Test // FlakyTest: GEODE-1334
   public void testCreateExtensions() throws Exception {
     Object[] result = setup();
     final int locatorPort = (Integer) result[0];
@@ -184,8 +185,7 @@ public class ClusterConfigurationDUnitTest extends CliCommandTestBase {
    * 
    * @since GemFire 8.1
    */
-  @Category(FlakyTest.class) // GEODE-1333
-  @Test
+  @Test // FlakyTest: GEODE-1333
   public void testDestroyExtensions() throws Exception {
     Object[] result = setup();
     final int locatorPort = (Integer) result[0];

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java
index 8ab45b7..d8ef3a8 100644
--- a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java
+++ b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java
@@ -14,10 +14,29 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.management.internal.cli.i18n.CliStrings.*;
-import static org.apache.geode.util.test.TestUtil.*;
-import static org.junit.Assert.*;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_CIPHERS;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_ENABLED;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_KEYSTORE;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_KEYSTORE_TYPE;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_PROTOCOLS;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_TRUSTSTORE;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__KEY_STORE;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__KEY_STORE_PASSWORD;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__SSL_CIPHERS;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__SSL_PROTOCOLS;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__TRUST_STORE;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__TRUST_STORE_PASSWORD;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__URL;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__USE_HTTP;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.CONNECT__USE_SSL;
+import static org.apache.geode.util.test.TestUtil.getResourcePath;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
 
 import java.io.File;
 import java.util.Arrays;
@@ -38,15 +57,17 @@ import org.apache.geode.management.internal.cli.HeadlessGfsh;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
 import org.apache.geode.test.junit.categories.SecurityTest;
 import org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactory;
 
 /**
  * @since GemFire 8.1
  */
-@Category({DistributedTest.class, SecurityTest.class})
+@Category({DistributedTest.class, SecurityTest.class, FlakyTest.class}) // GEODE-3530
 @RunWith(Parameterized.class)
 @Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class)
+@SuppressWarnings("serial")
 public class ConnectCommandWithHttpAndSSLDUnitTest extends CliCommandTestBase {
 
   private static final ThreadLocal<Properties> sslInfoHolder = new ThreadLocal<>();

http://git-wip-us.apache.org/repos/asf/geode/blob/77a0b9f8/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandOverHttpDistributedTest.java
----------------------------------------------------------------------
diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandOverHttpDistributedTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandOverHttpDistributedTest.java
index 6101744..733f047 100644
--- a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandOverHttpDistributedTest.java
+++ b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandOverHttpDistributedTest.java
@@ -14,13 +14,15 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import org.apache.geode.test.junit.categories.DistributedTest;
 import org.junit.ClassRule;
 import org.junit.contrib.java.lang.system.ProvideSystemProperty;
 import org.junit.experimental.categories.Category;
 
-@Category(DistributedTest.class)
-@SuppressWarnings("deprecated")
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
+
+@Category({DistributedTest.class, FlakyTest.class}) // GEODE-3530
+@SuppressWarnings("serial")
 public class RebalanceCommandOverHttpDistributedTest extends RebalanceCommandDistributedTest {
 
   @ClassRule


[07/47] geode git commit: GEODE-3436: Restore refactoring of QueueCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of QueueCommands

* See initial commit GEODE-3267 (fd47ed660168864a6f81b2a4cd7dbceebc99a282)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 92f1eee4674a3f4dabe58f84bf5feb9d4d0ab6af
Parents: 6aab662
Author: YehEmily <em...@gmail.com>
Authored: Mon Aug 7 14:47:15 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:24 2017 -0700

----------------------------------------------------------------------
 .../commands/CreateAsyncEventQueueCommand.java  | 171 ++++++++++++
 .../commands/ListAsyncEventQueuesCommand.java   | 118 +++++++++
 .../internal/cli/commands/QueueCommands.java    | 259 -------------------
 .../controllers/QueueCommandsController.java    |  10 +-
 4 files changed, 295 insertions(+), 263 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/92f1eee4/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAsyncEventQueueCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAsyncEventQueueCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAsyncEventQueueCommand.java
new file mode 100644
index 0000000..ba9dc94
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAsyncEventQueueCommand.java
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.AsyncEventQueueFunctionArgs;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.CreateAsyncEventQueueFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CreateAsyncEventQueueCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.CREATE_ASYNC_EVENT_QUEUE,
+      help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__HELP)
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
+  public Result createAsyncEventQueue(
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, mandatory = true,
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID__HELP) String id,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GROUP__HELP) String[] groups,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL,
+          unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL__HELP) Boolean parallel,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION,
+          unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION__HELP) Boolean enableBatchConflation,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE,
+          unspecifiedDefaultValue = "100",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE__HELP) int batchSize,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL,
+          unspecifiedDefaultValue = "1000",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL__HELP) int batchTimeInterval,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT,
+          unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT__HELP) boolean persistent,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE,
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE__HELP) String diskStore,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS,
+          unspecifiedDefaultValue = "true", specifiedDefaultValue = "true",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY,
+          unspecifiedDefaultValue = "false", specifiedDefaultValue = "false",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY__HELP) Boolean ignoreEvictionAndExpiration,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY,
+          unspecifiedDefaultValue = "100",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY__HELP) int maxQueueMemory,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS,
+          unspecifiedDefaultValue = "1",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS__HELP) Integer dispatcherThreads,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY,
+          unspecifiedDefaultValue = "KEY",
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY__HELP) String orderPolicy,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER,
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER__HELP) String[] gatewayEventFilters,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER,
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER__HELP) String gatewaySubstitutionListener,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER, mandatory = true,
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER__HELP) String listener,
+      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE,
+          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE__HELP) String[] listenerParamsAndValues) {
+
+    if (persistent) {
+      getSecurityService().authorize(ResourcePermission.Resource.CLUSTER,
+          ResourcePermission.Operation.WRITE, ResourcePermission.Target.DISK);
+    }
+    Properties listenerProperties = new Properties();
+
+    try {
+      if (listenerParamsAndValues != null) {
+        for (String listenerParamsAndValue : listenerParamsAndValues) {
+          final int hashPosition = listenerParamsAndValue.indexOf('#');
+          if (hashPosition == -1) {
+            listenerProperties.put(listenerParamsAndValue, "");
+          } else {
+            listenerProperties.put(listenerParamsAndValue.substring(0, hashPosition),
+                listenerParamsAndValue.substring(hashPosition + 1));
+          }
+        }
+      }
+
+      TabularResultData tabularData = ResultBuilder.createTabularResultData();
+      boolean accumulatedData = false;
+
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      AsyncEventQueueFunctionArgs aeqArgs = new AsyncEventQueueFunctionArgs(id, parallel,
+          enableBatchConflation, batchSize, batchTimeInterval, persistent, diskStore,
+          diskSynchronous, maxQueueMemory, dispatcherThreads, orderPolicy, gatewayEventFilters,
+          gatewaySubstitutionListener, listener, listenerProperties, ignoreEvictionAndExpiration);
+
+      ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(new CreateAsyncEventQueueFunction(), aeqArgs, targetMembers);
+
+      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+      AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+      for (CliFunctionResult result : results) {
+        if (result.getThrowable() != null) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
+              + ": " + result.getThrowable().getMessage());
+          accumulatedData = true;
+          tabularData.setStatus(Result.Status.ERROR);
+        } else if (result.isSuccessful()) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Result", result.getMessage());
+          accumulatedData = true;
+
+          if (xmlEntity.get() == null) {
+            xmlEntity.set(result.getXmlEntity());
+          }
+        }
+      }
+
+      if (!accumulatedData) {
+        return ResultBuilder.createInfoResult("Unable to create async event queue(s).");
+      }
+
+      Result result = ResultBuilder.buildResult(tabularData);
+      if (xmlEntity.get() != null) {
+        persistClusterConfiguration(result,
+            () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
+      }
+      return result;
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult(
+          CliStrings.format(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ERROR_WHILE_CREATING_REASON_0,
+              new Object[] {th.getMessage()}));
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/92f1eee4/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListAsyncEventQueuesCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListAsyncEventQueuesCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListAsyncEventQueuesCommand.java
new file mode 100644
index 0000000..8b3d1bd
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListAsyncEventQueuesCommand.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.AsyncEventQueueDetails;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.ListAsyncEventQueuesFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ListAsyncEventQueuesCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.LIST_ASYNC_EVENT_QUEUES,
+      help = CliStrings.LIST_ASYNC_EVENT_QUEUES__HELP)
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result listAsyncEventQueues() {
+    try {
+      TabularResultData tabularData = ResultBuilder.createTabularResultData();
+      boolean accumulatedData = false;
+
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(null, null);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      ResultCollector<?, ?> rc = CliUtil.executeFunction(new ListAsyncEventQueuesFunction(),
+          new Object[] {}, targetMembers);
+      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+      for (CliFunctionResult result : results) {
+        if (result.getThrowable() != null) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
+              + ": " + result.getThrowable().getMessage());
+          accumulatedData = true;
+          tabularData.setStatus(Result.Status.ERROR);
+        } else {
+          AsyncEventQueueDetails[] details = (AsyncEventQueueDetails[]) result.getSerializables();
+          for (AsyncEventQueueDetails detail : details) {
+            tabularData.accumulate("Member", result.getMemberIdOrName());
+            tabularData.accumulate("ID", detail.getId());
+            tabularData.accumulate("Batch Size", detail.getBatchSize());
+            tabularData.accumulate("Persistent", detail.isPersistent());
+            tabularData.accumulate("Disk Store", detail.getDiskStoreName());
+            tabularData.accumulate("Max Memory", detail.getMaxQueueMemory());
+
+            Properties listenerProperties = detail.getListenerProperties();
+            if (listenerProperties == null || listenerProperties.size() == 0) {
+              tabularData.accumulate("Listener", detail.getListener());
+            } else {
+              StringBuilder propsStringBuilder = new StringBuilder();
+              propsStringBuilder.append('(');
+              boolean firstProperty = true;
+              for (Map.Entry<Object, Object> property : listenerProperties.entrySet()) {
+                if (!firstProperty) {
+                  propsStringBuilder.append(',');
+                } else {
+                  firstProperty = false;
+                }
+                propsStringBuilder.append(property.getKey()).append('=')
+                    .append(property.getValue());
+              }
+              propsStringBuilder.append(')');
+
+              tabularData.accumulate("Listener",
+                  detail.getListener() + propsStringBuilder.toString());
+            }
+            accumulatedData = true;
+          }
+        }
+      }
+
+      if (!accumulatedData) {
+        return ResultBuilder
+            .createInfoResult(CliStrings.LIST_ASYNC_EVENT_QUEUES__NO_QUEUES_FOUND_MESSAGE);
+      }
+
+      return ResultBuilder.buildResult(tabularData);
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult(
+          CliStrings.format(CliStrings.LIST_ASYNC_EVENT_QUEUES__ERROR_WHILE_LISTING_REASON_0,
+              new Object[] {th.getMessage()}));
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/92f1eee4/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
deleted file mode 100644
index 87c5bbc..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.AsyncEventQueueDetails;
-import org.apache.geode.management.internal.cli.functions.AsyncEventQueueFunctionArgs;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.CreateAsyncEventQueueFunction;
-import org.apache.geode.management.internal.cli.functions.ListAsyncEventQueuesFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.geode.security.ResourcePermission.Target;
-
-/**
- * The QueueCommands class encapsulates all GemFire Queue commands in Gfsh.
- * </p>
- * 
- * @since GemFire 8.0
- */
-public class QueueCommands implements GfshCommand {
-
-  @CliCommand(value = CliStrings.CREATE_ASYNC_EVENT_QUEUE,
-      help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__HELP)
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
-  public Result createAsyncEventQueue(
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, mandatory = true,
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID__HELP) String id,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GROUP__HELP) String[] groups,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL,
-          unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL__HELP) Boolean parallel,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION,
-          unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION__HELP) Boolean enableBatchConflation,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE,
-          unspecifiedDefaultValue = "100",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE__HELP) int batchSize,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL,
-          unspecifiedDefaultValue = "1000",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL__HELP) int batchTimeInterval,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT,
-          unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT__HELP) boolean persistent,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE,
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE__HELP) String diskStore,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS,
-          unspecifiedDefaultValue = "true", specifiedDefaultValue = "true",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY,
-          unspecifiedDefaultValue = "false", specifiedDefaultValue = "false",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY__HELP) Boolean ignoreEvictionAndExpiration,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY,
-          unspecifiedDefaultValue = "100",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY__HELP) int maxQueueMemory,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS,
-          unspecifiedDefaultValue = "1",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS__HELP) Integer dispatcherThreads,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY,
-          unspecifiedDefaultValue = "KEY",
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY__HELP) String orderPolicy,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER,
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER__HELP) String[] gatewayEventFilters,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER,
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER__HELP) String gatewaySubstitutionListener,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER, mandatory = true,
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER__HELP) String listener,
-      @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE,
-          help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE__HELP) String[] listenerParamsAndValues) {
-
-    if (persistent) {
-      getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
-    }
-    Properties listenerProperties = new Properties();
-
-    try {
-      if (listenerParamsAndValues != null) {
-        for (String listenerParamsAndValue : listenerParamsAndValues) {
-          final int hashPosition = listenerParamsAndValue.indexOf('#');
-          if (hashPosition == -1) {
-            listenerProperties.put(listenerParamsAndValue, "");
-          } else {
-            listenerProperties.put(listenerParamsAndValue.substring(0, hashPosition),
-                listenerParamsAndValue.substring(hashPosition + 1));
-          }
-        }
-      }
-
-      TabularResultData tabularData = ResultBuilder.createTabularResultData();
-      boolean accumulatedData = false;
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      AsyncEventQueueFunctionArgs aeqArgs = new AsyncEventQueueFunctionArgs(id, parallel,
-          enableBatchConflation, batchSize, batchTimeInterval, persistent, diskStore,
-          diskSynchronous, maxQueueMemory, dispatcherThreads, orderPolicy, gatewayEventFilters,
-          gatewaySubstitutionListener, listener, listenerProperties, ignoreEvictionAndExpiration);
-
-      ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(new CreateAsyncEventQueueFunction(), aeqArgs, targetMembers);
-
-      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
-      AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-      for (CliFunctionResult result : results) {
-        if (result.getThrowable() != null) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
-              + ": " + result.getThrowable().getMessage());
-          accumulatedData = true;
-          tabularData.setStatus(Status.ERROR);
-        } else if (result.isSuccessful()) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Result", result.getMessage());
-          accumulatedData = true;
-
-          if (xmlEntity.get() == null) {
-            xmlEntity.set(result.getXmlEntity());
-          }
-        }
-      }
-
-      if (!accumulatedData) {
-        return ResultBuilder.createInfoResult("Unable to create async event queue(s).");
-      }
-
-      Result result = ResultBuilder.buildResult(tabularData);
-      if (xmlEntity.get() != null) {
-        persistClusterConfiguration(result,
-            () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
-      }
-      return result;
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult(
-          CliStrings.format(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ERROR_WHILE_CREATING_REASON_0,
-              new Object[] {th.getMessage()}));
-    }
-  }
-
-  @CliCommand(value = CliStrings.LIST_ASYNC_EVENT_QUEUES,
-      help = CliStrings.LIST_ASYNC_EVENT_QUEUES__HELP)
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result listAsyncEventQueues() {
-    try {
-      TabularResultData tabularData = ResultBuilder.createTabularResultData();
-      boolean accumulatedData = false;
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(null, null);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      ResultCollector<?, ?> rc = CliUtil.executeFunction(new ListAsyncEventQueuesFunction(),
-          new Object[] {}, targetMembers);
-      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
-      for (CliFunctionResult result : results) {
-        if (result.getThrowable() != null) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
-              + ": " + result.getThrowable().getMessage());
-          accumulatedData = true;
-          tabularData.setStatus(Status.ERROR);
-        } else {
-          AsyncEventQueueDetails[] details = (AsyncEventQueueDetails[]) result.getSerializables();
-          for (AsyncEventQueueDetails detail : details) {
-            tabularData.accumulate("Member", result.getMemberIdOrName());
-            tabularData.accumulate("ID", detail.getId());
-            tabularData.accumulate("Batch Size", detail.getBatchSize());
-            tabularData.accumulate("Persistent", detail.isPersistent());
-            tabularData.accumulate("Disk Store", detail.getDiskStoreName());
-            tabularData.accumulate("Max Memory", detail.getMaxQueueMemory());
-
-            Properties listenerProperties = detail.getListenerProperties();
-            if (listenerProperties == null || listenerProperties.size() == 0) {
-              tabularData.accumulate("Listener", detail.getListener());
-            } else {
-              StringBuilder propsStringBuilder = new StringBuilder();
-              propsStringBuilder.append('(');
-              boolean firstProperty = true;
-              for (Map.Entry<Object, Object> property : listenerProperties.entrySet()) {
-                if (!firstProperty) {
-                  propsStringBuilder.append(',');
-                } else {
-                  firstProperty = false;
-                }
-                propsStringBuilder.append(property.getKey()).append('=')
-                    .append(property.getValue());
-              }
-              propsStringBuilder.append(')');
-
-              tabularData.accumulate("Listener",
-                  detail.getListener() + propsStringBuilder.toString());
-            }
-            accumulatedData = true;
-          }
-        }
-      }
-
-      if (!accumulatedData) {
-        return ResultBuilder
-            .createInfoResult(CliStrings.LIST_ASYNC_EVENT_QUEUES__NO_QUEUES_FOUND_MESSAGE);
-      }
-
-      return ResultBuilder.buildResult(tabularData);
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult(
-          CliStrings.format(CliStrings.LIST_ASYNC_EVENT_QUEUES__ERROR_WHILE_LISTING_REASON_0,
-              new Object[] {th.getMessage()}));
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/92f1eee4/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java
index 02d9bcb..9fea79a 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java
@@ -14,21 +14,23 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+
 /**
  * The QueueCommandsController class implements GemFire Management REST API web service endpoints
  * for the Gfsh Queue Commands.
  * <p/>
  * 
- * @see org.apache.geode.management.internal.cli.commands.QueueCommands
+ * @see org.apache.geode.management.internal.cli.commands.CreateAsyncEventQueueCommand
+ * @see org.apache.geode.management.internal.cli.commands.ListAsyncEventQueuesCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.PathVariable


[03/47] geode git commit: GEODE-3436: Restore refactoring of MemberCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of MemberCommands

* See initial commit GEODE-3264 (d27f8b956de7d9c5d95ebdc68dfc67ee8b2d7b51)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 33870085adbefa488b626361f82c4994e4682af5
Parents: 21c1fb9
Author: YehEmily <em...@gmail.com>
Authored: Tue Aug 22 10:57:05 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:22 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/DescribeMemberCommand.java     | 132 +++++++++++++
 .../cli/commands/ListMemberCommand.java         |  77 ++++++++
 .../internal/cli/commands/MemberCommands.java   | 195 -------------------
 .../controllers/MemberCommandsController.java   |  23 +--
 .../internal/security/TestCommand.java          |   2 +-
 5 files changed, 215 insertions(+), 214 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/33870085/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeMemberCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeMemberCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeMemberCommand.java
new file mode 100644
index 0000000..9f742ef
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeMemberCommand.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.CacheClosedException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.CacheServerInfo;
+import org.apache.geode.management.internal.cli.domain.MemberInformation;
+import org.apache.geode.management.internal.cli.functions.GetMemberInformationFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DescribeMemberCommand implements GfshCommand {
+  private static final GetMemberInformationFunction getMemberInformation =
+      new GetMemberInformationFunction();
+
+  @CliCommand(value = {CliStrings.DESCRIBE_MEMBER}, help = CliStrings.DESCRIBE_MEMBER__HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_SERVER)
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result describeMember(@CliOption(key = CliStrings.DESCRIBE_MEMBER__IDENTIFIER,
+      optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.DESCRIBE_MEMBER__HELP,
+      mandatory = true) String memberNameOrId) {
+    Result result = null;
+
+    try {
+      DistributedMember memberToBeDescribed =
+          CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+
+      if (memberToBeDescribed != null) {
+        ResultCollector<?, ?> rc =
+            CliUtil.executeFunction(getMemberInformation, null, memberToBeDescribed);
+
+        ArrayList<?> output = (ArrayList<?>) rc.getResult();
+        Object obj = output.get(0);
+
+        if (obj != null && (obj instanceof MemberInformation)) {
+
+          CompositeResultData crd = ResultBuilder.createCompositeResultData();
+
+          MemberInformation memberInformation = (MemberInformation) obj;
+          memberInformation.setName(memberToBeDescribed.getName());
+          memberInformation.setId(memberToBeDescribed.getId());
+          memberInformation.setHost(memberToBeDescribed.getHost());
+          memberInformation.setProcessId("" + memberToBeDescribed.getProcessId());
+
+          CompositeResultData.SectionResultData section = crd.addSection();
+          section.addData("Name", memberInformation.getName());
+          section.addData("Id", memberInformation.getId());
+          section.addData("Host", memberInformation.getHost());
+          section.addData("Regions",
+              CliUtil.convertStringSetToString(memberInformation.getHostedRegions(), '\n'));
+          section.addData("PID", memberInformation.getProcessId());
+          section.addData("Groups", memberInformation.getGroups());
+          section.addData("Used Heap", memberInformation.getHeapUsage() + "M");
+          section.addData("Max Heap", memberInformation.getMaxHeapSize() + "M");
+
+          String offHeapMemorySize = memberInformation.getOffHeapMemorySize();
+          if (offHeapMemorySize != null && !offHeapMemorySize.isEmpty()) {
+            section.addData("Off Heap Size", offHeapMemorySize);
+          }
+
+          section.addData("Working Dir", memberInformation.getWorkingDirPath());
+          section.addData("Log file", memberInformation.getLogFilePath());
+
+          section.addData("Locators", memberInformation.getLocators());
+
+          if (memberInformation.isServer()) {
+            CompositeResultData.SectionResultData clientServiceSection = crd.addSection();
+            List<CacheServerInfo> csList = memberInformation.getCacheServeInfo();
+
+            if (csList != null) {
+              Iterator<CacheServerInfo> iters = csList.iterator();
+              clientServiceSection.setHeader("Cache Server Information");
+
+              while (iters.hasNext()) {
+                CacheServerInfo cacheServerInfo = iters.next();
+                clientServiceSection.addData("Server Bind", cacheServerInfo.getBindAddress());
+                clientServiceSection.addData("Server Port", cacheServerInfo.getPort());
+                clientServiceSection.addData("Running", cacheServerInfo.isRunning());
+              }
+
+              clientServiceSection.addData("Client Connections",
+                  memberInformation.getClientCount());
+            }
+          }
+          result = ResultBuilder.buildResult(crd);
+
+        } else {
+          result = ResultBuilder.createInfoResult(CliStrings.format(
+              CliStrings.DESCRIBE_MEMBER__MSG__INFO_FOR__0__COULD_NOT_BE_RETRIEVED,
+              new Object[] {memberNameOrId}));
+        }
+      } else {
+        result = ResultBuilder.createInfoResult(CliStrings
+            .format(CliStrings.DESCRIBE_MEMBER__MSG__NOT_FOUND, new Object[] {memberNameOrId}));
+      }
+    } catch (CacheClosedException ignored) {
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/33870085/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListMemberCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListMemberCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListMemberCommand.java
new file mode 100644
index 0000000..ea88c69
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListMemberCommand.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ListMemberCommand implements GfshCommand {
+  @CliCommand(value = {CliStrings.LIST_MEMBER}, help = CliStrings.LIST_MEMBER__HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_SERVER)
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result listMember(@CliOption(key = {CliStrings.GROUP}, unspecifiedDefaultValue = "",
+      optionContext = ConverterHint.MEMBERGROUP,
+      help = CliStrings.LIST_MEMBER__GROUP__HELP) String group) {
+    Result result;
+
+    // TODO: Add the code for identifying the system services
+    try {
+      Set<DistributedMember> memberSet = new TreeSet<>();
+      InternalCache cache = getCache();
+
+      // default get all the members in the DS
+      if (group.isEmpty()) {
+        memberSet.addAll(CliUtil.getAllMembers(cache));
+      } else {
+        memberSet.addAll(cache.getDistributedSystem().getGroupMembers(group));
+      }
+
+      if (memberSet.isEmpty()) {
+        result = ResultBuilder.createInfoResult(CliStrings.LIST_MEMBER__MSG__NO_MEMBER_FOUND);
+      } else {
+        TabularResultData resultData = ResultBuilder.createTabularResultData();
+        for (DistributedMember member : memberSet) {
+          resultData.accumulate("Name", member.getName());
+          resultData.accumulate("Id", member.getId());
+        }
+
+        result = ResultBuilder.buildResult(resultData);
+      }
+    } catch (Exception e) {
+      result = ResultBuilder
+          .createGemFireErrorResult("Could not fetch the list of members. " + e.getMessage());
+      LogWrapper.getInstance().warning(e.getMessage(), e);
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/33870085/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MemberCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MemberCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MemberCommands.java
deleted file mode 100644
index 45642f6..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MemberCommands.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.CacheClosedException;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.domain.CacheServerInfo;
-import org.apache.geode.management.internal.cli.domain.MemberInformation;
-import org.apache.geode.management.internal.cli.functions.GetMemberInformationFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-
-/**
- * @since GemFire 7.0
- */
-public class MemberCommands implements GfshCommand {
-
-  private static final GetMemberInformationFunction getMemberInformation =
-      new GetMemberInformationFunction();
-
-  @CliCommand(value = {CliStrings.LIST_MEMBER}, help = CliStrings.LIST_MEMBER__HELP)
-  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_SERVER)
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result listMember(@CliOption(key = {CliStrings.GROUP}, unspecifiedDefaultValue = "",
-      optionContext = ConverterHint.MEMBERGROUP,
-      help = CliStrings.LIST_MEMBER__GROUP__HELP) String group) {
-    Result result = null;
-
-    // TODO: Add the code for identifying the system services
-    try {
-      Set<DistributedMember> memberSet = new TreeSet<DistributedMember>();
-      InternalCache cache = getCache();
-
-      // default get all the members in the DS
-      if (group.isEmpty()) {
-        memberSet.addAll(CliUtil.getAllMembers(cache));
-      } else {
-        memberSet.addAll(cache.getDistributedSystem().getGroupMembers(group));
-      }
-
-      if (memberSet.isEmpty()) {
-        result = ResultBuilder.createInfoResult(CliStrings.LIST_MEMBER__MSG__NO_MEMBER_FOUND);
-      } else {
-        TabularResultData resultData = ResultBuilder.createTabularResultData();
-        Iterator<DistributedMember> memberIters = memberSet.iterator();
-        while (memberIters.hasNext()) {
-          DistributedMember member = memberIters.next();
-          resultData.accumulate("Name", member.getName());
-          resultData.accumulate("Id", member.getId());
-        }
-
-        result = ResultBuilder.buildResult(resultData);
-      }
-    } catch (Exception e) {
-
-      result = ResultBuilder
-          .createGemFireErrorResult("Could not fetch the list of members. " + e.getMessage());
-      LogWrapper.getInstance().warning(e.getMessage(), e);
-    }
-
-    return result;
-  }
-
-  @CliCommand(value = {CliStrings.DESCRIBE_MEMBER}, help = CliStrings.DESCRIBE_MEMBER__HELP)
-  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_SERVER)
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result describeMember(@CliOption(key = CliStrings.DESCRIBE_MEMBER__IDENTIFIER,
-      optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.DESCRIBE_MEMBER__HELP,
-      mandatory = true) String memberNameOrId) {
-    Result result = null;
-
-    try {
-      DistributedMember memberToBeDescribed =
-          CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
-
-      if (memberToBeDescribed != null) {
-        // This information should be available through the MBeans too. We might not need
-        // the function.
-
-        // Yes, but then the command is subject to Mbean availability, which would be
-        // affected once MBean filters are used.
-
-        ResultCollector<?, ?> rc =
-            CliUtil.executeFunction(getMemberInformation, null, memberToBeDescribed);
-
-        ArrayList<?> output = (ArrayList<?>) rc.getResult();
-        Object obj = output.get(0);
-
-        if (obj != null && (obj instanceof MemberInformation)) {
-
-          CompositeResultData crd = ResultBuilder.createCompositeResultData();
-
-          MemberInformation memberInformation = (MemberInformation) obj;
-          memberInformation.setName(memberToBeDescribed.getName());
-          memberInformation.setId(memberToBeDescribed.getId());
-          memberInformation.setHost(memberToBeDescribed.getHost());
-          memberInformation.setProcessId("" + memberToBeDescribed.getProcessId());
-
-          SectionResultData section = crd.addSection();
-          section.addData("Name", memberInformation.getName());
-          section.addData("Id", memberInformation.getId());
-          section.addData("Host", memberInformation.getHost());
-          section.addData("Regions",
-              CliUtil.convertStringSetToString(memberInformation.getHostedRegions(), '\n'));
-          section.addData("PID", memberInformation.getProcessId());
-          section.addData("Groups", memberInformation.getGroups());
-          section.addData("Used Heap", memberInformation.getHeapUsage() + "M");
-          section.addData("Max Heap", memberInformation.getMaxHeapSize() + "M");
-
-          String offHeapMemorySize = memberInformation.getOffHeapMemorySize();
-          if (offHeapMemorySize != null && !offHeapMemorySize.isEmpty()) {
-            section.addData("Off Heap Size", offHeapMemorySize);
-          }
-
-          section.addData("Working Dir", memberInformation.getWorkingDirPath());
-          section.addData("Log file", memberInformation.getLogFilePath());
-
-          section.addData("Locators", memberInformation.getLocators());
-
-          if (memberInformation.isServer()) {
-            SectionResultData clientServiceSection = crd.addSection();
-            List<CacheServerInfo> csList = memberInformation.getCacheServeInfo();
-
-            if (csList != null) {
-              Iterator<CacheServerInfo> iters = csList.iterator();
-              clientServiceSection.setHeader("Cache Server Information");
-
-              while (iters.hasNext()) {
-                CacheServerInfo cacheServerInfo = iters.next();
-                clientServiceSection.addData("Server Bind", cacheServerInfo.getBindAddress());
-                clientServiceSection.addData("Server Port", cacheServerInfo.getPort());
-                clientServiceSection.addData("Running", cacheServerInfo.isRunning());
-              }
-
-              clientServiceSection.addData("Client Connections",
-                  memberInformation.getClientCount());
-            }
-          }
-          result = ResultBuilder.buildResult(crd);
-
-        } else {
-          result = ResultBuilder.createInfoResult(CliStrings.format(
-              CliStrings.DESCRIBE_MEMBER__MSG__INFO_FOR__0__COULD_NOT_BE_RETRIEVED,
-              new Object[] {memberNameOrId}));
-        }
-      } else {
-        result = ResultBuilder.createInfoResult(CliStrings
-            .format(CliStrings.DESCRIBE_MEMBER__MSG__NOT_FOUND, new Object[] {memberNameOrId}));
-      }
-    } catch (CacheClosedException e) {
-
-    } catch (FunctionInvocationTargetException e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-    return result;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/33870085/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java
index 66e82ee..ba5c788 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java
@@ -14,9 +14,6 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -24,12 +21,16 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+
 /**
  * The MemberCommandsController class implements GemFire Management REST API web service endpoints
  * for the Gfsh Member Commands.
  * <p/>
  * 
- * @see org.apache.geode.management.internal.cli.commands.MemberCommands
+ * @see org.apache.geode.management.internal.cli.commands.ListMemberCommand
+ * @see org.apache.geode.management.internal.cli.commands.DescribeMemberCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.PathVariable
@@ -46,25 +47,12 @@ public class MemberCommandsController extends AbstractCommandsController {
 
   @RequestMapping(method = RequestMethod.GET, value = "/members")
   @ResponseBody
-  // public String listMembers(@RequestBody MultiValueMap<String, String> requestParameters) {
-  // public String listMembers(@RequestParam(value = "group", required = false) final String
-  // groupName,
-  // @RequestParam(value = "group", required = false) final String[] groupNames) {
   public String listMembers(
       @RequestParam(value = CliStrings.GROUP, required = false) final String groupName) {
     CommandStringBuilder command = new CommandStringBuilder(CliStrings.LIST_MEMBER);
-
-    // logger.info(String.format("Request Body: %1$s", requestParameters));
-    // logger.info(String.format("Request Parameter (group): %1$s", groupName));
-    // logger.info(String.format("Request Parameter (group) as array: %1$s",
-    // ArrayUtils.toString(groupNames)));
-
-    // final String groupName = requestParameters.getFirst("group");
-
     if (hasValue(groupName)) {
       command.addOption(CliStrings.GROUP, groupName);
     }
-
     return processCommand(command.toString());
   }
 
@@ -75,5 +63,4 @@ public class MemberCommandsController extends AbstractCommandsController {
     command.addOption(CliStrings.DESCRIBE_MEMBER__IDENTIFIER, decode(memberNameId));
     return processCommand(command.toString());
   }
-
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/33870085/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index f380d88..3456e8c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -216,7 +216,7 @@ public class TestCommand {
     // createTestCommand("stop locator --name=locator1", clusterManage);
     // createTestCommand("stop server --name=server1", clusterManage);
 
-    // MemberCommands
+    // DescribeMemberCommand, ListMemberCommand
     createTestCommand("describe member --name=server1", clusterRead);
     createTestCommand("list members", clusterRead);
 


[29/47] geode git commit: GEODE-3277: revert changes to Launcher bind address and State constructors

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-core/src/test/java/org/apache/geode/distributed/LauncherIntegrationTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/LauncherIntegrationTestCase.java b/geode-core/src/test/java/org/apache/geode/distributed/LauncherIntegrationTestCase.java
index e2d40ec..409a96d 100755
--- a/geode-core/src/test/java/org/apache/geode/distributed/LauncherIntegrationTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/LauncherIntegrationTestCase.java
@@ -30,9 +30,7 @@ import java.io.FileWriter;
 import java.io.IOException;
 import java.io.UncheckedIOException;
 import java.lang.management.ManagementFactory;
-import java.net.InetAddress;
 import java.net.ServerSocket;
-import java.net.UnknownHostException;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicBoolean;
 
@@ -284,17 +282,9 @@ public abstract class LauncherIntegrationTestCase {
 
   private void givenPortInUse(final int port) {
     try {
-      givenPortInUse(port, InetAddress.getLocalHost());
-    } catch (UnknownHostException e) {
-      throw new UncheckedIOException(e);
-    }
-  }
-
-  private void givenPortInUse(final int port, InetAddress bindAddress) {
-    try {
       socket = SocketCreatorFactory
           .createNonDefaultInstance(false, false, null, null, System.getProperties())
-          .createServerSocket(port, 50, bindAddress, -1);
+          .createServerSocket(port, 50, null, -1);
       assertThat(socket.isBound()).isTrue();
       assertThat(socket.isClosed()).isFalse();
       assertThat(isPortAvailable(port, SOCKET)).isFalse();

http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-core/src/test/java/org/apache/geode/distributed/LocatorLauncherRemoteIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/LocatorLauncherRemoteIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/distributed/LocatorLauncherRemoteIntegrationTest.java
index 085e4da..cc42a53 100755
--- a/geode-core/src/test/java/org/apache/geode/distributed/LocatorLauncherRemoteIntegrationTest.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/LocatorLauncherRemoteIntegrationTest.java
@@ -185,8 +185,8 @@ public class LocatorLauncherRemoteIntegrationTest extends LocatorLauncherRemoteI
     assertThat(locatorState.getStatus()).isEqualTo(NOT_RESPONDING);
     assertThat(locatorState.getClasspath()).isNull();
     assertThat(locatorState.getGemFireVersion()).isEqualTo(GemFireVersion.getGemFireVersion());
-    assertThat(locatorState.getHost()).isEqualTo(InetAddress.getLocalHost().getCanonicalHostName());
-    assertThat(locatorState.getJavaVersion()).isEqualTo(System.getProperty("java.version"));
+    assertThat(locatorState.getHost()).isNull();
+    assertThat(locatorState.getJavaVersion()).isNull();
     assertThat(locatorState.getLogFile()).isNull();
     assertThat(locatorState.getMemberName()).isNull();
     assertThat(locatorState.getPid()).isNull();

http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherRemoteIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherRemoteIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherRemoteIntegrationTest.java
index 025ad5d..733a108 100755
--- a/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherRemoteIntegrationTest.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherRemoteIntegrationTest.java
@@ -244,9 +244,9 @@ public class ServerLauncherRemoteIntegrationTest extends ServerLauncherRemoteInt
     assertThat(serverState.getWorkingDirectory()).isEqualTo(getWorkingDirectoryPath());
     assertThat(serverState.getClasspath()).isNull();
     assertThat(serverState.getGemFireVersion()).isEqualTo(GemFireVersion.getGemFireVersion());
-    assertThat(serverState.getJavaVersion()).isEqualTo(System.getProperty("java.version"));
+    assertThat(serverState.getJavaVersion()).isNull();
     assertThat(serverState.getLogFile()).isNull();
-    assertThat(serverState.getHost()).isEqualTo(InetAddress.getLocalHost().getCanonicalHostName());
+    assertThat(serverState.getHost()).isNull();
     assertThat(serverState.getMemberName()).isNull();
   }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java b/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java
index 61d0596..2bcd994 100755
--- a/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/ServerLauncherTest.java
@@ -18,6 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.isNull;
 import static org.mockito.Mockito.atLeast;
 import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.mock;
@@ -270,7 +271,7 @@ public class ServerLauncherTest {
 
     launcher.startCacheServer(cache);
 
-    verify(cacheServer, times(1)).setBindAddress(anyString());
+    verify(cacheServer, times(1)).setBindAddress(isNull());
     verify(cacheServer, times(1)).setPort(eq(11235));
     verify(cacheServer, times(1)).start();
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/GfshStatusCommandsIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/GfshStatusCommandsIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/GfshStatusCommandsIntegrationTest.java
index 8537777..dd5841f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/GfshStatusCommandsIntegrationTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/GfshStatusCommandsIntegrationTest.java
@@ -19,13 +19,13 @@ import static org.assertj.core.api.Assertions.assertThat;
 import java.io.File;
 
 import org.junit.Before;
+import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.junit.rules.TemporaryFolder;
 import org.junit.rules.TestName;
 
-import org.apache.geode.internal.DistributionLocator;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.test.dunit.rules.GfshShellConnectionRule;
 import org.apache.geode.test.dunit.rules.LocatorStarterRule;
@@ -33,7 +33,8 @@ import org.apache.geode.test.junit.categories.IntegrationTest;
 
 @Category(IntegrationTest.class)
 public class GfshStatusCommandsIntegrationTest {
-  private static final String LOCATOR_NAME = "locator1";
+  final private static String LOCATOR_NAME = "locator1";
+  // private int port;
 
   @Rule
   public LocatorStarterRule locator =
@@ -51,48 +52,37 @@ public class GfshStatusCommandsIntegrationTest {
 
   @Before
   public void connect() throws Exception {
+    // port = getRandomAvailablePort(SOCKET);
     gfsh.connectAndVerify(locator);
   }
 
   @Test
-  public void statusLocatorWithBadPort_statusNotResponding() throws Exception {
-    String wrongPort = String.valueOf(locator.getLocator().getPort() - 1);
-    CommandResult result =
-        gfsh.executeCommand("status locator --host=localhost --port=" + wrongPort);
-    assertThat(result.getContent().getString("message")).doesNotContain("null");
+  public void statusLocatorWithBadPortReportsNotResponding() throws Exception {
+    CommandResult result = gfsh.executeCommand("status locator --host=localhost --port="
+        + String.valueOf(locator.getLocator().getPort() - 1));
     assertThat(result.getContent().getString("message")).contains("not responding");
-    assertThat(result.getContent().getString("message")).contains(wrongPort);
   }
 
   @Test
-  public void statusLocatorDefault_LocatorOnNonDefaultPort_statusNotResponding() throws Exception {
-    CommandResult result = gfsh.executeCommand("status locator --host=localhost");
-    assertThat(result.getContent().getString("message")).doesNotContain("null");
-    assertThat(result.getContent().getString("message")).contains("not responding");
-    assertThat(result.getContent().getString("message"))
-        .contains(String.valueOf(DistributionLocator.DEFAULT_LOCATOR_PORT));
-  }
-
-  @Test
-  public void statusLocatorWithActivePort_statusOnline() throws Exception {
+  public void statusLocatorWithActivePortReportsOnline() throws Exception {
     CommandResult result = gfsh.executeCommand(
         "status locator --host=localhost --port=" + String.valueOf(locator.getLocator().getPort()));
     assertThat(result.getContent().getString("message")).contains("is currently online");
   }
 
   @Test
-  public void statusServerNoServer_statusNotResponding() throws Exception {
+  public void statusServerWithWithNoOptions() throws Exception {
+    File serverDir = new File(temporaryFolder.getRoot(), "serverDir");
+    serverDir.mkdirs();
     CommandResult result = gfsh.executeCommand("status server");
-    assertThat(result.getContent().getString("message")).doesNotContain("null");
     assertThat(result.getContent().getString("message")).contains("not responding");
   }
 
   @Test
-  public void statusServerWithEmptyDir_statusNotResponding() throws Exception {
+  public void statusServerWithInvalidDirReturnsMeangingfulMessage() throws Exception {
     File serverDir = new File(temporaryFolder.getRoot(), "serverDir");
     serverDir.mkdirs();
     CommandResult result = gfsh.executeCommand("status server --dir=" + serverDir.toString());
-    assertThat(result.getContent().getString("message")).doesNotContain("null");
     assertThat(result.getContent().getString("message")).contains("not responding");
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java
index dc17d03..e7f17ef 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java
@@ -44,12 +44,12 @@ import org.apache.geode.test.junit.rules.DescribedExternalResource;
  *
  * you can use this as Rule
  * 
- * @Rule GfshShellConnectionRule rule = new GfshShellConnectionRule(); then after you connect to a
+ * @Rule GfshShellConnectionRule rule = new GfshSheelConnectionRule(); then after you connect to a
  *       locator, you don't have to call disconnect() or close() at all, since the rule's after
  *       takes care of it for you.
  *
  *       Or as a ClassRule
- * @ClassRule GfshShellConnectionRule rule = new GfshShellConnectionRule(); When using as a
+ * @ClassRule GfshShellConnectionRule rule = new GfshSheelConnectionRule(); When using as a
  *            ClassRule, if you call connect in a test, you will need to call disconnect after the
  *            test as well. See NetstatDUnitTest for example.
  *


[06/47] geode git commit: GEODE-3436: Restore refactoring of GfshHelpCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of GfshHelpCommands

* See initial commit GEODE-3261 (cf91426692349d0c81ce77394935576d9cc336e8)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 4fc3ffe07e2a326d765240d5fd7e65f27b6ed3cf
Parents: 92f1eee
Author: YehEmily <em...@gmail.com>
Authored: Thu Aug 24 15:42:12 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:24 2017 -0700

----------------------------------------------------------------------
 .../internal/cli/commands/GfshHelpCommand.java  | 45 ++++++++++++
 .../internal/cli/commands/GfshHelpCommands.java | 55 ---------------
 .../internal/cli/commands/GfshHintCommand.java  | 42 +++++++++++
 .../internal/cli/converters/HelpConverter.java  | 25 +++----
 .../cli/help/HelperIntegrationTest.java         | 73 +++++++++++++++++---
 .../internal/security/TestCommand.java          |  2 +-
 6 files changed, 160 insertions(+), 82 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/4fc3ffe0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
new file mode 100644
index 0000000..1161f65
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CommandManager;
+import org.apache.geode.management.internal.cli.CommandManagerAware;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.springframework.shell.core.CommandMarker;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+public class GfshHelpCommand implements GfshCommand, CommandManagerAware {
+  private CommandManager commandManager = null;
+
+  public void setCommandManager(CommandManager commandManager) {
+    this.commandManager = commandManager;
+  }
+
+  @CliCommand(value = CliStrings.HELP, help = CliStrings.HELP__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
+  public Result obtainHelp(
+      @CliOption(key = {"", CliStrings.SH__COMMAND}, optionContext = ConverterHint.HELP,
+          help = "Command name to provide help for") String buffer) {
+
+    return ResultBuilder.createInfoResult(commandManager.obtainHelp(buffer));
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/4fc3ffe0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommands.java
deleted file mode 100644
index 5fd7988..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommands.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CommandManager;
-import org.apache.geode.management.internal.cli.CommandManagerAware;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.springframework.shell.core.CommandMarker;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-/**
- * @since GemFire 7.0
- */
-public class GfshHelpCommands implements GfshCommand, CommandManagerAware {
-  private CommandManager commandManager = null;
-
-  public void setCommandManager(CommandManager commandManager) {
-    this.commandManager = commandManager;
-  }
-
-  @CliCommand(value = CliStrings.HELP, help = CliStrings.HELP__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
-  public Result obtainHelp(
-      @CliOption(key = {"", CliStrings.SH__COMMAND}, optionContext = ConverterHint.HELP,
-          help = "Command name to provide help for") String buffer) {
-
-    return ResultBuilder.createInfoResult(commandManager.obtainHelp(buffer));
-  }
-
-  @CliCommand(value = CliStrings.HINT, help = CliStrings.HINT__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
-  public Result hint(@CliOption(key = {"", CliStrings.HINT__TOPICNAME},
-      optionContext = ConverterHint.HINT, help = CliStrings.HINT__TOPICNAME) String topicName) {
-
-    return ResultBuilder.createInfoResult(commandManager.obtainHint(topicName));
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/4fc3ffe0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHintCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHintCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHintCommand.java
new file mode 100644
index 0000000..ccc1900
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHintCommand.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CommandManager;
+import org.apache.geode.management.internal.cli.CommandManagerAware;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+
+public class GfshHintCommand implements GfshCommand, CommandManagerAware {
+  private CommandManager commandManager = null;
+
+  public void setCommandManager(CommandManager commandManager) {
+    this.commandManager = commandManager;
+  }
+
+  @CliCommand(value = CliStrings.HINT, help = CliStrings.HINT__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
+  public Result hint(@CliOption(key = {"", CliStrings.HINT__TOPICNAME},
+      optionContext = ConverterHint.HINT, help = CliStrings.HINT__TOPICNAME) String topicName) {
+    return ResultBuilder.createInfoResult(commandManager.obtainHint(topicName));
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/4fc3ffe0/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java
index 88fd758..502eddd 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java
@@ -14,19 +14,20 @@
  */
 package org.apache.geode.management.internal.cli.converters;
 
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.internal.cli.CommandManager;
-import org.apache.geode.management.internal.cli.CommandManagerAware;
-import org.apache.geode.management.internal.cli.commands.GfshHelpCommands;
+import java.util.List;
+import java.util.Set;
+
 import org.springframework.shell.core.Completion;
 import org.springframework.shell.core.Converter;
 import org.springframework.shell.core.MethodTarget;
 
-import java.util.List;
-import java.util.Set;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.internal.cli.CommandManager;
+import org.apache.geode.management.internal.cli.CommandManagerAware;
+import org.apache.geode.management.internal.cli.commands.GfshHelpCommand;
 
 /**
- * {@link Converter} for {@link GfshHelpCommands#obtainHelp(String)}
+ * {@link Converter} for {@link GfshHelpCommand#obtainHelp(String)}
  * 
  *
  * @since GemFire 7.0
@@ -48,18 +49,12 @@ public class HelpConverter implements Converter<String>, CommandManagerAware {
       completionCandidates.add(new Completion(string));
     }
 
-    if (completionCandidates.size() > 0) {
-      return true;
-    }
-    return false;
+    return completionCandidates.size() > 0;
   }
 
   @Override
   public boolean supports(Class<?> arg0, String optionContext) {
-    if (String.class.isAssignableFrom(arg0) && optionContext.contains(ConverterHint.HELP)) {
-      return true;
-    }
-    return false;
+    return String.class.isAssignableFrom(arg0) && optionContext.contains(ConverterHint.HELP);
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/geode/blob/4fc3ffe0/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java
index 48ad499..e44465f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java
@@ -15,16 +15,22 @@
 
 package org.apache.geode.management.internal.cli.help;
 
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.HINT__MSG__TOPICS_AVAILABLE;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.HINT__MSG__UNKNOWN_TOPIC;
+import static org.apache.geode.management.internal.cli.i18n.CliStrings.TOPIC_CLIENT__DESC;
 import static org.assertj.core.api.Assertions.assertThat;
 
-import org.apache.geode.management.internal.cli.commands.GfshHelpCommands;
-import org.apache.geode.test.junit.categories.IntegrationTest;
+import java.lang.reflect.Method;
+
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.springframework.shell.core.annotation.CliCommand;
 
-import java.lang.reflect.Method;
+import org.apache.geode.management.internal.cli.commands.GfshHelpCommand;
+import org.apache.geode.management.internal.cli.commands.GfshHintCommand;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.test.junit.categories.IntegrationTest;
 
 @Category(IntegrationTest.class)
 public class HelperIntegrationTest {
@@ -33,8 +39,20 @@ public class HelperIntegrationTest {
   @BeforeClass
   public static void beforeClass() {
     helper = new Helper();
-    // use GfshHelpCommand for testing
-    Method[] methods = GfshHelpCommands.class.getMethods();
+  }
+
+  private void getHelpCommand() {
+    Method[] methods = GfshHelpCommand.class.getMethods();
+    for (Method method : methods) {
+      CliCommand cliCommand = method.getDeclaredAnnotation(CliCommand.class);
+      if (cliCommand != null) {
+        helper.addCommand(cliCommand, method);
+      }
+    }
+  }
+
+  private void getHintCommand() {
+    Method[] methods = GfshHintCommand.class.getMethods();
     for (Method method : methods) {
       CliCommand cliCommand = method.getDeclaredAnnotation(CliCommand.class);
       if (cliCommand != null) {
@@ -45,19 +63,52 @@ public class HelperIntegrationTest {
 
   @Test
   public void testHelpWithNoInput() {
-    String test = helper.getHelp(null, -1);
-    String[] helpLines = test.split("\n");
-    assertThat(helpLines).hasSize(4);
+    getHelpCommand();
+    String testNoInput = helper.getHelp(null, -1);
+    String[] helpLines = testNoInput.split("\n");
+    assertThat(helpLines).hasSize(2);
     assertThat(helpLines[0]).isEqualTo("help (Available)");
-    assertThat(helpLines[2]).isEqualTo("hint (Available)");
+    assertThat(helpLines[1]).isEqualTo(CliStrings.HELP__HELP);
   }
 
   @Test
   public void testHelpWithInput() {
-    String test = helper.getHelp("help", -1);
-    String[] helpLines = test.split("\n");
+    getHelpCommand();
+    String testInput = helper.getHelp("help", -1);
+    String[] helpLines = testInput.split("\n");
     assertThat(helpLines).hasSize(12);
     assertThat(helpLines[0]).isEqualTo("NAME");
     assertThat(helpLines[1]).isEqualTo("help");
   }
+
+  @Test
+  public void testHelpWithInvalidInput() {
+    getHelpCommand();
+    String testInvalidInput = helper.getHelp("InvalidTopic", -1);
+    assertThat(testInvalidInput).isEqualTo("no help exists for this command.");
+  }
+
+  @Test
+  public void testHintWithNoInput() {
+    getHintCommand();
+    String testNoInput = helper.getHint(null);
+    String[] hintLines = testNoInput.split("\n");
+    assertThat(hintLines).hasSize(21);
+    assertThat(hintLines[0]).isEqualTo(HINT__MSG__TOPICS_AVAILABLE);
+  }
+
+  @Test
+  public void testHintWithInput() {
+    getHintCommand();
+    String testInput = helper.getHint("Client");
+    assertThat(testInput).contains(TOPIC_CLIENT__DESC);
+  }
+
+  @Test
+  public void testHintWithInvalidInput() {
+    getHintCommand();
+    String testInvalidInput = helper.getHint("InvalidTopic");
+    assertThat(testInvalidInput)
+        .isEqualTo(CliStrings.format(HINT__MSG__UNKNOWN_TOPIC, "InvalidTopic"));
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/4fc3ffe0/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index d382646..ac5058f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -189,7 +189,7 @@ public class TestCommand {
     createTestCommand("execute function --id=InterestCalculations --groups=Group1", dataWrite);
     createTestCommand("list functions", clusterRead);
 
-    // GfshHelpCommands
+    // GfshHelpCommand, GfshHintCommand
     createTestCommand("hint");
     createTestCommand("help");
 


[30/47] geode git commit: GEODE-3277: revert changes to Launcher bind address and State constructors

Posted by ds...@apache.org.
GEODE-3277: revert changes to Launcher bind address and State constructors

This reverts commit 73a847a4b22239414db0ae9d973673f6a03fdcf0.
This reverts commit 4a5c56eb8edd277b258e916212d41bec0b0e7b83.
This reverts commit f41ca9d7d2fa7c045ec439df9478335233f1d95e.


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

Branch: refs/heads/feature/GEODE-3543
Commit: 4ac5e65f79ca7383cc7274c65c9a435d124b5d75
Parents: 4c55938
Author: Ken Howe <kh...@pivotal.io>
Authored: Tue Aug 29 10:31:46 2017 -0700
Committer: Ken Howe <kh...@pivotal.io>
Committed: Tue Aug 29 10:38:58 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/StatusLocatorRealGfshTest.java |  24 +-
 .../geode/distributed/LocatorLauncher.java      | 248 ++++++++---------
 .../geode/distributed/ServerLauncher.java       | 266 ++++++++-----------
 .../LauncherIntegrationTestCase.java            |  12 +-
 .../LocatorLauncherRemoteIntegrationTest.java   |   4 +-
 .../ServerLauncherRemoteIntegrationTest.java    |   4 +-
 .../geode/distributed/ServerLauncherTest.java   |   3 +-
 .../GfshStatusCommandsIntegrationTest.java      |  34 +--
 .../dunit/rules/GfshShellConnectionRule.java    |   4 +-
 9 files changed, 251 insertions(+), 348 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorRealGfshTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorRealGfshTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorRealGfshTest.java
index 02f49a6..3a98373 100644
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorRealGfshTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorRealGfshTest.java
@@ -14,12 +14,6 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import static org.apache.geode.internal.AvailablePort.SOCKET;
-import static org.apache.geode.internal.AvailablePort.getRandomAvailablePort;
-
-import java.net.InetAddress;
-
-import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -33,26 +27,16 @@ public class StatusLocatorRealGfshTest {
   @Rule
   public GfshRule gfshRule = new GfshRule();
 
-  private int port;
-
-  @Before
-  public void setup() {
-    port = getRandomAvailablePort(SOCKET);
-  }
-
   @Test
   public void statusLocatorSucceedsWhenConnected() throws Exception {
-    GfshScript.of("start locator --name=locator1 --port=" + Integer.valueOf(port))
-        .execute(gfshRule);
+    GfshScript.of("start locator --name=locator1").execute(gfshRule);
 
-    GfshScript.of("connect --locator=" + InetAddress.getLocalHost().getHostAddress() + "["
-        + Integer.valueOf(port) + "]", "status locator --name=locator1").execute(gfshRule);
+    GfshScript.of("connect", "status locator --name=locator1").execute(gfshRule);
   }
 
   @Test
-  public void statusLocatorByNameFailsWhenNotConnected() throws Exception {
-    GfshScript.of("start locator --name=locator1 --port=" + Integer.valueOf(port))
-        .withName("start locator").execute(gfshRule);
+  public void statusLocatorFailsWhenNotConnected() throws Exception {
+    GfshScript.of("start locator --name=locator1").withName("start locator").execute(gfshRule);
 
     GfshScript.of("status locator --name=locator1").withName("status locator").expectFailure()
         .execute(gfshRule);

http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java b/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java
index bc258be..83c1ab5 100644
--- a/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/LocatorLauncher.java
@@ -74,16 +74,16 @@ import org.apache.geode.internal.process.ProcessControllerParameters;
 import org.apache.geode.internal.process.ProcessLauncherContext;
 import org.apache.geode.internal.process.ProcessType;
 import org.apache.geode.internal.process.ProcessUtils;
+import org.apache.geode.internal.process.StartupStatusListener;
 import org.apache.geode.internal.process.UnableToControlProcessException;
 import org.apache.geode.lang.AttachAPINotFoundException;
 import org.apache.geode.management.internal.cli.json.GfJsonArray;
 import org.apache.geode.management.internal.cli.json.GfJsonException;
 import org.apache.geode.management.internal.cli.json.GfJsonObject;
-import org.apache.geode.management.internal.cli.util.HostUtils;
 
 /**
  * The LocatorLauncher class is a launcher for a GemFire Locator.
- *
+ * 
  * @see org.apache.geode.distributed.AbstractLauncher
  * @see org.apache.geode.distributed.ServerLauncher
  * @since GemFire 7.0
@@ -183,7 +183,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Launches a GemFire Locator from the command-line configured with the given arguments.
-   *
+   * 
    * @param args the command-line arguments used to configure the GemFire Locator at runtime.
    */
   public static void main(final String... args) {
@@ -202,7 +202,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Gets the instance of the LocatorLauncher used to launch the GemFire Locator, or null if this VM
    * does not have an instance of LocatorLauncher indicating no GemFire Locator is running.
-   *
+   * 
    * @return the instance of LocatorLauncher used to launcher a GemFire Locator in this VM.
    */
   public static LocatorLauncher getInstance() {
@@ -212,7 +212,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Gets the LocatorState for this process or null if this process was not launched using this VM's
    * LocatorLauncher reference.
-   *
+   * 
    * @return the LocatorState for this process or null.
    */
   public static LocatorState getLocatorState() {
@@ -224,7 +224,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * using a Builder. The Builder is used to configure a LocatorLauncher instance. The Builder can
    * process user input from the command-line or be used to properly construct an instance of the
    * LocatorLauncher programmatically using the API.
-   *
+   * 
    * @param builder an instance of LocatorLauncher.Builder for configuring and constructing an
    *        instance of the LocatorLauncher.
    * @see org.apache.geode.distributed.LocatorLauncher.Builder
@@ -281,7 +281,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the reference to the Locator object representing the running GemFire Locator.
-   *
+   * 
    * @return a reference to the Locator.
    */
   InternalLocator getLocator() {
@@ -291,7 +291,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Gets an identifier that uniquely identifies and represents the Locator associated with this
    * launcher.
-   *
+   * 
    * @return a String value identifier to uniquely identify the Locator and it's launcher.
    * @see #getBindAddressAsString()
    * @see #getPortAsString()
@@ -303,7 +303,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Get the Locator launcher command used to invoke the Locator.
-   *
+   * 
    * @return the Locator launcher command used to invoke the Locator.
    * @see org.apache.geode.distributed.LocatorLauncher.Command
    */
@@ -314,7 +314,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Determines whether the PID file is allowed to be overwritten when the Locator is started and a
    * PID file already exists in the Locator's specified working directory.
-   *
+   * 
    * @return boolean indicating if force has been enabled.
    */
   public boolean isForcing() {
@@ -326,7 +326,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * the standard Locator launcher commands will be used to affect the state of the Locator. A
    * launcher is said to be 'helping' if the user entered the "--help" option (switch) on the
    * command-line.
-   *
+   * 
    * @return a boolean value indicating if this launcher is used for displaying help information.
    * @see org.apache.geode.distributed.LocatorLauncher.Command
    */
@@ -337,7 +337,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Determines whether this launcher will redirect output to system logs when starting a new
    * Locator process.
-   *
+   * 
    * @return a boolean value indicating if this launcher will redirect output to system logs when
    *         starting a new Locator process
    */
@@ -348,21 +348,12 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Gets the IP address of the NIC to which the Locator has bound itself listening for client
    * requests.
-   *
+   * 
    * @return an InetAddress object representing the configured bind address for the Locator.
    * @see java.net.InetAddress
    */
   public InetAddress getBindAddress() {
-    try {
-      if (bindAddress != null) {
-        return bindAddress;
-      }
-      return SocketCreator.getLocalHost();
-    } catch (UnknownHostException handled) {
-      // Returning loopback implies the serverBindAddress was null and no IP address
-      // for localhost could be found
-      return InetAddress.getLoopbackAddress();
-    }
+    return this.bindAddress;
   }
 
   /**
@@ -370,10 +361,10 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * attempt is made to get the canonical hostname for IP address to which the Locator was bound for
    * accepting client requests. If the bind address is null or localhost is unknown, then a default
    * String value of "localhost/127.0.0.1" is returned.
-   *
+   * 
    * Note, this information is purely information and should not be used to re-construct state or
    * for other purposes.
-   *
+   * 
    * @return the hostname or IP address of the host running the Locator, based on the bind-address,
    *         or 'localhost/127.0.0.1' if the bind address is null and localhost is unknown.
    * @see java.net.InetAddress
@@ -389,7 +380,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
       return localhost.getCanonicalHostName();
     } catch (UnknownHostException handled) {
-      // Returning localhost/127.0.0.1 implies the bindAddress was null and no IP address for
+      // NOTE returning localhost/127.0.0.1 implies the bindAddress was null and no IP address for
       // localhost could be found
       return "localhost/127.0.0.1";
     }
@@ -397,7 +388,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the hostname that clients will use to lookup the running Locator.
-   *
+   * 
    * @return a String indicating the hostname used by clients to lookup the Locator.
    */
   public String getHostnameForClients() {
@@ -406,7 +397,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the name of the log file used to log information about this Locator.
-   *
+   * 
    * @return a String value indicating the name of this Locator's log file.
    */
   @Override
@@ -418,7 +409,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Gets the name of this member (this Locator) in the GemFire distributed system and determined by
    * the 'name' GemFire property.
-   *
+   * 
    * @return a String indicating the name of the member (this Locator) in the GemFire distributed
    *         system.
    */
@@ -430,7 +421,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Gets the user-specified process ID (PID) of the running Locator that LocatorLauncher uses to
    * issue status and stop commands to the Locator.
-   *
+   * 
    * @return an Integer value indicating the process ID (PID) of the running Locator.
    */
   @Override
@@ -440,7 +431,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the port number on which the Locator listens for client requests.
-   *
+   * 
    * @return an Integer value indicating the port number on which the Locator is listening for
    *         client requests.
    */
@@ -455,7 +446,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Gets the port number represented as a String value. If the port number is null, the the default
    * Locator port (10334) is returned;
-   *
+   * 
    * @return the port number as a String value.
    * @see #getPort()
    */
@@ -476,7 +467,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the name for a GemFire Locator.
-   *
+   * 
    * @return a String indicating the name for a GemFire Locator.
    */
   @Override
@@ -486,7 +477,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the working directory pathname in which the Locator will be run.
-   *
+   * 
    * @return a String value indicating the pathname of the Locator's working directory.
    */
   @Override
@@ -497,7 +488,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Displays help for the specified Locator launcher command to standard err. If the Locator
    * launcher command is unspecified, then usage information is displayed instead.
-   *
+   * 
    * @param command the Locator launcher command in which to display help information.
    * @see #usage()
    */
@@ -521,7 +512,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Displays usage information on the proper invocation of the LocatorLauncher from the
    * command-line to standard err.
-   *
+   * 
    * @see #help(org.apache.geode.distributed.LocatorLauncher.Command)
    */
   public void usage() {
@@ -538,7 +529,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * The Runnable method used to launch the Locator with the specified command. If 'start' has been
    * issued, then run will block as expected for the Locator to stop. The 'start' command is
    * implemented with a call to start() followed by a call to waitOnLocator().
-   *
+   * 
    * @see java.lang.Runnable
    * @see LocatorLauncher.Command
    * @see LocatorLauncher#start()
@@ -576,7 +567,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets a File reference with the path to the PID file for the Locator.
-   *
+   * 
    * @return a File reference to the path of the Locator's PID file.
    */
   protected File getLocatorPidFile() {
@@ -585,7 +576,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   /**
    * Determines whether a GemFire Locator can be started with this instance of LocatorLauncher.
-   *
+   * 
    * @return a boolean indicating whether a GemFire Locator can be started with this instance of
    *         LocatorLauncher, which is true if the LocatorLauncher has not already started a Locator
    *         or a Locator is not already running.
@@ -599,19 +590,19 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * Starts a Locator running on the specified port and bind address, as determined by getPort and
    * getBindAddress respectively, defaulting to 10334 and 'localhost' if not specified, with both
    * peer and server location enabled.
-   *
+   * 
    * 'start' is an asynchronous invocation of the Locator. As such, this method makes no guarantees
    * whether the Locator's location services (peer and server) are actually running before it
    * returns. The Locator's location-based services are initiated in separate, daemon Threads and
    * depends on the relative timing and scheduling of those Threads by the JVM. If the application
    * using this API wishes for the Locator to continue running after normal application processing
    * completes, then one must call <code>waitOnLocator</code>.
-   *
+   * 
    * Given the nature of start, the Locator's status will be in either 1 of 2 possible states. If
    * the 'request' to start the Locator proceeds without exception, the status will be 'STARTED'.
    * However, if any exception is encountered during the normal startup sequence, then a
    * RuntimeException is thrown and the status is set to 'STOPPED'.
-   *
+   * 
    * @return a LocatorState to reflect the state of the Locator after start.
    * @throws RuntimeException if the Locator failed to start for any reason.
    * @throws IllegalStateException if the Locator is already running.
@@ -643,7 +634,12 @@ public class LocatorLauncher extends AbstractLauncher<String> {
         assertPortAvailable(getBindAddress(), getPort());
 
         ProcessLauncherContext.set(isRedirectingOutput(), getOverriddenDefaults(),
-            statusMessage -> LocatorLauncher.this.statusMessage = statusMessage);
+            new StartupStatusListener() {
+              @Override
+              public void setStatus(final String statusMessage) {
+                LocatorLauncher.this.statusMessage = statusMessage;
+              }
+            });
 
         try {
           this.locator = InternalLocator.startLocator(getPort(), getLogFile(), null, null, null,
@@ -692,13 +688,14 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
   @Override
   protected Properties getDistributedSystemProperties() {
-    return super.getDistributedSystemProperties(getProperties());
+    Properties properties = super.getDistributedSystemProperties(getProperties());
+    return properties;
   }
 
   /**
    * A helper method to ensure the same sequence of actions are taken when the Locator fails to
    * start caused by some exception.
-   *
+   * 
    * @param cause the Throwable thrown during the startup or wait operation on the Locator.
    */
   private void failOnStart(final Throwable cause) {
@@ -726,7 +723,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Waits on the Locator to stop causing the calling Thread to join with the Locator's
    * location-based services Thread.
-   *
+   * 
    * @return the Locator's status once it stops.
    * @throws AssertionError if the Locator has not been started and the reference is null
    *         (assertions must be enabled for the error to be thrown).
@@ -765,15 +762,15 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * time until the timeout expires. If the request to determine the Locator's status is successful,
    * then the Locator is considered to be 'ONLINE'. Otherwise, the Locator is considered to be
    * unresponsive to the status request.
-   *
+   * 
    * However, this does not necessarily imply the Locator start was unsuccessful, only that a
    * response was not received in the given time period.
-   *
+   * 
    * Note, this method does not block or cause the Locator's location-based services (daemon
    * Threads) to continue running in anyway if the main application Thread terminates when running
    * the Locator in-process. If the caller wishes to start a Locator in an asynchronous manner
    * within the application process, then a call should be made to <code>waitOnLocator</code>.
-   *
+   * 
    * @param timeout a long value in time unit indicating when the period of time should expire in
    *        attempting to determine the Locator's status.
    * @param interval a long value in time unit for how frequent the requests should be sent to the
@@ -825,17 +822,17 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * MemberMXBean registered in the MBeanServer of the Locator's JVM, and invoking the 'status'
    * operation. The same behavior occurs if the caller specified the Locator's GemFire member name
    * or ID.
-   *
+   * 
    * However, if 'dir' or 'pid' were not specified, then determining the Locator's status defaults
    * to using the configured bind address and port. If the bind address or port was not specified
    * when using the Builder to construct a LocatorLauncher instance, then the defaults for both bind
    * address and port are used. In either case, an actual TCP/IP request is made to the Locator's
    * ServerSocket to ensure it is listening for client requests. This is true even when the
    * LocatorLauncher is used in-process by calling the API.
-   *
+   * 
    * If the conditions above hold, then the Locator is deemed to be 'ONLINE', otherwise, the Locator
    * is considered 'OFFLINE'.
-   *
+   * 
    * @return the Locator's state.
    * @see #start()
    * @see #stop()
@@ -871,7 +868,8 @@ public class LocatorLauncher extends AbstractLauncher<String> {
       return statusWithWorkingDirectory();
     }
     // attempt to get status using host and port (Note, bind address doubles as host when the
-    // launcher is used to get the Locator's status).
+    // launcher
+    // is used to get the Locator's status).
     else {
       debug("Getting Locator status using host (%1$s) and port (%2$s)%n", getBindAddressAsString(),
           getPortAsString());
@@ -919,8 +917,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
       LocatorStatusResponse response = statusLocator(getPort(), getBindAddress());
       return new LocatorState(this, Status.ONLINE, response);
     } catch (Exception handled) {
-      return createNoResponseState(handled, "Failed to connect to locator "
-          + getBindAddress().getCanonicalHostName() + "[" + getPort() + "]");
+      return createNoResponseState(handled, "Failed to connect to locator " + getId());
     }
   }
 
@@ -968,7 +965,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * Determines whether the Locator can be stopped in-process, such as when a Locator is embedded in
    * an application and the LocatorLauncher API is being used.
-   *
+   * 
    * @return a boolean indicating whether the Locator can be stopped in-process (the application's
    *         process with an embedded Locator).
    */
@@ -982,7 +979,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * LocatorLauncher class from the command-line or from within GemFire shell (Gfsh). In every
    * single case, stop sends a TCP/IP 'shutdown' request on the configured address/port to which the
    * Locator is bound and listening.
-   *
+   * 
    * If the "shutdown" request is successful, then the Locator will be 'STOPPED'. Otherwise, the
    * Locator is considered 'OFFLINE' since the actual state cannot be fully assessed (as in the
    * application process in which the Locator was hosted may still be running and the Locator object
@@ -990,7 +987,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * is particularly important in cases where the system resources (such as Sockets) may not have
    * been cleaned up yet. Therefore, by returning a status of 'OFFLINE', the value is meant to
    * reflect this in-deterministic state.
-   *
+   * 
    * @return a LocatorState indicating the state of the Locator after stop has been requested.
    * @see #start()
    * @see #status()
@@ -1013,6 +1010,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
       return stopWithPid();
     }
     // attempt to stop Locator using the working directory...
+    // else if (this.workingDirectorySpecified) {
     else if (getWorkingDirectory() != null) {
       return stopWithWorkingDirectory();
     } else {
@@ -1211,7 +1209,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
      * Constructor used to create and configure an instance of the Builder class with the specified
      * arguments, often passed from the command-line when launching an instance of this class from
      * the command-line using the Java launcher.
-     *
+     * 
      * @param args the array of arguments used to configure the Builder.
      */
     public Builder(final String... args) {
@@ -1220,7 +1218,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets an instance of the JOpt Simple OptionParser to parse the command-line arguments.
-     *
+     * 
      * @return an instance of the JOpt Simple OptionParser configured with the command-line options
      *         used by the Locator.
      */
@@ -1246,7 +1244,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
      * Parses an array of arguments to configure this Builder with the intent of constructing a
      * Locator launcher to invoke a Locator. This method is called to parse the arguments specified
      * by the user on the command-line.
-     *
+     * 
      * @param args the array of arguments used to configure this Builder and create an instance of
      *        LocatorLauncher.
      */
@@ -1300,7 +1298,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Iterates the list of arguments in search of the target Locator launcher command.
-     *
+     * 
      * @param args an array of arguments from which to search for the Locator launcher command.
      * @see org.apache.geode.distributed.LocatorLauncher.Command#valueOfName(String)
      * @see #parseArguments(String...)
@@ -1324,7 +1322,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
      * Iterates the list of arguments in search of the Locator's GemFire member name. If the
      * argument does not start with '-' or is not the name of a Locator launcher command, then the
      * value is presumed to be the member name for the Locator in GemFire.
-     *
+     * 
      * @param args the array of arguments from which to search for the Locator's member name in
      *        GemFire.
      * @see org.apache.geode.distributed.LocatorLauncher.Command#isCommand(String)
@@ -1343,7 +1341,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the Locator launcher command used during the invocation of the LocatorLauncher.
-     *
+     * 
      * @return the Locator launcher command used to invoke (run) the LocatorLauncher class.
      * @see #setCommand(org.apache.geode.distributed.LocatorLauncher.Command)
      * @see LocatorLauncher.Command
@@ -1354,7 +1352,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Sets the Locator launcher command used during the invocation of the LocatorLauncher
-     *
+     * 
      * @param command the targeted Locator launcher command used during the invocation (run) of
      *        LocatorLauncher.
      * @return this Builder instance.
@@ -1368,7 +1366,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether the new instance of the LocatorLauncher will be set to debug mode.
-     *
+     * 
      * @return a boolean value indicating whether debug mode is enabled or disabled.
      * @see #setDebug(Boolean)
      */
@@ -1378,7 +1376,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Sets whether the new instance of the LocatorLauncher will be set to debug mode.
-     *
+     * 
      * @param debug a boolean value indicating whether debug mode is to be enabled or disabled.
      * @return this Builder instance.
      * @see #getDebug()
@@ -1428,7 +1426,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Gets the boolean value used by the Locator to determine if it should overwrite the PID file
      * if it already exists.
-     *
+     * 
      * @return the boolean value specifying whether or not to overwrite the PID file if it already
      *         exists.
      * @see #setForce(Boolean)
@@ -1440,7 +1438,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Sets the boolean value used by the Locator to determine if it should overwrite the PID file
      * if it already exists.
-     *
+     * 
      * @param force a boolean value indicating whether to overwrite the PID file when it already
      *        exists.
      * @return this Builder instance.
@@ -1455,7 +1453,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Determines whether the new instance of LocatorLauncher will be used to output help
      * information for either a specific command, or for using LocatorLauncher in general.
-     *
+     * 
      * @return a boolean value indicating whether help will be output during the invocation of
      *         LocatorLauncher.
      * @see #setHelp(Boolean)
@@ -1466,7 +1464,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether help has been enabled.
-     *
+     * 
      * @return a boolean indicating if help was enabled.
      */
     private boolean isHelping() {
@@ -1476,7 +1474,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Sets whether the new instance of LocatorLauncher will be used to output help information for
      * either a specific command, or for using LocatorLauncher in general.
-     *
+     * 
      * @param help a boolean indicating whether help information is to be displayed during
      *        invocation of LocatorLauncher.
      * @return this Builder instance.
@@ -1494,7 +1492,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the IP address to which the Locator has bound itself listening for client requests.
-     *
+     * 
      * @return an InetAddress with the IP address or hostname on which the Locator is bound and
      *         listening.
      * @see #setBindAddress(String)
@@ -1507,7 +1505,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Sets the IP address as an java.net.InetAddress to which the Locator has bound itself
      * listening for client requests.
-     *
+     * 
      * @param bindAddress the InetAddress with the IP address or hostname on which the Locator is
      *        bound and listening.
      * @return this Builder instance.
@@ -1541,7 +1539,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the hostname used by clients to lookup the Locator.
-     *
+     * 
      * @return a String indicating the hostname Locator binding used in client lookups.
      * @see #setHostnameForClients(String)
      */
@@ -1551,7 +1549,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Sets the hostname used by clients to lookup the Locator.
-     *
+     * 
      * @param hostnameForClients a String indicating the hostname Locator binding used in client
      *        lookups.
      * @return this Builder instance.
@@ -1572,7 +1570,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the member name of this Locator in GemFire.
-     *
+     * 
      * @return a String indicating the member name of this Locator in GemFire.
      * @see #setMemberName(String)
      */
@@ -1582,7 +1580,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Sets the member name of the Locator in GemFire.
-     *
+     * 
      * @param memberName a String indicating the member name of this Locator in GemFire.
      * @return this Builder instance.
      * @throws IllegalArgumentException if the member name is invalid.
@@ -1602,7 +1600,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
      * Gets the process ID (PID) of the running Locator indicated by the user as an argument to the
      * LocatorLauncher. This PID is used by the Locator launcher to determine the Locator's status,
      * or invoke shutdown on the Locator.
-     *
+     * 
      * @return a user specified Integer value indicating the process ID of the running Locator.
      * @see #setPid(Integer)
      */
@@ -1614,7 +1612,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
      * Sets the process ID (PID) of the running Locator indicated by the user as an argument to the
      * LocatorLauncher. This PID will be used by the Locator launcher to determine the Locator's
      * status, or invoke shutdown on the Locator.
-     *
+     * 
      * @param pid a user specified Integer value indicating the process ID of the running Locator.
      * @return this Builder instance.
      * @throws IllegalArgumentException if the process ID (PID) is not valid (greater than zero if
@@ -1637,7 +1635,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Gets the port number used by the Locator to listen for client requests. If the port was not
      * specified, then the default Locator port (10334) is returned.
-     *
+     * 
      * @return the specified Locator port or the default port if unspecified.
      * @see #setPort(Integer)
      */
@@ -1648,7 +1646,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Sets the port number used by the Locator to listen for client requests. The port number must
      * be between 1 and 65535 inclusive.
-     *
+     * 
      * @param port an Integer value indicating the port used by the Locator to listen for client
      *        requests.
      * @return this Builder instance.
@@ -1671,9 +1669,10 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Determines whether the new instance of LocatorLauncher will redirect output to system logs
      * when starting a Locator.
-     *
+     * 
      * @return a boolean value indicating if output will be redirected to system logs when starting
      *         a Locator
+     * 
      * @see #setRedirectOutput(Boolean)
      */
     public Boolean getRedirectOutput() {
@@ -1682,7 +1681,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether redirecting of output has been enabled.
-     *
+     * 
      * @return a boolean indicating if redirecting of output was enabled.
      */
     private boolean isRedirectingOutput() {
@@ -1692,7 +1691,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Sets whether the new instance of LocatorLauncher will redirect output to system logs when
      * starting a Locator.
-     *
+     * 
      * @param redirectOutput a boolean value indicating if output will be redirected to system logs
      *        when starting a Locator.
      * @return this Builder instance.
@@ -1710,7 +1709,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Gets the working directory pathname in which the Locator will be ran. If the directory is
      * unspecified, then working directory defaults to the current directory.
-     *
+     * 
      * @return a String indicating the working directory pathname.
      * @see #setWorkingDirectory(String)
      */
@@ -1723,7 +1722,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
      * Sets the working directory in which the Locator will be ran. This also the directory in which
      * all Locator files (such as log and license files) will be written. If the directory is
      * unspecified, then the working directory defaults to the current directory.
-     *
+     * 
      * @param workingDirectory a String indicating the pathname of the directory in which the
      *        Locator will be ran.
      * @return this Builder instance.
@@ -1765,7 +1764,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
      * specified the pathname to the gemfire.properties file before validate is called. It is then
      * assumed, but not further validated, that the user has specified the Locator's member name in
      * the properties file.
-     *
+     * 
      * @throws IllegalStateException if the Builder is not properly configured.
      */
     protected void validate() {
@@ -1779,7 +1778,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Validates the arguments passed to the Builder when the 'start' command has been issued.
-     *
+     * 
      * @see org.apache.geode.distributed.LocatorLauncher.Command#START
      */
     protected void validateOnStart() {
@@ -1803,7 +1802,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Validates the arguments passed to the Builder when the 'status' command has been issued.
-     *
+     * 
      * @see org.apache.geode.distributed.LocatorLauncher.Command#STATUS
      */
     protected void validateOnStatus() {
@@ -1813,7 +1812,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Validates the arguments passed to the Builder when the 'stop' command has been issued.
-     *
+     * 
      * @see org.apache.geode.distributed.LocatorLauncher.Command#STOP
      */
     protected void validateOnStop() {
@@ -1824,7 +1823,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Validates the Builder configuration settings and then constructs an instance of the
      * LocatorLauncher class to invoke operations on a GemFire Locator.
-     *
+     * 
      * @return a newly constructed instance of LocatorLauncher configured with this Builder.
      * @see #validate()
      * @see org.apache.geode.distributed.LocatorLauncher
@@ -1838,7 +1837,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
   /**
    * An enumerated type representing valid commands to the Locator launcher.
    */
-  public enum Command {
+  public static enum Command {
     START("start", "bind-address", "hostname-for-clients", "port", "force", "debug", "help"),
     STATUS("status", "bind-address", "port", "member", "pid", "dir", "debug", "help"),
     STOP("stop", "member", "pid", "dir", "debug", "help"),
@@ -1853,13 +1852,13 @@ public class LocatorLauncher extends AbstractLauncher<String> {
       assert isNotBlank(name) : "The name of the locator launcher command must be specified!";
       this.name = name;
       this.options = (options != null ? Collections.unmodifiableList(Arrays.asList(options))
-          : Collections.emptyList());
+          : Collections.<String>emptyList());
     }
 
     /**
      * Determines whether the specified name refers to a valid Locator launcher command, as defined
      * by this enumerated type.
-     *
+     * 
      * @param name a String value indicating the potential name of a Locator launcher command.
      * @return a boolean indicating whether the specified name for a Locator launcher command is
      *         valid.
@@ -1871,7 +1870,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Determines whether the given Locator launcher command has been properly specified. The
      * command is deemed unspecified if the reference is null or the Command is UNSPECIFIED.
-     *
+     * 
      * @param command the Locator launcher command.
      * @return a boolean value indicating whether the Locator launcher command is unspecified.
      * @see Command#UNSPECIFIED
@@ -1883,7 +1882,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Looks up a Locator launcher command by name. The equality comparison on name is
      * case-insensitive.
-     *
+     * 
      * @param name a String value indicating the name of the Locator launcher command.
      * @return an enumerated type representing the command name or null if the no such command with
      *         the specified name exists.
@@ -1900,7 +1899,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the name of the Locator launcher command.
-     *
+     * 
      * @return a String value indicating the name of the Locator launcher command.
      */
     public String getName() {
@@ -1910,7 +1909,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
     /**
      * Gets a set of valid options that can be used with the Locator launcher command when used from
      * the command-line.
-     *
+     * 
      * @return a Set of Strings indicating the names of the options available to the Locator
      *         launcher command.
      */
@@ -1920,7 +1919,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether this Locator launcher command has the specified command-line option.
-     *
+     * 
      * @param option a String indicating the name of the command-line option to this command.
      * @return a boolean value indicating whether this command has the specified named command-line
      *         option.
@@ -1931,7 +1930,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Convenience method for determining whether this is the UNSPECIFIED Locator launcher command.
-     *
+     * 
      * @return a boolean indicating if this command is UNSPECIFIED.
      * @see #UNSPECIFIED
      */
@@ -1941,7 +1940,7 @@ public class LocatorLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the String representation of this Locator launcher command.
-     *
+     * 
      * @return a String value representing this Locator launcher command.
      */
     @Override
@@ -1954,14 +1953,14 @@ public class LocatorLauncher extends AbstractLauncher<String> {
    * The LocatorState is an immutable type representing the state of the specified Locator at any
    * given moment in time. The state of the Locator is assessed at the exact moment an instance of
    * this class is constructed.
-   *
+   * 
    * @see org.apache.geode.distributed.AbstractLauncher.ServiceState
    */
   public static class LocatorState extends ServiceState<String> {
 
     /**
      * Unmarshals a LocatorState instance from the JSON String.
-     *
+     * 
      * @return a LocatorState value unmarshalled from the JSON String.
      */
     public static LocatorState fromJson(final String json) {
@@ -2015,41 +2014,26 @@ public class LocatorLauncher extends AbstractLauncher<String> {
       this(status, // status
           errorMessage, // statusMessage
           System.currentTimeMillis(), // timestamp
-          getLocatorLocation(launcher), // locatorLocation
+          null, // locatorLocation
           null, // pid
           0L, // uptime
           launcher.getWorkingDirectory(), // workingDirectory
-          ManagementFactory.getRuntimeMXBean().getInputArguments(), // jvmArguments
+          Collections.<String>emptyList(), // jvmArguments
           null, // classpath
           GemFireVersion.getGemFireVersion(), // gemfireVersion
-          System.getProperty("java.version"), // javaVersion
+          null, // javaVersion
           null, // logFile
-          getBindAddress(launcher).getCanonicalHostName(), // host
-          launcher.getPortAsString(), // port
+          null, // host
+          null, // port
           null);// memberName
     }
 
-    /*
-     * Guards against throwing NPEs due to incorrect or missing host information while constructing
-     * error states
-     */
-    private static String getLocatorLocation(LocatorLauncher launcher) {
-      if (launcher.getPort() == null) {
-        return launcher.getId();
-      }
-      if (launcher.getBindAddress() == null) {
-        return HostUtils.getLocatorId(HostUtils.getLocalHost(), launcher.getPort());
-      }
-      return HostUtils.getLocatorId(launcher.getBindAddress().getCanonicalHostName(),
-          launcher.getPort());
-    }
-
     private static String getBindAddressAsString(LocatorLauncher launcher) {
       if (InternalLocator.hasLocator()) {
         final InternalLocator locator = InternalLocator.getLocator();
         final InetAddress bindAddress = locator.getBindAddress();
         if (bindAddress != null) {
-          if (isNotBlank(bindAddress.getHostAddress())) {
+          if (isBlank(bindAddress.getHostAddress())) {
             return bindAddress.getHostAddress();
           }
         }
@@ -2057,17 +2041,6 @@ public class LocatorLauncher extends AbstractLauncher<String> {
       return launcher.getBindAddressAsString();
     }
 
-    private static InetAddress getBindAddress(LocatorLauncher launcher) {
-      if (InternalLocator.hasLocator()) {
-        final InternalLocator locator = InternalLocator.getLocator();
-        final InetAddress bindAddress = locator.getBindAddress();
-        if (bindAddress != null) {
-          return bindAddress;
-        }
-      }
-      return launcher.getBindAddress();
-    }
-
     private static String getLogFileCanonicalPath(LocatorLauncher launcher) {
       if (InternalLocator.hasLocator()) {
         final InternalLocator locator = InternalLocator.getLocator();
@@ -2076,7 +2049,8 @@ public class LocatorLauncher extends AbstractLauncher<String> {
         if (logFile != null && logFile.isFile()) {
           final String logFileCanonicalPath = tryGetCanonicalPathElseGetAbsolutePath(logFile);
           if (isNotBlank(logFileCanonicalPath)) { // this is probably not need but a
-            // safe check none-the-less.
+                                                  // safe
+            // check none-the-less.
             return logFileCanonicalPath;
           }
         }

http://git-wip-us.apache.org/repos/asf/geode/blob/4ac5e65f/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java b/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java
index a5548d1..ae64691 100755
--- a/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java
+++ b/geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java
@@ -30,7 +30,6 @@ import static org.apache.geode.internal.util.IOUtils.tryGetCanonicalPathElseGetA
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.io.UncheckedIOException;
 import java.lang.management.ManagementFactory;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
@@ -82,13 +81,13 @@ import org.apache.geode.internal.process.ProcessControllerFactory;
 import org.apache.geode.internal.process.ProcessControllerParameters;
 import org.apache.geode.internal.process.ProcessLauncherContext;
 import org.apache.geode.internal.process.ProcessType;
+import org.apache.geode.internal.process.StartupStatusListener;
 import org.apache.geode.internal.process.UnableToControlProcessException;
 import org.apache.geode.lang.AttachAPINotFoundException;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.json.GfJsonArray;
 import org.apache.geode.management.internal.cli.json.GfJsonException;
 import org.apache.geode.management.internal.cli.json.GfJsonObject;
-import org.apache.geode.management.internal.cli.util.HostUtils;
 import org.apache.geode.pdx.PdxSerializer;
 import org.apache.geode.security.AuthenticationRequiredException;
 import org.apache.geode.security.GemFireSecurityException;
@@ -96,7 +95,7 @@ import org.apache.geode.security.GemFireSecurityException;
 /**
  * The ServerLauncher class is a launcher class with main method to start a GemFire Server (implying
  * a GemFire Cache Server process).
- *
+ * 
  * @see org.apache.geode.distributed.AbstractLauncher
  * @see org.apache.geode.distributed.LocatorLauncher
  * @since GemFire 7.0
@@ -218,7 +217,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Launches a GemFire Server from the command-line configured with the given arguments.
-   *
+   * 
    * @param args the command-line arguments used to configure the GemFire Server at runtime.
    */
   public static void main(final String... args) {
@@ -238,7 +237,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * Gets the instance of the ServerLauncher used to launch the GemFire Cache Server, or null if
    * this VM does not have an instance of ServerLauncher indicating no GemFire Cache Server is
    * running.
-   *
+   * 
    * @return the instance of ServerLauncher used to launcher a GemFire Cache Server in this VM.
    */
   public static ServerLauncher getInstance() {
@@ -248,7 +247,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Gets the ServerState for this process or null if this process was not launched using this VM's
    * ServerLauncher reference .
-   *
+   * 
    * @return the ServerState for this process or null.
    */
   public static ServerState getServerState() {
@@ -260,7 +259,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * using a Builder. The Builder is used to configure a ServerLauncher instance. The Builder can
    * process user input from the command-line or be used programmatically to properly construct an
    * instance of the ServerLauncher using the API.
-   *
+   * 
    * @param builder an instance of ServerLauncher.Builder for configuring and constructing an
    *        instance of the ServerLauncher.
    * @see org.apache.geode.distributed.ServerLauncher.Builder
@@ -319,7 +318,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets a reference to the Cache that was created when the GemFire Server was started.
-   *
+   * 
    * @return a reference to the Cache created by the GemFire Server start operation.
    * @see org.apache.geode.cache.Cache
    */
@@ -352,7 +351,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Gets an identifier that uniquely identifies and represents the Server associated with this
    * launcher.
-   *
+   * 
    * @return a String value identifier to uniquely identify the Server and it's launcher.
    * @see #getServerBindAddressAsString()
    * @see #getServerPortAsString()
@@ -370,7 +369,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Get the Server launcher command used to invoke the Server.
-   *
+   * 
    * @return the Server launcher command used to invoke the Server.
    * @see org.apache.geode.distributed.ServerLauncher.Command
    */
@@ -381,7 +380,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Determines whether buckets should be assigned to partitioned regions in the cache upon Server
    * start.
-   *
+   * 
    * @return a boolean indicating if buckets should be assigned upon Server start.
    */
   public boolean isAssignBuckets() {
@@ -390,7 +389,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Determines whether a default cache server will be added when the GemFire Server comes online.
-   *
+   * 
    * @return a boolean value indicating whether to add a default cache server.
    */
   public boolean isDisableDefaultServer() {
@@ -400,7 +399,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Determines whether the PID file is allowed to be overwritten when the Server is started and a
    * PID file already exists in the Server's specified working directory.
-   *
+   * 
    * @return boolean indicating if force has been enabled.
    */
   public boolean isForcing() {
@@ -412,7 +411,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * the standard Server launcher commands will be used to affect the state of the Server. A
    * launcher is said to be 'helping' if the user entered the "--help" option (switch) on the
    * command-line.
-   *
+   * 
    * @return a boolean value indicating if this launcher is used for displaying help information.
    * @see org.apache.geode.distributed.ServerLauncher.Command
    */
@@ -423,7 +422,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Determines whether a rebalance operation on the cache will occur upon starting the GemFire
    * server using this launcher.
-   *
+   * 
    * @return a boolean indicating if the cache will be rebalance when the GemFire server starts.
    */
   public boolean isRebalancing() {
@@ -433,7 +432,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Determines whether this launcher will redirect output to system logs when starting a new
    * Locator process.
-   *
+   * 
    * @return a boolean value indicating if this launcher will redirect output to system logs when
    *         starting a new Locator process
    */
@@ -443,7 +442,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the name of the log file used to log information about this Server.
-   *
+   * 
    * @return a String value indicating the name of this Server's log file.
    */
   @Override
@@ -454,7 +453,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Gets the name of this member (this Server) in the GemFire distributed system as determined by
    * the 'name' GemFire property.
-   *
+   * 
    * @return a String indicating the name of the member (this Server) in the GemFire distributed
    *         system.
    */
@@ -466,7 +465,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Gets the user-specified process ID (PID) of the running Server that ServerLauncher uses to
    * issue status and stop commands to the Server.
-   *
+   * 
    * @return an Integer value indicating the process ID (PID) of the running Server.
    */
   @Override
@@ -490,22 +489,12 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * connections. This property should not be confused with 'bindAddress' ServerLauncher property,
    * which is the port for binding the Server's ServerSocket used in distribution and messaging
    * between the peers of the GemFire distributed system.
-   *
+   * 
    * @return an InetAddress indicating the IP address that the Server is bound to listening for and
    *         accepting cache client connections in a client/server topology.
    */
   public InetAddress getServerBindAddress() {
-    if (serverBindAddress != null) {
-      return this.serverBindAddress;
-    }
-
-    try {
-      return SocketCreator.getLocalHost();
-    } catch (UnknownHostException handled) {
-      // Returning loopback implies the serverBindAddress was null and no IP address
-      // for localhost could be found
-      return InetAddress.getLoopbackAddress();
-    }
+    return this.serverBindAddress;
   }
 
   /**
@@ -513,10 +502,10 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * attempt is made to get the canonical hostname for IP address to which the Server was bound for
    * accepting client requests. If the server bind address is null or localhost is unknown, then a
    * default String value of "localhost/127.0.0.1" is returned.
-   *
+   * 
    * Note, this information is purely information and should not be used to re-construct state or
    * for other purposes.
-   *
+   * 
    * @return the hostname or IP address of the host running the Server, based on the bind-address,
    *         or 'localhost/127.0.0.1' if the bind address is null and localhost is unknown.
    * @see java.net.InetAddress
@@ -532,7 +521,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
       return localhost.getCanonicalHostName();
     } catch (UnknownHostException handled) {
-      // Returning localhost/127.0.0.1 implies the serverBindAddress was null and no IP address
+      // NOTE returning localhost/127.0.0.1 implies the serverBindAddress was null and no IP address
       // for localhost could be found
       return "localhost/127.0.0.1";
     }
@@ -543,7 +532,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * should not be confused with the 'port' ServerLauncher property, which is used by the Server to
    * set the 'tcp-port' distribution config property and is used by the ServerSocket for peer
    * distribution and messaging.
-   *
+   * 
    * @return an Integer value indicating the port the Server is listening on for cache client
    *         connections in the client/server topology.
    */
@@ -554,7 +543,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Gets the server port on which the Server is listening for client requests represented as a
    * String value.
-   *
+   * 
    * @return a String representing the server port on which the Server is listening for client
    *         requests.
    * @see #getServerPort()
@@ -565,7 +554,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the name for a GemFire Server.
-   *
+   * 
    * @return a String indicating the name for a GemFire Server.
    */
   @Override
@@ -577,7 +566,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * Gets the location of the Spring XML configuration meta-data file used to bootstrap, configure
    * and initialize the GemFire Server on start.
    * <p>
-   *
+   * 
    * @return a String indicating the location of the Spring XML configuration file.
    * @see org.apache.geode.distributed.ServerLauncher.Builder#getSpringXmlLocation()
    */
@@ -589,7 +578,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * Determines whether this GemFire Server was configured and initialized with Spring configuration
    * meta-data.
    * <p>
-   *
+   * 
    * @return a boolean value indicating whether this GemFire Server was configured with Spring
    *         configuration meta-data.
    */
@@ -599,7 +588,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets the working directory pathname in which the Server will be run.
-   *
+   * 
    * @return a String value indicating the pathname of the Server's working directory.
    */
   @Override
@@ -650,7 +639,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Displays help for the specified Server launcher command to standard err. If the Server launcher
    * command is unspecified, then usage information is displayed instead.
-   *
+   * 
    * @param command the Server launcher command in which to display help information.
    * @see #usage()
    */
@@ -674,7 +663,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Displays usage information on the proper invocation of the ServerLauncher from the command-line
    * to standard err.
-   *
+   * 
    * @see #help(org.apache.geode.distributed.ServerLauncher.Command)
    */
   public void usage() {
@@ -691,7 +680,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * A Runnable method used to invoke the GemFire server (cache server) with the specified command.
    * From run, a user can invoke 'start', 'status', 'stop' and 'version'. Note, that 'version' is
    * also a command-line option, but can be treated as a "command" as well.
-   *
+   * 
    * @see java.lang.Runnable
    */
   @Override
@@ -721,7 +710,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Gets a File reference with the path to the PID file for the Server.
-   *
+   * 
    * @return a File reference to the path of the Server's PID file.
    */
   protected File getServerPidFile() {
@@ -762,9 +751,12 @@ public class ServerLauncher extends AbstractLauncher<String> {
         SystemFailure.setExitOK(true);
 
         ProcessLauncherContext.set(isRedirectingOutput(), getOverriddenDefaults(),
-            (String statusMessage) -> {
-              debug("Callback setStatus(String) called with message (%1$s)...", statusMessage);
-              ServerLauncher.this.statusMessage = statusMessage;
+            new StartupStatusListener() {
+              @Override
+              public void setStatus(final String statusMessage) {
+                debug("Callback setStatus(String) called with message (%1$s)...", statusMessage);
+                ServerLauncher.this.statusMessage = statusMessage;
+              }
             });
 
         try {
@@ -857,7 +849,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * A helper method to ensure the same sequence of actions are taken when the Server fails to start
    * caused by some exception.
-   *
+   * 
    * @param cause the Throwable thrown during the startup operation on the Server.
    */
   private void failOnStart(final Throwable cause) {
@@ -877,7 +869,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Determines whether the specified Cache has any CacheServers.
-   *
+   * 
    * @param cache the Cache to check for existing CacheServers.
    * @return a boolean value indicating if any CacheServers were added to the Cache.
    */
@@ -887,7 +879,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Determines whether to continue waiting and keep the GemFire non-Server data member running.
-   *
+   * 
    * @param cache the Cache associated with this GemFire (non-Server) data member.
    * @return a boolean value indicating whether the GemFire data member should continue running, as
    *         determined by the running flag and a connection to the distributed system (GemFire
@@ -930,7 +922,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * by the absence of specifying the --disable-default-server command-line option (switch). In
    * addition, a default cache server is started only if no cache servers have been added to the
    * Cache by way of cache.xml.
-   *
+   * 
    * @param cache the reference to the Cache to check for any existing cache servers.
    * @return a boolean indicating whether a default server should be added to the Cache.
    * @see #isDisableDefaultServer()
@@ -943,7 +935,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * If the default server (cache server) has not been disabled and no prior cache servers were
    * added to the cache, then this method will add a cache server to the Cache and start the server
    * Thread on the specified bind address and port.
-   *
+   * 
    * @param cache the Cache to which the server will be added.
    * @throws IOException if the Cache server fails to start due to IO error.
    */
@@ -990,7 +982,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Causes a rebalance operation to occur on the given Cache.
-   *
+   * 
    * @param cache the reference to the Cache to rebalance.
    * @see org.apache.geode.cache.control.ResourceManager#createRebalanceFactory()
    */
@@ -1005,7 +997,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * using the --assign-buckets command-line option (switch) at the command-line as well as whether
    * the option is technically allowed. The option is only allowed if the instance of the Cache is
    * the internal GemFireCacheImpl at present.
-   *
+   * 
    * @param cache the Cache reference to check for instance type.
    * @return a boolean indicating if bucket assignment is both enabled and allowed.
    * @see #isAssignBuckets()
@@ -1016,7 +1008,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Assigns buckets to individual Partitioned Regions of the Cache.
-   *
+   * 
    * @param cache the Cache who's Partitioned Regions are accessed to assign buckets to.
    * @see PartitionRegionHelper#assignBucketsToPartitions(org.apache.geode.cache.Region)
    */
@@ -1030,7 +1022,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
   /**
    * Determines whether the Server is the process of starting or is already running.
-   *
+   * 
    * @return a boolean indicating if the Server is starting or is already running.
    */
   protected boolean isStartingOrRunning() {
@@ -1059,8 +1051,10 @@ public class ServerLauncher extends AbstractLauncher<String> {
       debug("Getting Server status using working directory (%1$s)%n", getWorkingDirectory());
       return statusWithWorkingDirectory();
     }
-    debug("This ServerLauncher was not the instance used to launch the GemFire Cache Server, and "
-        + "neither PID nor working directory were specified; the Server's state is unknown.%n");
+
+    debug(
+        "This ServerLauncher was not the instance used to launch the GemFire Cache Server, and neither PID "
+            .concat("nor working directory were specified; the Server's state is unknown.%n"));
 
     return new ServerState(this, Status.NOT_RESPONDING);
   }
@@ -1137,7 +1131,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
   /**
    * Determines whether the Server can be stopped in-process, such as when a Server is embedded in
    * an application and the ServerLauncher API is being used.
-   *
+   * 
    * @return a boolean indicating whether the Server can be stopped in-process (the application's
    *         process with an embedded Server).
    */
@@ -1395,7 +1389,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * Constructor used to create and configure an instance of the Builder class with the specified
      * arguments, passed in from the command-line when launching an instance of this class from the
      * command-line using the Java launcher.
-     *
+     * 
      * @param args the array of arguments used to configure the Builder.
      * @see #parseArguments(String...)
      */
@@ -1406,7 +1400,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Gets an instance of the JOptSimple OptionParser to parse the command-line arguments for
      * Server.
-     *
+     * 
      * @return an instance of the JOptSimple OptionParser configured with the command-line options
      *         used by the Server.
      */
@@ -1454,7 +1448,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * Parses the list of arguments to configure this Builder with the intent of constructing a
      * Server launcher to invoke a Cache Server. This method is called to parse the arguments
      * specified by the user on the command-line.
-     *
+     * 
      * @param args the array of arguments used to configure this Builder and create an instance of
      *        ServerLauncher.
      */
@@ -1599,7 +1593,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Iterates the list of arguments in search of the target Server launcher command.
-     *
+     * 
      * @param args an array of arguments from which to search for the Server launcher command.
      * @see org.apache.geode.distributed.ServerLauncher.Command#valueOfName(String)
      * @see #parseArguments(String...)
@@ -1620,7 +1614,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * Iterates the list of arguments in search of the Server's GemFire member name. If the argument
      * does not start with '-' or is not the name of a Server launcher command, then the value is
      * presumed to be the member name for the Server in GemFire.
-     *
+     * 
      * @param args the array of arguments from which to search for the Server's member name in
      *        GemFire.
      * @see org.apache.geode.distributed.ServerLauncher.Command#isCommand(String)
@@ -1648,7 +1642,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the Server launcher command used during the invocation of the ServerLauncher.
-     *
+     * 
      * @return the Server launcher command used to invoke (run) the ServerLauncher class.
      * @see #setCommand(org.apache.geode.distributed.ServerLauncher.Command)
      * @see org.apache.geode.distributed.ServerLauncher.Command
@@ -1659,7 +1653,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Sets the Sever launcher command used during the invocation of the ServerLauncher
-     *
+     * 
      * @param command the targeted Server launcher command used during the invocation (run) of
      *        ServerLauncher.
      * @return this Builder instance.
@@ -1674,7 +1668,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Determines whether buckets should be assigned to partitioned regions in the cache upon Server
      * start.
-     *
+     * 
      * @return a boolean indicating if buckets should be assigned upon Server start.
      * @see #setAssignBuckets(Boolean)
      */
@@ -1685,7 +1679,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Sets whether buckets should be assigned to partitioned regions in the cache upon Server
      * start.
-     *
+     * 
      * @param assignBuckets a boolean indicating if buckets should be assigned upon Server start.
      * @return this Builder instance.
      * @see #getAssignBuckets()
@@ -1708,7 +1702,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether the new instance of the ServerLauncher will be set to debug mode.
-     *
+     * 
      * @return a boolean value indicating whether debug mode is enabled or disabled.
      * @see #setDebug(Boolean)
      */
@@ -1718,7 +1712,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Sets whether the new instance of the ServerLauncher will be set to debug mode.
-     *
+     * 
      * @param debug a boolean value indicating whether debug mode is to be enabled or disabled.
      * @return this Builder instance.
      * @see #getDebug()
@@ -1756,7 +1750,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether a default cache server will be added when the Geode Server comes online.
-     *
+     * 
      * @return a boolean value indicating whether to add a default cache server.
      * @see #setDisableDefaultServer(Boolean)
      */
@@ -1767,7 +1761,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Sets a boolean value indicating whether to add a default cache when the GemFire Server comes
      * online.
-     *
+     * 
      * @param disableDefaultServer a boolean value indicating whether to add a default cache server.
      * @return this Builder instance.
      * @see #getDisableDefaultServer()
@@ -1791,7 +1785,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Gets the boolean value used by the Server to determine if it should overwrite the PID file if
      * it already exists.
-     *
+     * 
      * @return the boolean value specifying whether or not to overwrite the PID file if it already
      *         exists.
      * @see #setForce(Boolean)
@@ -1803,7 +1797,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Sets the boolean value used by the Server to determine if it should overwrite the PID file if
      * it already exists.
-     *
+     * 
      * @param force a boolean value indicating whether to overwrite the PID file when it already
      *        exists.
      * @return this Builder instance.
@@ -1817,7 +1811,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Determines whether the new instance of the ServerLauncher will be used to output help
      * information for either a specific command, or for using ServerLauncher in general.
-     *
+     * 
      * @return a boolean value indicating whether help will be output during the invocation of the
      *         ServerLauncher.
      * @see #setHelp(Boolean)
@@ -1828,7 +1822,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether help has been enabled.
-     *
+     * 
      * @return a boolean indicating if help was enabled.
      */
     protected boolean isHelping() {
@@ -1838,7 +1832,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Sets whether the new instance of ServerLauncher will be used to output help information for
      * either a specific command, or for using ServerLauncher in general.
-     *
+     * 
      * @param help a boolean indicating whether help information is to be displayed during
      *        invocation of ServerLauncher.
      * @return this Builder instance.
@@ -1852,7 +1846,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Determines whether a rebalance operation on the cache will occur upon starting the GemFire
      * server.
-     *
+     * 
      * @return a boolean indicating if the cache will be rebalance when the GemFire server starts.
      * @see #setRebalance(Boolean)
      */
@@ -1863,7 +1857,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Set a boolean value indicating whether a rebalance operation on the cache should occur upon
      * starting the GemFire server.
-     *
+     * 
      * @param rebalance a boolean indicating if the cache will be rebalanced when the GemFire server
      *        starts.
      * @return this Builder instance.
@@ -1876,7 +1870,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the member name of this Server in GemFire.
-     *
+     * 
      * @return a String indicating the member name of this Server in GemFire.
      * @see #setMemberName(String)
      */
@@ -1886,7 +1880,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Sets the member name of the Server in GemFire.
-     *
+     * 
      * @param memberName a String indicating the member name of this Server in GemFire.
      * @return this Builder instance.
      * @throws IllegalArgumentException if the member name is invalid.
@@ -1906,7 +1900,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * Gets the process ID (PID) of the running Server indicated by the user as an argument to the
      * ServerLauncher. This PID is used by the Server launcher to determine the Server's status, or
      * invoke shutdown on the Server.
-     *
+     * 
      * @return a user specified Integer value indicating the process ID of the running Server.
      * @see #setPid(Integer)
      */
@@ -1918,7 +1912,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * Sets the process ID (PID) of the running Server indicated by the user as an argument to the
      * ServerLauncher. This PID will be used by the Server launcher to determine the Server's
      * status, or invoke shutdown on the Server.
-     *
+     * 
      * @param pid a user specified Integer value indicating the process ID of the running Server.
      * @return this Builder instance.
      * @throws IllegalArgumentException if the process ID (PID) is not valid (greater than zero if
@@ -1937,9 +1931,10 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Determines whether the new instance of ServerLauncher will redirect output to system logs
      * when starting a Server.
-     *
+     * 
      * @return a boolean value indicating if output will be redirected to system logs when starting
      *         a Server
+     * 
      * @see #setRedirectOutput(Boolean)
      */
     public Boolean getRedirectOutput() {
@@ -1948,7 +1943,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether redirecting of output has been enabled.
-     *
+     * 
      * @return a boolean indicating if redirecting of output was enabled.
      */
     private boolean isRedirectingOutput() {
@@ -1958,7 +1953,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Sets whether the new instance of ServerLauncher will redirect output to system logs when
      * starting a Server.
-     *
+     * 
      * @param redirectOutput a boolean value indicating if output will be redirected to system logs
      *        when starting a Server.
      * @return this Builder instance.
@@ -1972,7 +1967,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Gets the IP address to which the Server will be bound listening for and accepting cache
      * client connections in a client/server topology.
-     *
+     * 
      * @return an InetAddress indicating the IP address that the Server is bound to listening for
      *         and accepting cache client connections in a client/server topology.
      * @see #setServerBindAddress(String)
@@ -1988,7 +1983,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Sets the IP address to which the Server will be bound listening for and accepting cache
      * client connections in a client/server topology.
-     *
+     * 
      * @param serverBindAddress a String specifying the IP address or hostname that the Server will
      *        be bound to listen for and accept cache client connections in a client/server
      *        topology.
@@ -2026,7 +2021,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Gets the port on which the Server will listen for and accept cache client connections in a
      * client/server topology.
-     *
+     * 
      * @return an Integer value specifying the port the Server will listen on and accept cache
      *         client connections in a client/server topology.
      * @see #setServerPort(Integer)
@@ -2042,7 +2037,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Sets the port on which the Server will listen for and accept cache client connections in a
      * client/server topology.
-     *
+     * 
      * @param serverPort an Integer value specifying the port the Server will listen on and accept
      *        cache client connections in a client/server topology.
      * @return this Builder instance.
@@ -2064,7 +2059,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * Gets the location of the Spring XML configuration meta-data file used to bootstrap, configure
      * and initialize the GemFire Server on start.
      * <p>
-     *
+     * 
      * @return a String indicating the location of the Spring XML configuration file.
      * @see #setSpringXmlLocation(String)
      */
@@ -2076,7 +2071,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * Sets the location of the Spring XML configuration meta-data file used to bootstrap, configure
      * and initialize the GemFire Server on start.
      * <p>
-     *
+     * 
      * @param springXmlLocation a String indicating the location of the Spring XML configuration
      *        file.
      * @return this Builder instance.
@@ -2090,7 +2085,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Gets the working directory pathname in which the Server will be ran. If the directory is
      * unspecified, then working directory defaults to the current directory.
-     *
+     * 
      * @return a String indicating the working directory pathname.
      * @see #setWorkingDirectory(String)
      */
@@ -2103,7 +2098,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * Sets the working directory in which the Server will be ran. This also the directory in which
      * all Server files (such as log and license files) will be written. If the directory is
      * unspecified, then the working directory defaults to the current directory.
-     *
+     * 
      * @param workingDirectory a String indicating the pathname of the directory in which the Server
      *        will be ran.
      * @return this Builder instance.
@@ -2266,6 +2261,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     }
 
 
+
     /**
      * Sets a GemFire Distributed System Property.
      *
@@ -2347,7 +2343,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
      * user must specify the member name for the Server in the GemFire distributed system as a
      * command-line argument, or by setting the memberName property programmatically using the
      * corresponding setter method.
-     *
+     * 
      * @throws IllegalStateException if the Builder is not properly configured.
      */
     protected void validate() {
@@ -2360,7 +2356,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Validates the arguments passed to the Builder when the 'start' command has been issued.
-     *
+     * 
      * @see org.apache.geode.distributed.ServerLauncher.Command#START
      */
     void validateOnStart() {
@@ -2384,7 +2380,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Validates the arguments passed to the Builder when the 'status' command has been issued.
-     *
+     * 
      * @see org.apache.geode.distributed.ServerLauncher.Command#STATUS
      */
     void validateOnStatus() {
@@ -2395,7 +2391,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Validates the arguments passed to the Builder when the 'stop' command has been issued.
-     *
+     * 
      * @see org.apache.geode.distributed.ServerLauncher.Command#STOP
      */
     void validateOnStop() {
@@ -2407,7 +2403,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Validates the Builder configuration settings and then constructs an instance of the
      * ServerLauncher class to invoke operations on a GemFire Server.
-     *
+     * 
      * @return a newly constructed instance of the ServerLauncher configured with this Builder.
      * @see #validate()
      * @see org.apache.geode.distributed.ServerLauncher
@@ -2437,13 +2433,13 @@ public class ServerLauncher extends AbstractLauncher<String> {
       assert isNotBlank(name) : "The name of the command must be specified!";
       this.name = name;
       this.options = options != null ? Collections.unmodifiableList(Arrays.asList(options))
-          : Collections.emptyList();
+          : Collections.<String>emptyList();
     }
 
     /**
      * Determines whether the specified name refers to a valid Server launcher command, as defined
      * by this enumerated type.
-     *
+     * 
      * @param name a String value indicating the potential name of a Server launcher command.
      * @return a boolean indicating whether the specified name for a Server launcher command is
      *         valid.
@@ -2455,7 +2451,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Determines whether the given Server launcher command has been properly specified. The command
      * is deemed unspecified if the reference is null or the Command is UNSPECIFIED.
-     *
+     * 
      * @param command the Server launcher command.
      * @return a boolean value indicating whether the Server launcher command is unspecified.
      * @see Command#UNSPECIFIED
@@ -2467,7 +2463,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Looks up a Server launcher command by name. The equality comparison on name is
      * case-insensitive.
-     *
+     * 
      * @param name a String value indicating the name of the Server launcher command.
      * @return an enumerated type representing the command name or null if the no such command with
      *         the specified name exists.
@@ -2484,7 +2480,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the name of the Server launcher command.
-     *
+     * 
      * @return a String value indicating the name of the Server launcher command.
      */
     public String getName() {
@@ -2494,7 +2490,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
     /**
      * Gets a set of valid options that can be used with the Server launcher command when used from
      * the command-line.
-     *
+     * 
      * @return a Set of Strings indicating the names of the options available to the Server launcher
      *         command.
      */
@@ -2504,7 +2500,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Determines whether this Server launcher command has the specified command-line option.
-     *
+     * 
      * @param option a String indicating the name of the command-line option to this command.
      * @return a boolean value indicating whether this command has the specified named command-line
      *         option.
@@ -2515,7 +2511,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Convenience method for determining whether this is the UNSPECIFIED Server launcher command.
-     *
+     * 
      * @return a boolean indicating if this command is UNSPECIFIED.
      * @see #UNSPECIFIED
      */
@@ -2525,7 +2521,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
 
     /**
      * Gets the String representation of this Server launcher command.
-     *
+     * 
      * @return a String value representing this Server launcher command.
      */
     @Override
@@ -2538,14 +2534,14 @@ public class ServerLauncher extends AbstractLauncher<String> {
    * The ServerState is an immutable type representing the state of the specified Server at any
    * given moment in time. The state of the Server is assessed at the exact moment an instance of
    * this class is constructed.
-   *
+   * 
    * @see org.apache.geode.distributed.AbstractLauncher.ServiceState
    */
   public static class ServerState extends ServiceState<String> {
 
     /**
      * Unmarshals a ServerState instance from the JSON String.
-     *
+     * 
      * @return a ServerState value unmarshalled from the JSON String.
      */
     public static ServerState fromJson(final String json) {
@@ -2596,35 +2592,20 @@ public class ServerLauncher extends AbstractLauncher<String> {
       this(status, // status
           errorMessage, // statusMessage
           System.currentTimeMillis(), // timestamp
-          getServerLocation(launcher), // serverLocation
+          null, // serverLocation
           null, // pid
           0L, // uptime
           launcher.getWorkingDirectory(), // workingDirectory
-          ManagementFactory.getRuntimeMXBean().getInputArguments(), // jvmArguments
+          Collections.<String>emptyList(), // jvmArguments
           null, // classpath
           GemFireVersion.getGemFireVersion(), // gemfireVersion
-          System.getProperty("java.version"), // javaVersion
+          null, // javaVersion
           null, // logFile
-          getServerBindAddress(launcher).getCanonicalHostName(), // host
-          launcher.getServerPortAsString(), // port
+          null, // host
+          null, // port
           null);// memberName
     }
 
-    /*
-     * Guards against throwing NPEs due to incorrect or missing host information while constructing
-     * error states
-     */
-    private static String getServerLocation(ServerLauncher launcher) {
-      if (launcher.getServerPort() == null) {
-        return launcher.getId();
-      }
-      if (launcher.getServerBindAddress() == null) {
-        return HostUtils.getLocatorId(HostUtils.getLocalHost(), launcher.getServerPort());
-      }
-      return HostUtils.getLocatorId(launcher.getServerBindAddress().getCanonicalHostName(),
-          launcher.getServerPort());
-    }
-
     protected ServerState(final Status status, final String statusMessage, final long timestamp,
         final String serverLocation, final Integer pid, final Long uptime,
         final String workingDirectory, final List<String> jvmArguments, final String classpath,
@@ -2646,6 +2627,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
           }
         }
       }
+
       return launcher.getLogFileCanonicalPath();
     }
 
@@ -2663,28 +2645,8 @@ public class ServerLauncher extends AbstractLauncher<String> {
           }
         }
       }
-      return launcher.getServerBindAddressAsString();
-    }
-
-    private static InetAddress getServerBindAddress(final ServerLauncher launcher) {
-      final InternalCache internalCache = GemFireCacheImpl.getInstance();
 
-      if (internalCache != null) {
-        final List<CacheServer> csList = internalCache.getCacheServers();
-        if (csList != null && !csList.isEmpty()) {
-          final CacheServer cs = csList.get(0);
-          final InetAddress serverBindAddress;
-          try {
-            serverBindAddress = InetAddress.getByName(cs.getBindAddress());
-          } catch (UnknownHostException e) {
-            throw new UncheckedIOException(e);
-          }
-          if (serverBindAddress != null) {
-            return serverBindAddress;
-          }
-        }
-      }
-      return launcher.getServerBindAddress();
+      return launcher.getServerBindAddressAsString();
     }
 
     @SuppressWarnings("unchecked")
@@ -2701,6 +2663,7 @@ public class ServerLauncher extends AbstractLauncher<String> {
           }
         }
       }
+
       return launcher.isDisableDefaultServer() ? EMPTY : launcher.getServerPortAsString();
     }
 
@@ -2709,4 +2672,5 @@ public class ServerLauncher extends AbstractLauncher<String> {
       return SERVER_SERVICE_NAME;
     }
   }
+
 }


[28/47] geode git commit: GEODE-3515 User Guide: bad table format, multi-site firewall properties

Posted by ds...@apache.org.
GEODE-3515 User Guide: bad table format, multi-site firewall properties


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

Branch: refs/heads/feature/GEODE-3543
Commit: 4c55938131490f0563f87d97b9582005657c02df
Parents: be8a135
Author: Dave Barnes <db...@pivotal.io>
Authored: Tue Aug 29 10:12:34 2017 -0700
Committer: Dave Barnes <db...@pivotal.io>
Committed: Tue Aug 29 10:17:22 2017 -0700

----------------------------------------------------------------------
 .../running/firewalls_multisite.html.md.erb     | 87 --------------------
 .../running/firewalls_ports.html.md.erb         | 72 +++-------------
 2 files changed, 13 insertions(+), 146 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/4c559381/geode-docs/configuring/running/firewalls_multisite.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/configuring/running/firewalls_multisite.html.md.erb b/geode-docs/configuring/running/firewalls_multisite.html.md.erb
deleted file mode 100644
index 50c25c7..0000000
--- a/geode-docs/configuring/running/firewalls_multisite.html.md.erb
+++ /dev/null
@@ -1,87 +0,0 @@
----
-title:  Firewalls and Ports in Multi-Site (WAN) Configurations
----
-
-<!--
-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.
--->
-
-Make sure your port settings are configured correctly for firewalls.
-
-<a id="concept_pfs_sf4_ft__section_alm_2g4_ft"></a>
-Each gateway receiver uses a port to listen for incoming communication from one or more gateway senders communication between GemFire sites. The full range of port values for gateway receivers must be made accessible within the firewall from across the WAN.
-
-## **Properties for Firewall and Port Configuration in Multi-Site (WAN) Configurations**
-
-This table contains properties potentially involved in firewall behavior, with a brief description of each property. Click on a property name for a link to the [gemfire.properties and gfsecurity.properties (GemFire Properties)](../../reference/topics/gemfire_properties.html#gemfire_properties) reference topic.
-
-<table>
-<colgroup>
-<col width="33%" />
-<col width="33%" />
-<col width="33%" />
-</colgroup>
-<thead>
-<tr class="header">
-<th>Configuration Area</th>
-<th><strong>Property or Setting</strong></th>
-<th><strong>Definition</strong></th>
-</tr>
-</thead>
-<tbody>
-<tr class="odd">
-<td>multi-site (WAN) config</td>
-<td><p>[hostname-for-senders](../../reference/topics/gfe_cache_xml.html#gateway-receiver)</p></td>
-<td><p>Hostname or IP address of the gateway receiver used by gateway senders to connect.</p></td>
-</tr>
-<tr class="even">
-<td>multi-site (WAN) config</td>
-<td>[remote-locators](../../reference/topics/gemfire_properties.html#gemfire_properties)</td>
-<td><p>List of locators (and their ports) that are available on the remote WAN site.</p></td>
-</tr>
-<tr class="odd">
-<td>multi-site (WAN) config</td>
-<td><p>[start-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) and [end-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) (cache.xml) or <code class="ph codeph">--start-port</code> and <code class="ph codeph">--end-port</code> parameters to the gfsh start gateway receiver command</p></td>
-<td><p>Port range that the gateway receiver can use to listen for gateway sender communication.</p></td>
-</tr>
-</tbody>
-</table>
-
-## Default Port Configuration
-
-<table>
-<colgroup>
-<col width="33%" />
-<col width="33%" />
-<col width="33%" />
-</colgroup>
-<thead>
-<tr class="header">
-<th><p><strong>Port Name</strong></p></th>
-<th>Related Configuration Setting</th>
-<th><p><strong>Default Port</strong></p></th>
-</tr>
-</thead>
-<tbody>
-<tr class="odd">
-<td><p>Gateway Receiver</p></td>
-<td><p>[start-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) and [end-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) (cache.xml) or <code class="ph codeph">--start-port</code> and <code class="ph codeph">--end-port</code> parameters to the <code class="ph codeph">gfsh start gateway receiver</code> command</p></td>
-<td><em>not set</em> Each gateway receiver uses a single port to accept connections from gateway senders in other systems. However, the configuration of a gateway receiver specifies a range of possible port values to use. GemFire selects an available port from the specified range when the gateway receiver starts. Configure your firewall so that the full range of possible port values is accessible by gateway senders from across the WAN.</td>
-</tr>
-</tbody>
-</table>
-
-

http://git-wip-us.apache.org/repos/asf/geode/blob/4c559381/geode-docs/configuring/running/firewalls_ports.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/configuring/running/firewalls_ports.html.md.erb b/geode-docs/configuring/running/firewalls_ports.html.md.erb
index dd781c1..96212d6 100644
--- a/geode-docs/configuring/running/firewalls_ports.html.md.erb
+++ b/geode-docs/configuring/running/firewalls_ports.html.md.erb
@@ -41,7 +41,7 @@ By default, <%=vars.product_name%> assigns *ephemeral* ports, that is, temporary
 
 ## **Properties for Firewall and Port Configuration**
 
-This table contains properties potentially involved in firewall behavior, with a brief description of each property. Click on a property name for a link to the reference topic.
+This table contains properties potentially involved in firewall behavior, with a brief description of each property.
 
 <table>
 <colgroup>
@@ -94,7 +94,7 @@ This table contains properties potentially involved in firewall behavior, with a
 <colgroup>
 <col width="33%" />
 <col width="33%" />
-<col width="33%" />
+<col width="34%" />
 </colgroup>
 <thead>
 <tr class="header">
@@ -128,7 +128,7 @@ This table contains properties potentially involved in firewall behavior, with a
 <colgroup>
 <col width="33%" />
 <col width="33%" />
-<col width="33%" />
+<col width="34%" />
 </colgroup>
 <thead>
 <tr class="header">
@@ -183,64 +183,18 @@ This table contains properties potentially involved in firewall behavior, with a
 
 ## **Properties for Firewall and Port Configuration in Multi-Site (WAN) Configurations**
 
-Each gateway receiver uses a port to listen for incoming communication from one or more gateway senders communication between <%=vars.product_name%> sites. The full range of port values for gateway receivers must be made accessible within the firewall from across the WAN.
+Each gateway receiver uses a single port to accept connections from gateway senders in other
+systems. The configuration of a gateway receiver specifies a range of possible port values
+to use. <%=vars.product_name%> selects an available port from the specified range when the gateway
+receiver starts. Configure your firewall so that the full range of possible port values is
+accessible by gateway senders from across the WAN.
 
-This table contains properties potentially involved in firewall behavior, with a brief description of each property. Click on a property name for a link to the [gemfire.properties and gfsecurity.properties (<%=vars.product_name%> Properties)](../../reference/topics/gemfire_properties.html#gemfire_properties) reference topic.
+| Configuration Area | Property or Setting | Definition |
+|--------------------|---------------------|------------|
+| multi-site (WAN) config for gateway sender | [hostname-for-senders](../../reference/topics/gfe_cache_xml.html#gateway-receiver) | Hostname or IP address of the gateway receiver used by gateway senders to connect. |
+| multi-site (WAN) config for locator | [remote-locators](../../reference/topics/gemfire_properties.html#gemfire_properties) | List of locators (and their ports) that are available on the remote WAN site. |
+| multi-site (WAN) config for gateway receiver | [start-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) and [end-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) (cache.xml) or <code class="ph codeph">--start-port</code> and <code class="ph codeph">--end-port</code> parameters to the <code class=" ph codeph">gfsh start gateway receiver</code> command | Port range that the gateway receiver can use to listen for gateway sender communication. |
 
-<table>
-<colgroup>
-<col width="33%" />
-<col width="33%" />
-<col width="33%" />
-</colgroup>
-<thead>
-<tr class="header">
-<th>Configuration Area</th>
-<th><strong>Property or Setting</strong></th>
-<th><strong>Definition</strong></th>
-</tr>
-</thead>
-<tbody>
-<tr class="odd">
-<td>multi-site (WAN) config</td>
-<td><p>[hostname-for-senders](../../reference/topics/gfe_cache_xml.html#gateway-receiver)</p></td>
-<td><p>Hostname or IP address of the gateway receiver used by gateway senders to connect.</p></td>
-</tr>
-<tr class="even">
-<td>multi-site (WAN) config</td>
-<td>[remote-locators](../../reference/topics/gemfire_properties.html#gemfire_properties)</td>
-<td><p>List of locators (and their ports) that are available on the remote WAN site.</p></td>
-</tr>
-<tr class="odd">
-<td>multi-site (WAN) config</td>
-<td><p>[start-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) and [end-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) (cache.xml) or <code class="ph codeph">--start-port</code> and <code class="ph codeph">--end-port</code> parameters to the <code class=" ph codeph">gfsh start gateway receiver</code> command</p></td>
-<td><p>Port range that the gateway receiver can use to listen for gateway sender communication.</p></td>
-</tr>
-</tbody>
-</table>
 
-## Default Port Configuration
-
-<table>
-<colgroup>
-<col width="33%" />
-<col width="33%" />
-<col width="33%" />
-</colgroup>
-<thead>
-<tr class="header">
-<th><p><strong>Port Name</strong></p></th>
-<th>Related Configuration Setting</th>
-<th><p><strong>Default Port</strong></p></th>
-</tr>
-</thead>
-<tbody>
-<tr class="odd">
-<td><p>Gateway Receiver</p></td>
-<td><p>[start-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) and [end-port](../../reference/topics/gfe_cache_xml.html#gateway-receiver) (cache.xml) or <code class="ph codeph">--start-port</code> and <code class="ph codeph">--end-port</code> parameters to the <code class="ph codeph">gfsh start gateway receiver</code> command</p></td>
-<td><em>not set</em> Each gateway receiver uses a single port to accept connections from gateway senders in other systems. However, the configuration of a gateway receiver specifies a range of possible port values to use. <%=vars.product_name%> selects an available port from the specified range when the gateway receiver starts. Configure your firewall so that the full range of possible port values is accessible by gateway senders from across the WAN.</td>
-</tr>
-</tbody>
-</table>
 
 


[42/47] geode git commit: GEODE-2859: Fix race condition in ShowDeadlockDUnitTest

Posted by ds...@apache.org.
GEODE-2859: Fix race condition in ShowDeadlockDUnitTest


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

Branch: refs/heads/feature/GEODE-3543
Commit: ca0dca51ebd9694cf6a34548252ed3c720b59253
Parents: fb9a405
Author: Jared Stewart <js...@pivotal.io>
Authored: Tue Aug 29 12:02:47 2017 -0700
Committer: Jared Stewart <js...@pivotal.io>
Committed: Wed Aug 30 09:44:59 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/ShowDeadlockDUnitTest.java     | 205 +++++++------------
 .../dunit/rules/GfshShellConnectionRule.java    |   9 +-
 geode-junit/build.gradle                        |   1 +
 .../concurrent/FileBasedCountDownLatch.java     |  87 ++++++++
 .../concurrent/FileBasedCountDownLatchTest.java |  37 ++++
 5 files changed, 202 insertions(+), 137 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/ca0dca51/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java
index 4df0b96..51560db 100755
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java
@@ -14,203 +14,138 @@
  */
 package org.apache.geode.management.internal.cli.commands;
 
-import static org.apache.geode.test.dunit.Assert.assertEquals;
-import static org.apache.geode.test.dunit.Assert.assertTrue;
-import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.assertj.core.api.Assertions.assertThat;
 
 import java.io.File;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
-import org.apache.commons.io.FileUtils;
 import org.awaitility.Awaitility;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
 
 import org.apache.geode.cache.execute.Function;
 import org.apache.geode.cache.execute.FunctionContext;
 import org.apache.geode.cache.execute.FunctionService;
 import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.cache30.CacheTestCase;
-import org.apache.geode.distributed.internal.deadlock.GemFireDeadlockDetector;
 import org.apache.geode.distributed.internal.deadlock.GemFireDeadlockDetectorDUnitTest;
 import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
-import org.apache.geode.management.cli.CommandStatement;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.cli.Result.Status;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.remote.CommandProcessor;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.concurrent.FileBasedCountDownLatch;
+import org.apache.geode.test.dunit.rules.GfshShellConnectionRule;
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
+import org.apache.geode.test.dunit.rules.MemberVM;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 
 /**
- *
+ * Distributed tests for show deadlock command in {@link ShowDeadlockCommand}.
+ * 
  * @see GemFireDeadlockDetectorDUnitTest
  */
 @Category(DistributedTest.class)
-public class ShowDeadlockDUnitTest extends CacheTestCase {
+public class ShowDeadlockDUnitTest {
+  private static Thread stuckThread = null;
+  private static final Lock LOCK = new ReentrantLock();
 
-  private static final Set<Thread> stuckThreads =
-      Collections.synchronizedSet(new HashSet<Thread>());
+  private MemberVM server1;
+  private MemberVM server2;
 
-  private static final Lock lock = new ReentrantLock();
+  private File outputFile;
+  private String showDeadlockCommand;
 
-  private transient VM vm0;
-  private transient VM vm1;
+  @Rule
+  public LocatorServerStartupRule lsRule = new LocatorServerStartupRule();
 
-  private transient InternalDistributedMember member0;
-  private transient InternalDistributedMember member1;
+  @Rule
+  public TemporaryFolder temporaryFolder = new TemporaryFolder();
 
   @Rule
-  public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
+  public GfshShellConnectionRule gfsh = new GfshShellConnectionRule();
 
   @Before
-  public void setup() {
-    Host host = Host.getHost(0);
-    vm0 = host.getVM(0);
-    vm1 = host.getVM(1);
-
-    // Make sure a deadlock from a previous test is cleared.
-    disconnectAllFromDS();
+  public void setup() throws Exception {
+    outputFile = new File(temporaryFolder.getRoot(), "dependency.txt").getAbsoluteFile();
+    showDeadlockCommand = "show dead-locks --file=" + outputFile.getAbsolutePath();
+    outputFile.delete();
 
-    member0 = createCache(vm0);
-    member1 = createCache(vm1);
+    MemberVM locator = lsRule.startLocatorVM(0);
+    server1 = lsRule.startServerVM(1, locator.getPort());
+    server2 = lsRule.startServerVM(2, locator.getPort());
 
-    createCache(new Properties());
+    gfsh.connect(locator);
   }
 
   @After
-  public void teardown() {
-    disconnectAllFromDS();
-  }
-
-  @Override
-  public final void preTearDownCacheTestCase() throws Exception {
-    invokeInEveryVM(() -> stuckThreads.forEach(Thread::interrupt));
+  public final void after() throws Exception {
+    server1.invoke(() -> stuckThread.interrupt());
+    server2.invoke(() -> stuckThread.interrupt());
   }
 
   @Test
   public void testNoDeadlock() throws Exception {
-    GemFireDeadlockDetector detect = new GemFireDeadlockDetector();
-    assertEquals(null, detect.find().findCycle());
-
-    File outputFile = new File(temporaryFolder.getRoot(), "dependency.txt");
+    gfsh.executeAndVerifyCommand(showDeadlockCommand);
+    String commandOutput = gfsh.getGfshOutput();
 
-    String showDeadlockCommand = new CommandStringBuilder(CliStrings.SHOW_DEADLOCK)
-        .addOption(CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE, outputFile.getName()).toString();
-
-    Result result = new CommandProcessor()
-        .createCommandStatement(showDeadlockCommand, Collections.emptyMap()).process();
-    String commandOutput = getResultAsString(result);
-
-    assertEquals(true, result.hasIncomingFiles());
-    assertEquals(true, result.getStatus().equals(Status.OK));
-    assertEquals(true, commandOutput.startsWith(CliStrings.SHOW_DEADLOCK__NO__DEADLOCK));
-    result.saveIncomingFiles(temporaryFolder.getRoot().getAbsolutePath());
-    assertTrue(outputFile.exists());
+    assertThat(commandOutput).startsWith(CliStrings.SHOW_DEADLOCK__NO__DEADLOCK);
+    assertThat(outputFile).exists();
   }
 
   @Test
   public void testDistributedDeadlockWithFunction() throws Exception {
-    // Have two threads lock locks on different members in different orders.
-    // This thread locks the lock member0 first, then member1.
-    lockTheLocks(vm0, member1);
-    // This thread locks the lock member1 first, then member0.
-    lockTheLocks(vm1, member0);
-
-    File outputFile = new File(temporaryFolder.getRoot(), "dependency.txt");
-
-    String showDeadlockCommand = new CommandStringBuilder(CliStrings.SHOW_DEADLOCK)
-        .addOption(CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE, outputFile.getName()).toString();
-    CommandStatement showDeadlocksCommand =
-        new CommandProcessor().createCommandStatement(showDeadlockCommand, Collections.emptyMap());
-
-    Awaitility.await().atMost(1, TimeUnit.MINUTES).until(() -> {
-      FileUtils.deleteQuietly(outputFile);
-      Result result = showDeadlocksCommand.process();
-      try {
-        result.saveIncomingFiles(temporaryFolder.getRoot().getAbsolutePath());
-      } catch (IOException e) {
-        throw new RuntimeException(e);
-      }
-
-      String commandOutput = getResultAsString(result);
-      assertEquals(true, commandOutput.startsWith(CliStrings.SHOW_DEADLOCK__DEADLOCK__DETECTED));
-      assertEquals(true, result.getStatus().equals(Status.OK));
-      assertTrue(outputFile.exists());
+    FileBasedCountDownLatch countDownLatch = new FileBasedCountDownLatch(2);
+
+    // This thread locks the lock in server1 first, then server2.
+    lockTheLocks(server1, server2, countDownLatch);
+    // This thread locks the lock server2 first, then server1.
+    lockTheLocks(server2, server1, countDownLatch);
+
+    Awaitility.await().atMost(5, TimeUnit.MINUTES).pollDelay(5, TimeUnit.SECONDS).until(() -> {
+      gfsh.executeAndVerifyCommand(showDeadlockCommand);
+      String commandOutput = gfsh.getGfshOutput();
+      assertThat(commandOutput).startsWith(CliStrings.SHOW_DEADLOCK__DEADLOCK__DETECTED);
+      assertThat(outputFile).exists();
     });
   }
 
-  private void createCache(Properties props) {
-    getSystem(props);
-    getCache();
-  }
-
-  private void lockTheLocks(VM vm0, final InternalDistributedMember member) {
-    vm0.invokeAsync(() -> {
-      lock.lock();
-
-      ResultCollector collector = FunctionService.onMember(member).execute(new TestFunction());
-      // wait the function to lock the lock on member.
-      collector.getResult();
-      lock.unlock();
+  private void lockTheLocks(MemberVM thisVM, final MemberVM thatVM,
+      FileBasedCountDownLatch countDownLatch) {
+    thisVM.invokeAsync(() -> {
+      LOCK.lock();
+      countDownLatch.countDown();
+      countDownLatch.await();
+      // At this point each VM will hold its own lock.
+      lockRemoteVM(thatVM);
+      LOCK.unlock();
     });
   }
 
-  private InternalDistributedMember createCache(VM vm) {
-    return (InternalDistributedMember) vm.invoke(new SerializableCallable<Object>() {
-      @Override
-      public Object call() {
-        getCache();
-        return getSystem().getDistributedMember();
-      }
-    });
-  }
+  private static void lockRemoteVM(MemberVM vmToLock) {
+    InternalDistributedMember thatInternalMember = getInternalDistributedMember(vmToLock);
 
-  private String getResultAsString(Result result) {
-    StringBuilder sb = new StringBuilder();
-    while (result.hasNextLine()) {
-      sb.append(result.nextLine());
-    }
-
-    return sb.toString();
+    ResultCollector collector =
+        FunctionService.onMember(thatInternalMember).execute(new LockFunction());
+    collector.getResult();
   }
 
-  private static class TestFunction implements Function<Object> {
-    private static final int LOCK_WAIT_TIME = 1000;
-
-    @Override
-    public boolean hasResult() {
-      return true;
-    }
+  private static InternalDistributedMember getInternalDistributedMember(MemberVM memberVM) {
+    return memberVM.getVM().invoke(() -> LocatorServerStartupRule.serverStarter.getCache()
+        .getInternalDistributedSystem().getDistributedMember());
+  }
 
+  private static class LockFunction implements Function<Object> {
     @Override
     public void execute(FunctionContext<Object> context) {
+      stuckThread = Thread.currentThread();
       try {
-        stuckThreads.add(Thread.currentThread());
-        lock.tryLock(LOCK_WAIT_TIME, TimeUnit.SECONDS);
-      } catch (InterruptedException ignored) {
-        // ignored
+        LOCK.tryLock(5, TimeUnit.MINUTES);
+      } catch (InterruptedException e) {
+        context.getResultSender().lastResult(null);
       }
-      context.getResultSender().lastResult(null);
-    }
-
-    @Override
-    public boolean isHA() {
-      return false;
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/ca0dca51/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java
index e7f17ef..a9ce889 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/GfshShellConnectionRule.java
@@ -223,8 +223,13 @@ public class GfshShellConnectionRule extends DescribedExternalResource {
   }
 
 
-  public CommandResult executeAndVerifyCommand(String command) throws Exception {
-    CommandResult result = executeCommand(command);
+  public CommandResult executeAndVerifyCommand(String command) {
+    CommandResult result = null;
+    try {
+      result = executeCommand(command);
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
     assertThat(result.getStatus())
         .describedAs("Failure in command: " + command + "\n Result " + result)
         .isEqualTo(Result.Status.OK);

http://git-wip-us.apache.org/repos/asf/geode/blob/ca0dca51/geode-junit/build.gradle
----------------------------------------------------------------------
diff --git a/geode-junit/build.gradle b/geode-junit/build.gradle
index 7c533ad..ccfbb24 100755
--- a/geode-junit/build.gradle
+++ b/geode-junit/build.gradle
@@ -23,6 +23,7 @@ dependencies {
   compile 'commons-io:commons-io:' + project.'commons-io.version'
   compile 'commons-lang:commons-lang:' + project.'commons-lang.version'
   compile 'com.google.guava:guava:' + project.'guava.version'
+  compile 'org.awaitility:awaitility:' + project.'awaitility.version'
 
 
   compile('junit:junit:' + project.'junit.version') {

http://git-wip-us.apache.org/repos/asf/geode/blob/ca0dca51/geode-junit/src/main/java/org/apache/geode/test/concurrent/FileBasedCountDownLatch.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/main/java/org/apache/geode/test/concurrent/FileBasedCountDownLatch.java b/geode-junit/src/main/java/org/apache/geode/test/concurrent/FileBasedCountDownLatch.java
new file mode 100644
index 0000000..43fe260
--- /dev/null
+++ b/geode-junit/src/main/java/org/apache/geode/test/concurrent/FileBasedCountDownLatch.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.test.concurrent;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.concurrent.TimeUnit;
+
+import com.google.common.base.Charsets;
+import org.apache.commons.io.FileUtils;
+import org.awaitility.Awaitility;
+
+/**
+ * This is an implementation of CountDownLatch that can be serialized and used across multiple DUnit
+ * VMs. File locks are used to synchronize between the separate VMs. For an example usage, see
+ * ShowDeadlockDUnitTest.
+ */
+public class FileBasedCountDownLatch implements Serializable {
+  private final File lockFile;
+  private final File dataFile;
+
+  public FileBasedCountDownLatch(int count) throws IOException {
+    lockFile = File.createTempFile("CountDownLatchLock", ".txt");
+    dataFile = File.createTempFile("CountDownLatchData", ".txt");
+
+    try (FileOutputStream out = new FileOutputStream(lockFile)) {
+      java.nio.channels.FileLock lock = out.getChannel().lock();
+      try {
+        FileUtils.writeStringToFile(dataFile, String.valueOf(count), Charsets.UTF_8);
+      } finally {
+        lock.release();
+      }
+    }
+
+    lockFile.deleteOnExit();
+  }
+
+  public void countDown() throws IOException {
+    try (FileOutputStream out = new FileOutputStream(lockFile)) {
+      java.nio.channels.FileLock lock = out.getChannel().lock();
+
+      try {
+        String fileContents = FileUtils.readFileToString(dataFile, Charsets.UTF_8);
+        int currentValue = Integer.valueOf(fileContents);
+
+        int newValue = currentValue - 1;
+        FileUtils.writeStringToFile(dataFile, String.valueOf(newValue), Charsets.UTF_8);
+
+      } finally {
+        lock.release();
+      }
+    }
+  }
+
+  public void await() throws IOException {
+    Awaitility.await().atMost(10, TimeUnit.MINUTES).until(this::currentValue, is(equalTo(0)));
+  }
+
+  protected int currentValue() throws IOException {
+    try (FileOutputStream out = new FileOutputStream(lockFile)) {
+      java.nio.channels.FileLock lock = out.getChannel().lock();
+      try {
+        String fileContents = FileUtils.readFileToString(dataFile, Charsets.UTF_8);
+        return Integer.valueOf(fileContents);
+      } finally {
+        lock.release();
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/ca0dca51/geode-junit/src/test/java/org/apache/geode/test/concurrent/FileBasedCountDownLatchTest.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/test/java/org/apache/geode/test/concurrent/FileBasedCountDownLatchTest.java b/geode-junit/src/test/java/org/apache/geode/test/concurrent/FileBasedCountDownLatchTest.java
new file mode 100644
index 0000000..a4da5fb
--- /dev/null
+++ b/geode-junit/src/test/java/org/apache/geode/test/concurrent/FileBasedCountDownLatchTest.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.test.concurrent;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.test.junit.categories.IntegrationTest;
+
+@Category(IntegrationTest.class)
+public class FileBasedCountDownLatchTest {
+  @Test
+  public void singleThreadedBehaviorIsCorrect() throws Exception {
+    FileBasedCountDownLatch fileBasedCountDownLatch = new FileBasedCountDownLatch(2);
+    assertThat(fileBasedCountDownLatch.currentValue()).isEqualTo(2);
+
+    fileBasedCountDownLatch.countDown();
+    assertThat(fileBasedCountDownLatch.currentValue()).isEqualTo(1);
+
+    fileBasedCountDownLatch.countDown();
+    assertThat(fileBasedCountDownLatch.currentValue()).isEqualTo(0);
+  }
+}


[21/47] geode git commit: GEODE-3436: Restore refactoring of ConfigCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of ConfigCommands

* See initial commit GEODE-3254 (97c4e9a59f17c7bc914e39dd048b0a4cd96293c4)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 3bfe7a201ce77365f6197be36a3947afea749f10
Parents: 611095f
Author: YehEmily <em...@gmail.com>
Authored: Wed Jul 26 11:07:09 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:26 2017 -0700

----------------------------------------------------------------------
 .../org/apache/geode/BundledJarsJUnitTest.java  |  44 +-
 .../cli/commands/AlterRuntimeConfigCommand.java | 246 ++++++++++
 .../internal/cli/commands/ConfigCommands.java   | 490 -------------------
 .../cli/commands/DescribeConfigCommand.java     | 153 ++++++
 .../cli/commands/ExportConfigCommand.java       | 159 ++++++
 .../controllers/ConfigCommandsController.java   |  17 +-
 .../controllers/DeployCommandsController.java   |  19 +-
 .../cli/commands/LogLevelInterceptorTest.java   |   2 +-
 .../internal/security/TestCommand.java          |   2 +-
 9 files changed, 600 insertions(+), 532 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java b/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
index 3f0e2c0..3a5538c 100644
--- a/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
@@ -16,14 +16,6 @@ package org.apache.geode;
 
 import static org.junit.Assert.assertTrue;
 
-import org.apache.commons.io.FileUtils;
-import org.apache.geode.test.junit.categories.IntegrationTest;
-import org.apache.geode.test.junit.categories.RestAPITest;
-import org.apache.geode.util.test.TestUtil;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
 import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
@@ -36,11 +28,20 @@ import java.util.jar.JarFile;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
+import org.apache.commons.io.FileUtils;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.test.junit.categories.IntegrationTest;
+import org.apache.geode.test.junit.categories.RestAPITest;
+import org.apache.geode.util.test.TestUtil;
+
 @Category({IntegrationTest.class, RestAPITest.class})
 public class BundledJarsJUnitTest {
 
   private static final String VERSION_PATTERN = "[0-9-_.v]{3,}.*\\.jar$";
-  protected static final String GEODE_HOME = System.getenv("GEODE_HOME");
+  private static final String GEODE_HOME = System.getenv("GEODE_HOME");
   private Set<String> expectedJars;
 
   @Before
@@ -65,27 +66,22 @@ public class BundledJarsJUnitTest {
     TreeSet<String> missingJars = new TreeSet<String>(expectedJars);
     missingJars.removeAll(bundledJarNames);
 
-    StringBuilder message = new StringBuilder();
-    message.append(
-        "The bundled jars have changed. Please make sure you update the licence and notice");
-    message.append(
-        "\nas described in https://cwiki.apache.org/confluence/display/GEODE/License+Guide+for+Contributors");
-    message.append("\nWhen fixed, copy geode-assembly/build/test/bundled_jars.txt");
-    message.append("\nto src/test/resources/expected_jars.txt");
-    message.append("\nRemoved Jars\n--------------\n");
-    message.append(String.join("\n", missingJars));
-    message.append("\n\nAdded Jars\n--------------\n");
-    message.append(String.join("\n", newJars));
-    message.append("\n\n");
-
-    assertTrue(message.toString(), expectedJars.equals(bundledJarNames));
+    String message =
+        "The bundled jars have changed. Please make sure you update the licence and notice"
+            + "\nas described in https://cwiki.apache.org/confluence/display/GEODE/License+Guide+for+Contributors"
+            + "\nWhen fixed, copy geode-assembly/build/test/bundled_jars.txt"
+            + "\nto src/test/resources/expected_jars.txt" + "\nRemoved Jars\n--------------\n"
+            + String.join("\n", missingJars) + "\n\nAdded Jars\n--------------\n"
+            + String.join("\n", newJars) + "\n\n";
+
+    assertTrue(message, expectedJars.equals(bundledJarNames));
 
   }
 
   /**
    * Find all of the jars bundled with the project. Key is the name of the jar, value is the path.
    */
-  protected TreeMap<String, String> getBundledJars() {
+  private TreeMap<String, String> getBundledJars() {
     File geodeHomeDirectory = new File(GEODE_HOME);
 
     assertTrue(

http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeConfigCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeConfigCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeConfigCommand.java
new file mode 100644
index 0000000..3b75977
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeConfigCommand.java
@@ -0,0 +1,246 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLING_ENABLED;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.logging.log4j.Logger;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.xmlcache.CacheXml;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.internal.logging.log4j.LogLevel;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.functions.AlterRuntimeConfigFunction;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class AlterRuntimeConfigCommand implements GfshCommand {
+  private final AlterRuntimeConfigFunction alterRunTimeConfigFunction =
+      new AlterRuntimeConfigFunction();
+  private static Logger logger = LogService.getLogger();
+
+  @CliCommand(value = {CliStrings.ALTER_RUNTIME_CONFIG},
+      help = CliStrings.ALTER_RUNTIME_CONFIG__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG},
+      interceptor = "org.apache.geode.management.internal.cli.commands.AlterRuntimeConfigCommand$AlterRuntimeInterceptor")
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE)
+  public Result alterRuntimeConfig(
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+          help = CliStrings.ALTER_RUNTIME_CONFIG__MEMBER__HELP) String[] memberNameOrId,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.ALTER_RUNTIME_CONFIG__MEMBER__HELP) String[] group,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT__HELP) Integer archiveDiskSpaceLimit,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT__HELP) Integer archiveFileSizeLimit,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT__HELP) Integer logDiskSpaceLimit,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT__HELP) Integer logFileSizeLimit,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL},
+          optionContext = ConverterHint.LOG_LEVEL,
+          help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL__HELP) String logLevel,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE__HELP) String statisticArchiveFile,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE__HELP) Integer statisticSampleRate,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED__HELP) Boolean statisticSamplingEnabled,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ},
+          specifiedDefaultValue = "false",
+          help = CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ__HELP) Boolean setCopyOnRead,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE__HELP) Integer lockLease,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT__HELP) Integer lockTimeout,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL__HELP) Integer messageSyncInterval,
+      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT},
+          help = CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT__HELP) Integer searchTimeout) {
+
+    Map<String, String> runTimeDistributionConfigAttributes = new HashMap<>();
+    Map<String, String> rumTimeCacheAttributes = new HashMap<>();
+    Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+    if (targetMembers.isEmpty()) {
+      return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+    }
+
+    if (archiveDiskSpaceLimit != null) {
+      runTimeDistributionConfigAttributes.put(
+          CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT,
+          archiveDiskSpaceLimit.toString());
+    }
+
+    if (archiveFileSizeLimit != null) {
+      runTimeDistributionConfigAttributes.put(
+          CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT,
+          archiveFileSizeLimit.toString());
+    }
+
+    if (logDiskSpaceLimit != null) {
+      runTimeDistributionConfigAttributes.put(
+          CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, logDiskSpaceLimit.toString());
+    }
+
+    if (logFileSizeLimit != null) {
+      runTimeDistributionConfigAttributes.put(
+          CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT, logFileSizeLimit.toString());
+    }
+
+    if (logLevel != null && !logLevel.isEmpty()) {
+      runTimeDistributionConfigAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL,
+          logLevel);
+    }
+
+    if (statisticArchiveFile != null && !statisticArchiveFile.isEmpty()) {
+      runTimeDistributionConfigAttributes
+          .put(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE, statisticArchiveFile);
+    }
+
+    if (statisticSampleRate != null) {
+      runTimeDistributionConfigAttributes.put(
+          CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE, statisticSampleRate.toString());
+    }
+
+    if (statisticSamplingEnabled != null) {
+      runTimeDistributionConfigAttributes.put(STATISTIC_SAMPLING_ENABLED,
+          statisticSamplingEnabled.toString());
+    }
+
+
+    // Attributes that are set on the cache.
+    if (setCopyOnRead != null) {
+      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ,
+          setCopyOnRead.toString());
+    }
+
+    if (lockLease != null && lockLease > 0 && lockLease < Integer.MAX_VALUE) {
+      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE,
+          lockLease.toString());
+    }
+
+    if (lockTimeout != null && lockTimeout > 0 && lockTimeout < Integer.MAX_VALUE) {
+      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT,
+          lockTimeout.toString());
+    }
+
+    if (messageSyncInterval != null && messageSyncInterval > 0
+        && messageSyncInterval < Integer.MAX_VALUE) {
+      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL,
+          messageSyncInterval.toString());
+    }
+
+    if (searchTimeout != null && searchTimeout > 0 && searchTimeout < Integer.MAX_VALUE) {
+      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT,
+          searchTimeout.toString());
+    }
+
+    if (runTimeDistributionConfigAttributes.isEmpty() && rumTimeCacheAttributes.isEmpty()) {
+      return ResultBuilder
+          .createUserErrorResult(CliStrings.ALTER_RUNTIME_CONFIG__RELEVANT__OPTION__MESSAGE);
+    }
+
+    Map<String, String> allRunTimeAttributes = new HashMap<>();
+    allRunTimeAttributes.putAll(runTimeDistributionConfigAttributes);
+    allRunTimeAttributes.putAll(rumTimeCacheAttributes);
+
+    ResultCollector<?, ?> rc =
+        CliUtil.executeFunction(alterRunTimeConfigFunction, allRunTimeAttributes, targetMembers);
+    List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+    Set<String> successfulMembers = new TreeSet<>();
+    Set<String> errorMessages = new TreeSet<>();
+
+    for (CliFunctionResult result : results) {
+      if (result.getThrowable() != null) {
+        logger.info("Function failed: " + result.getThrowable());
+        errorMessages.add(result.getThrowable().getMessage());
+      } else {
+        successfulMembers.add(result.getMemberIdOrName());
+      }
+    }
+    final String lineSeparator = System.getProperty("line.separator");
+    if (!successfulMembers.isEmpty()) {
+      StringBuilder successMessageBuilder = new StringBuilder();
+
+      successMessageBuilder.append(CliStrings.ALTER_RUNTIME_CONFIG__SUCCESS__MESSAGE);
+      successMessageBuilder.append(lineSeparator);
+
+      for (String member : successfulMembers) {
+        successMessageBuilder.append(member);
+        successMessageBuilder.append(lineSeparator);
+      }
+
+      Properties properties = new Properties();
+      properties.putAll(runTimeDistributionConfigAttributes);
+
+      Result result = ResultBuilder.createInfoResult(successMessageBuilder.toString());
+
+      // Set the Cache attributes to be modified
+      final XmlEntity xmlEntity = XmlEntity.builder().withType(CacheXml.CACHE)
+          .withAttributes(rumTimeCacheAttributes).build();
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().modifyXmlAndProperties(properties, xmlEntity, group));
+      return result;
+    } else {
+      StringBuilder errorMessageBuilder = new StringBuilder();
+      errorMessageBuilder.append("Following errors occurred while altering runtime config");
+      errorMessageBuilder.append(lineSeparator);
+
+      for (String errorMessage : errorMessages) {
+        errorMessageBuilder.append(errorMessage);
+        errorMessageBuilder.append(lineSeparator);
+      }
+      return ResultBuilder.createUserErrorResult(errorMessageBuilder.toString());
+    }
+  }
+
+  public static class AlterRuntimeInterceptor extends AbstractCliAroundInterceptor {
+    @Override
+    public Result preExecution(GfshParseResult parseResult) {
+      Map<String, String> arguments = parseResult.getParamValueStrings();
+      // validate log level
+      String logLevel = arguments.get("log-level");
+      if (StringUtils.isNotBlank(logLevel) && (LogLevel.getLevel(logLevel) == null)) {
+        return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
+      }
+      return ResultBuilder.createInfoResult("");
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigCommands.java
deleted file mode 100644
index a8afa7d..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigCommands.java
+++ /dev/null
@@ -1,490 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLING_ENABLED;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.xmlcache.CacheXml;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.internal.logging.log4j.LogLevel;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.domain.MemberConfigurationInfo;
-import org.apache.geode.management.internal.cli.functions.AlterRuntimeConfigFunction;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.ExportConfigFunction;
-import org.apache.geode.management.internal.cli.functions.GetMemberConfigInformationFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResultException;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.logging.log4j.Logger;
-import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.TreeSet;
-
-/****
- * @since GemFire 7.0
- *
- */
-public class ConfigCommands implements GfshCommand {
-  private final ExportConfigFunction exportConfigFunction = new ExportConfigFunction();
-  private final GetMemberConfigInformationFunction getMemberConfigFunction =
-      new GetMemberConfigInformationFunction();
-  private final AlterRuntimeConfigFunction alterRunTimeConfigFunction =
-      new AlterRuntimeConfigFunction();
-  private static Logger logger = LogService.getLogger();
-
-  @CliCommand(value = {CliStrings.DESCRIBE_CONFIG}, help = CliStrings.DESCRIBE_CONFIG__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result describeConfig(
-      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
-          help = CliStrings.DESCRIBE_CONFIG__MEMBER__HELP, mandatory = true) String memberNameOrId,
-      @CliOption(key = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS,
-          help = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS__HELP, unspecifiedDefaultValue = "true",
-          specifiedDefaultValue = "true") boolean hideDefaults) {
-
-    Result result = null;
-    try {
-      DistributedMember targetMember = null;
-
-      if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
-        targetMember = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
-      }
-      if (targetMember != null) {
-        ResultCollector<?, ?> rc = CliUtil.executeFunction(getMemberConfigFunction,
-            new Boolean(hideDefaults), targetMember);
-        ArrayList<?> output = (ArrayList<?>) rc.getResult();
-        Object obj = output.get(0);
-
-        if (obj != null && obj instanceof MemberConfigurationInfo) {
-          MemberConfigurationInfo memberConfigInfo = (MemberConfigurationInfo) obj;
-
-          CompositeResultData crd = ResultBuilder.createCompositeResultData();
-          crd.setHeader(
-              CliStrings.format(CliStrings.DESCRIBE_CONFIG__HEADER__TEXT, memberNameOrId));
-
-          List<String> jvmArgsList = memberConfigInfo.getJvmInputArguments();
-          TabularResultData jvmInputArgs = crd.addSection().addSection().addTable();
-
-          for (String jvmArg : jvmArgsList) {
-            jvmInputArgs.accumulate("JVM command line arguments", jvmArg);
-          }
-
-          addSection(crd, memberConfigInfo.getGfePropsSetUsingApi(),
-              "GemFire properties defined using the API");
-          addSection(crd, memberConfigInfo.getGfePropsRuntime(),
-              "GemFire properties defined at the runtime");
-          addSection(crd, memberConfigInfo.getGfePropsSetFromFile(),
-              "GemFire properties defined with the property file");
-          addSection(crd, memberConfigInfo.getGfePropsSetWithDefaults(),
-              "GemFire properties using default values");
-          addSection(crd, memberConfigInfo.getCacheAttributes(), "Cache attributes");
-
-          List<Map<String, String>> cacheServerAttributesList =
-              memberConfigInfo.getCacheServerAttributes();
-
-          if (cacheServerAttributesList != null && !cacheServerAttributesList.isEmpty()) {
-            SectionResultData cacheServerSection = crd.addSection();
-            cacheServerSection.setHeader("Cache-server attributes");
-
-            for (Map<String, String> cacheServerAttributes : cacheServerAttributesList) {
-              addSubSection(cacheServerSection, cacheServerAttributes, "");
-            }
-          }
-          result = ResultBuilder.buildResult(crd);
-        }
-
-      } else {
-        ErrorResultData erd = ResultBuilder.createErrorResultData();
-        erd.addLine(CliStrings.format(CliStrings.DESCRIBE_CONFIG__MEMBER__NOT__FOUND,
-            new Object[] {memberNameOrId}));
-        result = ResultBuilder.buildResult(erd);
-      }
-    } catch (FunctionInvocationTargetException e) {
-      result = ResultBuilder.createGemFireErrorResult(CliStrings
-          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_CONFIG));
-    } catch (Exception e) {
-      ErrorResultData erd = ResultBuilder.createErrorResultData();
-      erd.addLine(e.getMessage());
-      result = ResultBuilder.buildResult(erd);
-    }
-    return result;
-  }
-
-
-  private void addSection(CompositeResultData crd, Map<String, String> attrMap, String headerText) {
-    if (attrMap != null && !attrMap.isEmpty()) {
-      SectionResultData section = crd.addSection();
-      section.setHeader(headerText);
-      section.addSeparator('.');
-      Set<String> attributes = new TreeSet<>(attrMap.keySet());
-
-      for (String attribute : attributes) {
-        String attributeValue = attrMap.get(attribute);
-        section.addData(attribute, attributeValue);
-      }
-    }
-  }
-
-  private void addSubSection(SectionResultData section, Map<String, String> attrMap,
-      String headerText) {
-    if (!attrMap.isEmpty()) {
-      SectionResultData subSection = section.addSection();
-      Set<String> attributes = new TreeSet<>(attrMap.keySet());
-      subSection.setHeader(headerText);
-
-      for (String attribute : attributes) {
-        String attributeValue = attrMap.get(attribute);
-        subSection.addData(attribute, attributeValue);
-      }
-    }
-  }
-
-  /**
-   * Export the cache configuration in XML format.
-   *
-   * @param member Member for which to write the configuration
-   * @param group Group or groups for which to write the configuration
-   * @return Results of the attempt to write the configuration
-   */
-  @CliCommand(value = {CliStrings.EXPORT_CONFIG}, help = CliStrings.EXPORT_CONFIG__HELP)
-  @CliMetaData(
-      interceptor = "org.apache.geode.management.internal.cli.commands.ConfigCommands$Interceptor",
-      relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result exportConfig(
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          optionContext = ConverterHint.ALL_MEMBER_IDNAME,
-          help = CliStrings.EXPORT_CONFIG__MEMBER__HELP) String[] member,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.EXPORT_CONFIG__GROUP__HELP) String[] group,
-      @CliOption(key = {CliStrings.EXPORT_CONFIG__DIR},
-          help = CliStrings.EXPORT_CONFIG__DIR__HELP) String dir) {
-    InfoResultData infoData = ResultBuilder.createInfoResultData();
-
-    Set<DistributedMember> targetMembers = CliUtil.findMembers(group, member);
-    if (targetMembers.isEmpty()) {
-      return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-    }
-
-    try {
-      ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(this.exportConfigFunction, null, targetMembers);
-      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
-      for (CliFunctionResult result : results) {
-        if (result.getThrowable() != null) {
-          infoData.addLine(CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__EXCEPTION,
-              result.getMemberIdOrName(), result.getThrowable()));
-        } else if (result.isSuccessful()) {
-          String cacheFileName = result.getMemberIdOrName() + "-cache.xml";
-          String propsFileName = result.getMemberIdOrName() + "-gf.properties";
-          String[] fileContent = (String[]) result.getSerializables();
-          infoData.addAsFile(cacheFileName, fileContent[0], "Downloading Cache XML file: {0}",
-              false);
-          infoData.addAsFile(propsFileName, fileContent[1], "Downloading properties file: {0}",
-              false);
-        }
-      }
-      return ResultBuilder.buildResult(infoData);
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      th.printStackTrace(System.err);
-      return ResultBuilder
-          .createGemFireErrorResult(CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__EXCEPTION,
-              th.getClass().getName() + ": " + th.getMessage()));
-    }
-  }
-
-
-  @CliCommand(value = {CliStrings.ALTER_RUNTIME_CONFIG},
-      help = CliStrings.ALTER_RUNTIME_CONFIG__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG},
-      interceptor = "org.apache.geode.management.internal.cli.commands.ConfigCommands$AlterRuntimeInterceptor")
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
-  public Result alterRuntimeConfig(
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          optionContext = ConverterHint.ALL_MEMBER_IDNAME,
-          help = CliStrings.ALTER_RUNTIME_CONFIG__MEMBER__HELP) String[] memberNameOrId,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.ALTER_RUNTIME_CONFIG__MEMBER__HELP) String[] group,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT__HELP) Integer archiveDiskSpaceLimit,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT__HELP) Integer archiveFileSizeLimit,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT__HELP) Integer logDiskSpaceLimit,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT__HELP) Integer logFileSizeLimit,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL},
-          optionContext = ConverterHint.LOG_LEVEL,
-          help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL__HELP) String logLevel,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE__HELP) String statisticArchiveFile,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE__HELP) Integer statisticSampleRate,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED__HELP) Boolean statisticSamplingEnabled,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ},
-          specifiedDefaultValue = "false",
-          help = CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ__HELP) Boolean setCopyOnRead,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE__HELP) Integer lockLease,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT__HELP) Integer lockTimeout,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL__HELP) Integer messageSyncInterval,
-      @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT},
-          help = CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT__HELP) Integer searchTimeout) {
-
-    Map<String, String> runTimeDistributionConfigAttributes = new HashMap<>();
-    Map<String, String> rumTimeCacheAttributes = new HashMap<>();
-    Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
-    if (targetMembers.isEmpty()) {
-      return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-    }
-
-    if (archiveDiskSpaceLimit != null) {
-      runTimeDistributionConfigAttributes.put(
-          CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT,
-          archiveDiskSpaceLimit.toString());
-    }
-
-    if (archiveFileSizeLimit != null) {
-      runTimeDistributionConfigAttributes.put(
-          CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT,
-          archiveFileSizeLimit.toString());
-    }
-
-    if (logDiskSpaceLimit != null) {
-      runTimeDistributionConfigAttributes.put(
-          CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, logDiskSpaceLimit.toString());
-    }
-
-    if (logFileSizeLimit != null) {
-      runTimeDistributionConfigAttributes.put(
-          CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT, logFileSizeLimit.toString());
-    }
-
-    if (logLevel != null && !logLevel.isEmpty()) {
-      runTimeDistributionConfigAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL,
-          logLevel);
-    }
-
-    if (statisticArchiveFile != null && !statisticArchiveFile.isEmpty()) {
-      runTimeDistributionConfigAttributes
-          .put(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE, statisticArchiveFile);
-    }
-
-    if (statisticSampleRate != null) {
-      runTimeDistributionConfigAttributes.put(
-          CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE, statisticSampleRate.toString());
-    }
-
-    if (statisticSamplingEnabled != null) {
-      runTimeDistributionConfigAttributes.put(STATISTIC_SAMPLING_ENABLED,
-          statisticSamplingEnabled.toString());
-    }
-
-
-    // Attributes that are set on the cache.
-    if (setCopyOnRead != null) {
-      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ,
-          setCopyOnRead.toString());
-    }
-
-    if (lockLease != null && lockLease > 0 && lockLease < Integer.MAX_VALUE) {
-      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE,
-          lockLease.toString());
-    }
-
-    if (lockTimeout != null && lockTimeout > 0 && lockTimeout < Integer.MAX_VALUE) {
-      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT,
-          lockTimeout.toString());
-    }
-
-    if (messageSyncInterval != null && messageSyncInterval > 0
-        && messageSyncInterval < Integer.MAX_VALUE) {
-      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL,
-          messageSyncInterval.toString());
-    }
-
-    if (searchTimeout != null && searchTimeout > 0 && searchTimeout < Integer.MAX_VALUE) {
-      rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT,
-          searchTimeout.toString());
-    }
-
-    if (runTimeDistributionConfigAttributes.isEmpty() && rumTimeCacheAttributes.isEmpty()) {
-      return ResultBuilder
-          .createUserErrorResult(CliStrings.ALTER_RUNTIME_CONFIG__RELEVANT__OPTION__MESSAGE);
-    }
-
-    Map<String, String> allRunTimeAttributes = new HashMap<>();
-    allRunTimeAttributes.putAll(runTimeDistributionConfigAttributes);
-    allRunTimeAttributes.putAll(rumTimeCacheAttributes);
-
-    ResultCollector<?, ?> rc =
-        CliUtil.executeFunction(alterRunTimeConfigFunction, allRunTimeAttributes, targetMembers);
-    List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-    Set<String> successfulMembers = new TreeSet<>();
-    Set<String> errorMessages = new TreeSet<>();
-
-    for (CliFunctionResult result : results) {
-      if (result.getThrowable() != null) {
-        logger.info("Function failed: " + result.getThrowable());
-        errorMessages.add(result.getThrowable().getMessage());
-      } else {
-        successfulMembers.add(result.getMemberIdOrName());
-      }
-    }
-    final String lineSeparator = System.getProperty("line.separator");
-    if (!successfulMembers.isEmpty()) {
-      StringBuilder successMessageBuilder = new StringBuilder();
-
-      successMessageBuilder.append(CliStrings.ALTER_RUNTIME_CONFIG__SUCCESS__MESSAGE);
-      successMessageBuilder.append(lineSeparator);
-
-      for (String member : successfulMembers) {
-        successMessageBuilder.append(member);
-        successMessageBuilder.append(lineSeparator);
-      }
-
-      Properties properties = new Properties();
-      properties.putAll(runTimeDistributionConfigAttributes);
-
-      Result result = ResultBuilder.createInfoResult(successMessageBuilder.toString());
-
-      // Set the Cache attributes to be modified
-      final XmlEntity xmlEntity = XmlEntity.builder().withType(CacheXml.CACHE)
-          .withAttributes(rumTimeCacheAttributes).build();
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().modifyXmlAndProperties(properties, xmlEntity, group));
-      return result;
-    } else {
-      StringBuilder errorMessageBuilder = new StringBuilder();
-      errorMessageBuilder.append("Following errors occurred while altering runtime config");
-      errorMessageBuilder.append(lineSeparator);
-
-      for (String errorMessage : errorMessages) {
-        errorMessageBuilder.append(errorMessage);
-        errorMessageBuilder.append(lineSeparator);
-      }
-      return ResultBuilder.createUserErrorResult(errorMessageBuilder.toString());
-    }
-  }
-
-  public static class AlterRuntimeInterceptor extends AbstractCliAroundInterceptor {
-    @Override
-    public Result preExecution(GfshParseResult parseResult) {
-      Map<String, String> arguments = parseResult.getParamValueStrings();
-      // validate log level
-      String logLevel = arguments.get("log-level");
-      if (StringUtils.isNotBlank(logLevel) && (LogLevel.getLevel(logLevel) == null)) {
-        return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
-      }
-
-      return ResultBuilder.createInfoResult("");
-    }
-  }
-
-  /**
-   * Interceptor used by gfsh to intercept execution of export config command at "shell".
-   */
-  public static class Interceptor extends AbstractCliAroundInterceptor {
-    private String saveDirString;
-
-    @Override
-    public Result preExecution(GfshParseResult parseResult) {
-      Map<String, String> paramValueMap = parseResult.getParamValueStrings();
-      String dir = paramValueMap.get("dir");
-      dir = (dir == null) ? null : dir.trim();
-
-      File saveDirFile = new File(".");
-      if (dir != null && !dir.isEmpty()) {
-        saveDirFile = new File(dir);
-        if (saveDirFile.exists()) {
-          if (!saveDirFile.isDirectory())
-            return ResultBuilder.createGemFireErrorResult(
-                CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__NOT_A_DIRECTORY, dir));
-        } else if (!saveDirFile.mkdirs()) {
-          return ResultBuilder.createGemFireErrorResult(
-              CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__CANNOT_CREATE_DIR, dir));
-        }
-      }
-      try {
-        if (!saveDirFile.canWrite()) {
-          return ResultBuilder.createGemFireErrorResult(CliStrings.format(
-              CliStrings.EXPORT_CONFIG__MSG__NOT_WRITEABLE, saveDirFile.getCanonicalPath()));
-        }
-      } catch (IOException ioex) {
-        return ResultBuilder.createGemFireErrorResult(
-            CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__NOT_WRITEABLE, saveDirFile.getName()));
-      }
-
-      saveDirString = saveDirFile.getAbsolutePath();
-      return ResultBuilder.createInfoResult("OK");
-    }
-
-    @Override
-    public Result postExecution(GfshParseResult parseResult, Result commandResult, Path tempFile) {
-      if (commandResult.hasIncomingFiles()) {
-        try {
-          commandResult.saveIncomingFiles(saveDirString);
-        } catch (IOException ioex) {
-          Gfsh.getCurrentInstance().logSevere("Unable to export config", ioex);
-        }
-      }
-
-      return commandResult;
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
new file mode 100644
index 0000000..824063a
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.MemberConfigurationInfo;
+import org.apache.geode.management.internal.cli.functions.GetMemberConfigInformationFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DescribeConfigCommand implements GfshCommand {
+  private final GetMemberConfigInformationFunction getMemberConfigFunction =
+      new GetMemberConfigInformationFunction();
+
+  @CliCommand(value = {CliStrings.DESCRIBE_CONFIG}, help = CliStrings.DESCRIBE_CONFIG__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result describeConfig(
+      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+          help = CliStrings.DESCRIBE_CONFIG__MEMBER__HELP, mandatory = true) String memberNameOrId,
+      @CliOption(key = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS,
+          help = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS__HELP, unspecifiedDefaultValue = "true",
+          specifiedDefaultValue = "true") boolean hideDefaults) {
+
+    Result result = null;
+    try {
+      DistributedMember targetMember = null;
+
+      if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
+        targetMember = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+      }
+      if (targetMember != null) {
+        ResultCollector<?, ?> rc =
+            CliUtil.executeFunction(getMemberConfigFunction, hideDefaults, targetMember);
+        ArrayList<?> output = (ArrayList<?>) rc.getResult();
+        Object obj = output.get(0);
+
+        if (obj != null && obj instanceof MemberConfigurationInfo) {
+          MemberConfigurationInfo memberConfigInfo = (MemberConfigurationInfo) obj;
+
+          CompositeResultData crd = ResultBuilder.createCompositeResultData();
+          crd.setHeader(
+              CliStrings.format(CliStrings.DESCRIBE_CONFIG__HEADER__TEXT, memberNameOrId));
+
+          List<String> jvmArgsList = memberConfigInfo.getJvmInputArguments();
+          TabularResultData jvmInputArgs = crd.addSection().addSection().addTable();
+
+          for (String jvmArg : jvmArgsList) {
+            jvmInputArgs.accumulate("JVM command line arguments", jvmArg);
+          }
+
+          addSection(crd, memberConfigInfo.getGfePropsSetUsingApi(),
+              "GemFire properties defined using the API");
+          addSection(crd, memberConfigInfo.getGfePropsRuntime(),
+              "GemFire properties defined at the runtime");
+          addSection(crd, memberConfigInfo.getGfePropsSetFromFile(),
+              "GemFire properties defined with the property file");
+          addSection(crd, memberConfigInfo.getGfePropsSetWithDefaults(),
+              "GemFire properties using default values");
+          addSection(crd, memberConfigInfo.getCacheAttributes(), "Cache attributes");
+
+          List<Map<String, String>> cacheServerAttributesList =
+              memberConfigInfo.getCacheServerAttributes();
+
+          if (cacheServerAttributesList != null && !cacheServerAttributesList.isEmpty()) {
+            CompositeResultData.SectionResultData cacheServerSection = crd.addSection();
+            cacheServerSection.setHeader("Cache-server attributes");
+
+            for (Map<String, String> cacheServerAttributes : cacheServerAttributesList) {
+              addSubSection(cacheServerSection, cacheServerAttributes);
+            }
+          }
+          result = ResultBuilder.buildResult(crd);
+        }
+
+      } else {
+        ErrorResultData erd = ResultBuilder.createErrorResultData();
+        erd.addLine(CliStrings.format(CliStrings.DESCRIBE_CONFIG__MEMBER__NOT__FOUND,
+            new Object[] {memberNameOrId}));
+        result = ResultBuilder.buildResult(erd);
+      }
+    } catch (FunctionInvocationTargetException e) {
+      result = ResultBuilder.createGemFireErrorResult(CliStrings
+          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_CONFIG));
+    } catch (Exception e) {
+      ErrorResultData erd = ResultBuilder.createErrorResultData();
+      erd.addLine(e.getMessage());
+      result = ResultBuilder.buildResult(erd);
+    }
+    return result;
+  }
+
+  private void addSection(CompositeResultData crd, Map<String, String> attrMap, String headerText) {
+    if (attrMap != null && !attrMap.isEmpty()) {
+      CompositeResultData.SectionResultData section = crd.addSection();
+      section.setHeader(headerText);
+      section.addSeparator('.');
+      Set<String> attributes = new TreeSet<>(attrMap.keySet());
+
+      for (String attribute : attributes) {
+        String attributeValue = attrMap.get(attribute);
+        section.addData(attribute, attributeValue);
+      }
+    }
+  }
+
+  private void addSubSection(CompositeResultData.SectionResultData section,
+      Map<String, String> attrMap) {
+    if (!attrMap.isEmpty()) {
+      CompositeResultData.SectionResultData subSection = section.addSection();
+      Set<String> attributes = new TreeSet<>(attrMap.keySet());
+      subSection.setHeader("");
+
+      for (String attribute : attributes) {
+        String attributeValue = attrMap.get(attribute);
+        subSection.addData(attribute, attributeValue);
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportConfigCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportConfigCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportConfigCommand.java
new file mode 100644
index 0000000..672ec88
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportConfigCommand.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.ExportConfigFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ExportConfigCommand implements GfshCommand {
+  private final ExportConfigFunction exportConfigFunction = new ExportConfigFunction();
+
+  /**
+   * Export the cache configuration in XML format.
+   *
+   * @param member Member for which to write the configuration
+   * @param group Group or groups for which to write the configuration
+   * @return Results of the attempt to write the configuration
+   */
+  @CliCommand(value = {CliStrings.EXPORT_CONFIG}, help = CliStrings.EXPORT_CONFIG__HELP)
+  @CliMetaData(
+      interceptor = "org.apache.geode.management.internal.cli.commands.ExportConfigCommand$Interceptor",
+      relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result exportConfig(
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+          help = CliStrings.EXPORT_CONFIG__MEMBER__HELP) String[] member,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.EXPORT_CONFIG__GROUP__HELP) String[] group,
+      @CliOption(key = {CliStrings.EXPORT_CONFIG__DIR},
+          help = CliStrings.EXPORT_CONFIG__DIR__HELP) String dir) {
+    InfoResultData infoData = ResultBuilder.createInfoResultData();
+
+    Set<DistributedMember> targetMembers = CliUtil.findMembers(group, member);
+    if (targetMembers.isEmpty()) {
+      return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+    }
+
+    try {
+      ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(this.exportConfigFunction, null, targetMembers);
+      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+      for (CliFunctionResult result : results) {
+        if (result.getThrowable() != null) {
+          infoData.addLine(CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__EXCEPTION,
+              result.getMemberIdOrName(), result.getThrowable()));
+        } else if (result.isSuccessful()) {
+          String cacheFileName = result.getMemberIdOrName() + "-cache.xml";
+          String propsFileName = result.getMemberIdOrName() + "-gf.properties";
+          String[] fileContent = (String[]) result.getSerializables();
+          infoData.addAsFile(cacheFileName, fileContent[0], "Downloading Cache XML file: {0}",
+              false);
+          infoData.addAsFile(propsFileName, fileContent[1], "Downloading properties file: {0}",
+              false);
+        }
+      }
+      return ResultBuilder.buildResult(infoData);
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      th.printStackTrace(System.err);
+      return ResultBuilder
+          .createGemFireErrorResult(CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__EXCEPTION,
+              th.getClass().getName() + ": " + th.getMessage()));
+    }
+  }
+
+  /**
+   * Interceptor used by gfsh to intercept execution of export config command at "shell".
+   */
+  public static class Interceptor extends AbstractCliAroundInterceptor {
+    private String saveDirString;
+
+    @Override
+    public Result preExecution(GfshParseResult parseResult) {
+      Map<String, String> paramValueMap = parseResult.getParamValueStrings();
+      String dir = paramValueMap.get("dir");
+      dir = (dir == null) ? null : dir.trim();
+
+      File saveDirFile = new File(".");
+      if (dir != null && !dir.isEmpty()) {
+        saveDirFile = new File(dir);
+        if (saveDirFile.exists()) {
+          if (!saveDirFile.isDirectory())
+            return ResultBuilder.createGemFireErrorResult(
+                CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__NOT_A_DIRECTORY, dir));
+        } else if (!saveDirFile.mkdirs()) {
+          return ResultBuilder.createGemFireErrorResult(
+              CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__CANNOT_CREATE_DIR, dir));
+        }
+      }
+      try {
+        if (!saveDirFile.canWrite()) {
+          return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+              CliStrings.EXPORT_CONFIG__MSG__NOT_WRITEABLE, saveDirFile.getCanonicalPath()));
+        }
+      } catch (IOException ioex) {
+        return ResultBuilder.createGemFireErrorResult(
+            CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__NOT_WRITEABLE, saveDirFile.getName()));
+      }
+
+      saveDirString = saveDirFile.getAbsolutePath();
+      return ResultBuilder.createInfoResult("OK");
+    }
+
+    @Override
+    public Result postExecution(GfshParseResult parseResult, Result commandResult, Path tempFile) {
+      if (commandResult.hasIncomingFiles()) {
+        try {
+          commandResult.saveIncomingFiles(saveDirString);
+        } catch (IOException ioex) {
+          Gfsh.getCurrentInstance().logSevere("Unable to export config", ioex);
+        }
+      }
+      return commandResult;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java
index 9f06ea3..d223a9f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java
@@ -14,10 +14,9 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-import org.apache.geode.management.internal.web.util.ConvertUtils;
+import java.io.IOException;
+import java.util.concurrent.Callable;
+
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
@@ -27,15 +26,19 @@ import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.multipart.MultipartFile;
 
-import java.io.IOException;
-import java.util.concurrent.Callable;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import org.apache.geode.management.internal.web.util.ConvertUtils;
 
 /**
  * The ConfigCommandsController class implements GemFire Management REST API web service endpoints
  * for the Gfsh Config Commands.
  * <p/>
  * 
- * @see org.apache.geode.management.internal.cli.commands.ConfigCommands
+ * @see org.apache.geode.management.internal.cli.commands.AlterRuntimeConfigCommand
+ * @see org.apache.geode.management.internal.cli.commands.DescribeConfigCommand
+ * @see org.apache.geode.management.internal.cli.commands.ExportConfigCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractMultiPartCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.PathVariable

http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
index 23c5083..f1cb1c7 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
@@ -14,10 +14,8 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-import org.apache.geode.management.internal.web.util.ConvertUtils;
+import java.io.IOException;
+
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
@@ -25,14 +23,19 @@ import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.multipart.MultipartFile;
 
-import java.io.IOException;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import org.apache.geode.management.internal.web.util.ConvertUtils;
 
 /**
  * The DeployCommandsController class implements the GemFire Management REST API web service
  * endpoints for the Gfsh Deploy Commands.
  * <p/>
- * 
- * @see org.apache.geode.management.internal.cli.commands.ConfigCommands
+ *
+ * @see org.apache.geode.management.internal.cli.commands.DeployCommand
+ * @see org.apache.geode.management.internal.cli.commands.UndeployCommand
+ * @see org.apache.geode.management.internal.cli.commands.ListDeployedCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractMultiPartCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.RequestMapping
@@ -61,8 +64,6 @@ public class DeployCommandsController extends AbstractMultiPartCommandsControlle
 
   @RequestMapping(method = RequestMethod.POST, value = "/deployed")
   @ResponseBody
-  // final MultipartHttpServletRequest request
-  // @RequestPart(RESOURCES_REQUEST_PARAMETER) final Resource[] jarFileResources,
   public String deploy(
       @RequestParam(RESOURCES_REQUEST_PARAMETER) final MultipartFile[] jarFileResources,
       @RequestParam(value = CliStrings.GROUP, required = false) final String[] groups,

http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
index 9feac1a..dd9fd24 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
@@ -43,7 +43,7 @@ public class LogLevelInterceptorTest {
   @Before
   public void before() {
     interceptors.add(new ExportLogsInterceptor());
-    interceptors.add(new ConfigCommands.AlterRuntimeInterceptor());
+    interceptors.add(new AlterRuntimeConfigCommand.AlterRuntimeInterceptor());
     interceptors.add(new ChangeLogLevelCommand.ChangeLogLevelCommandInterceptor());
 
     parseResult = Mockito.mock(GfshParseResult.class);

http://git-wip-us.apache.org/repos/asf/geode/blob/3bfe7a20/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index 038e8cf..853853b 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -123,7 +123,7 @@ public class TestCommand {
     createTestCommand("list clients", clusterRead);
     createTestCommand("describe client --clientID=172.16.196.144", clusterRead);
 
-    // ConfigCommands
+    // AlterRuntimeConfigCommand, DescribeConfigCommand, ExportConfigCommand (config commands)
     createTestCommand("alter runtime", clusterManage);
     createTestCommand("describe config --member=Member1", clusterRead);
     createTestCommand("export config --member=member1", clusterRead);


[04/47] geode git commit: GEODE-3436: Restore refactoring of DurableClientCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of DurableClientCommands

* See initial commit GEODE-3259 (440c87f81fab96f9ce38a2d53ded75e5fe8390d7)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 7ff953941dc730f05d059f19014672a3e703fb63
Parents: 3387008
Author: YehEmily <em...@gmail.com>
Authored: Mon Aug 7 11:52:14 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:23 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/CloseDurableCQsCommand.java    |  83 ++++
 .../cli/commands/CloseDurableClientCommand.java |  77 ++++
 .../commands/CountDurableCQEventsCommand.java   |  88 ++++
 .../cli/commands/DurableClientCommands.java     | 420 -------------------
 .../DurableClientCommandsResultBuilder.java     | 164 ++++++++
 .../commands/ListDurableClientCQsCommand.java   | 121 ++++++
 .../DurableClientCommandsController.java        |  15 +-
 .../internal/security/TestCommand.java          |   5 +-
 8 files changed, 545 insertions(+), 428 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/7ff95394/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableCQsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableCQsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableCQsCommand.java
new file mode 100644
index 0000000..61dd914
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableCQsCommand.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.MemberResult;
+import org.apache.geode.management.internal.cli.functions.CloseDurableCqFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CloseDurableCQsCommand implements GfshCommand {
+  DurableClientCommandsResultBuilder builder = new DurableClientCommandsResultBuilder();
+
+  @CliCommand(value = CliStrings.CLOSE_DURABLE_CQS, help = CliStrings.CLOSE_DURABLE_CQS__HELP)
+  @CliMetaData()
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
+  public Result closeDurableCqs(@CliOption(key = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID,
+      mandatory = true,
+      help = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
+
+      @CliOption(key = CliStrings.CLOSE_DURABLE_CQS__NAME, mandatory = true,
+          help = CliStrings.CLOSE_DURABLE_CQS__NAME__HELP) final String cqName,
+
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          help = CliStrings.CLOSE_DURABLE_CQS__MEMBER__HELP,
+          optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
+
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.CLOSE_DURABLE_CQS__GROUP__HELP,
+          optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
+    Result result;
+    try {
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      String[] params = new String[2];
+      params[0] = durableClientId;
+      params[1] = cqName;
+
+      final ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(new CloseDurableCqFunction(), params, targetMembers);
+      final List<MemberResult> results = (List<MemberResult>) rc.getResult();
+      String failureHeader =
+          CliStrings.format(CliStrings.CLOSE_DURABLE_CQS__FAILURE__HEADER, cqName, durableClientId);
+      String successHeader =
+          CliStrings.format(CliStrings.CLOSE_DURABLE_CQS__SUCCESS, cqName, durableClientId);
+      result = builder.buildResult(results, successHeader, failureHeader);
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/7ff95394/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableClientCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableClientCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableClientCommand.java
new file mode 100644
index 0000000..14c9731
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableClientCommand.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.MemberResult;
+import org.apache.geode.management.internal.cli.functions.CloseDurableClientFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CloseDurableClientCommand implements GfshCommand {
+  DurableClientCommandsResultBuilder builder = new DurableClientCommandsResultBuilder();
+
+  @CliCommand(value = CliStrings.CLOSE_DURABLE_CLIENTS,
+      help = CliStrings.CLOSE_DURABLE_CLIENTS__HELP)
+  @CliMetaData()
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
+  public Result closeDurableClient(
+      @CliOption(key = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, mandatory = true,
+          help = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID__HELP) final String durableClientId,
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          help = CliStrings.CLOSE_DURABLE_CLIENTS__MEMBER__HELP,
+          optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
+          optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
+
+    Result result;
+    try {
+
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      final ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(new CloseDurableClientFunction(), durableClientId, targetMembers);
+      final List<MemberResult> results = (List<MemberResult>) rc.getResult();
+      String failureHeader =
+          CliStrings.format(CliStrings.CLOSE_DURABLE_CLIENTS__FAILURE__HEADER, durableClientId);
+      String successHeader =
+          CliStrings.format(CliStrings.CLOSE_DURABLE_CLIENTS__SUCCESS, durableClientId);
+      result = builder.buildResult(results, successHeader, failureHeader);
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/7ff95394/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CountDurableCQEventsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CountDurableCQEventsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CountDurableCQEventsCommand.java
new file mode 100644
index 0000000..8ebc4da
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CountDurableCQEventsCommand.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.SubscriptionQueueSizeResult;
+import org.apache.geode.management.internal.cli.functions.GetSubscriptionQueueSizeFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CountDurableCQEventsCommand implements GfshCommand {
+  DurableClientCommandsResultBuilder builder = new DurableClientCommandsResultBuilder();
+
+  @CliCommand(value = CliStrings.COUNT_DURABLE_CQ_EVENTS,
+      help = CliStrings.COUNT_DURABLE_CQ_EVENTS__HELP)
+  @CliMetaData()
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result countDurableCqEvents(
+      @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, mandatory = true,
+          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
+      @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME,
+          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME__HELP) final String cqName,
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__MEMBER__HELP,
+          optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
+          optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
+
+    Result result;
+    try {
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      String[] params = new String[2];
+      params[0] = durableClientId;
+      params[1] = cqName;
+      final ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(new GetSubscriptionQueueSizeFunction(), params, targetMembers);
+      final List<SubscriptionQueueSizeResult> funcResults =
+          (List<SubscriptionQueueSizeResult>) rc.getResult();
+
+      String queueSizeColumnName;
+
+      if (cqName != null && !cqName.isEmpty()) {
+        queueSizeColumnName = CliStrings
+            .format(CliStrings.COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT, cqName);
+      } else {
+        queueSizeColumnName = CliStrings.format(
+            CliStrings.COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT, durableClientId);
+      }
+      result = builder.buildTableResultForQueueSize(funcResults, queueSizeColumnName);
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/7ff95394/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
deleted file mode 100644
index c5d859e..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
+++ /dev/null
@@ -1,420 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.DurableCqNamesResult;
-import org.apache.geode.management.internal.cli.domain.MemberResult;
-import org.apache.geode.management.internal.cli.domain.SubscriptionQueueSizeResult;
-import org.apache.geode.management.internal.cli.functions.CloseDurableClientFunction;
-import org.apache.geode.management.internal.cli.functions.CloseDurableCqFunction;
-import org.apache.geode.management.internal.cli.functions.GetSubscriptionQueueSizeFunction;
-import org.apache.geode.management.internal.cli.functions.ListDurableCqNamesFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.geode.security.ResourcePermission.Target;
-
-/**
- * The DurableClientCommands class encapsulates all GemFire shell (Gfsh) commands related to durable
- * clients and cqs defined in GemFire.
- * </p>
- */
-@SuppressWarnings("unused")
-public class DurableClientCommands implements GfshCommand {
-
-  private static final ListDurableCqNamesFunction listDurableCqNamesFunction =
-      new ListDurableCqNamesFunction();
-  private static final CloseDurableClientFunction closeDurableClientFunction =
-      new CloseDurableClientFunction();
-  private static final CloseDurableCqFunction closeDurableCqFunction = new CloseDurableCqFunction();
-  private static final GetSubscriptionQueueSizeFunction countDurableCqEvents =
-      new GetSubscriptionQueueSizeFunction();
-
-  @CliCommand(value = CliStrings.LIST_DURABLE_CQS, help = CliStrings.LIST_DURABLE_CQS__HELP)
-  @CliMetaData()
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result listDurableClientCqs(
-      @CliOption(key = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, mandatory = true,
-          help = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID__HELP) final String durableClientId,
-
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          help = CliStrings.LIST_DURABLE_CQS__MEMBER__HELP,
-          optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
-
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.LIST_DURABLE_CQS__GROUP__HELP,
-          optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
-    Result result;
-    try {
-
-      boolean noResults = true;
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      final ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(new ListDurableCqNamesFunction(), durableClientId, targetMembers);
-      final List<DurableCqNamesResult> results = (List<DurableCqNamesResult>) rc.getResult();
-      Map<String, List<String>> memberCqNamesMap = new TreeMap<>();
-      Map<String, List<String>> errorMessageNodes = new HashMap<>();
-      Map<String, List<String>> exceptionMessageNodes = new HashMap<>();
-
-      for (DurableCqNamesResult memberResult : results) {
-        if (memberResult != null) {
-          if (memberResult.isSuccessful()) {
-            memberCqNamesMap.put(memberResult.getMemberNameOrId(), memberResult.getCqNamesList());
-          } else {
-            if (memberResult.isOpPossible()) {
-              groupByMessage(memberResult.getExceptionMessage(), memberResult.getMemberNameOrId(),
-                  exceptionMessageNodes);
-            } else {
-              groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
-                  errorMessageNodes);
-            }
-          }
-        }
-      }
-
-      if (!memberCqNamesMap.isEmpty()) {
-        TabularResultData table = ResultBuilder.createTabularResultData();
-        Set<String> members = memberCqNamesMap.keySet();
-
-        for (String member : members) {
-          boolean isFirst = true;
-          List<String> cqNames = memberCqNamesMap.get(member);
-          for (String cqName : cqNames) {
-            if (isFirst) {
-              isFirst = false;
-              table.accumulate(CliStrings.MEMBER, member);
-            } else {
-              table.accumulate(CliStrings.MEMBER, "");
-            }
-            table.accumulate(CliStrings.LIST_DURABLE_CQS__NAME, cqName);
-          }
-        }
-        result = ResultBuilder.buildResult(table);
-      } else {
-        String errorHeader =
-            CliStrings.format(CliStrings.LIST_DURABLE_CQS__FAILURE__HEADER, durableClientId);
-        result = ResultBuilder.buildResult(
-            buildFailureData(null, exceptionMessageNodes, errorMessageNodes, errorHeader));
-      }
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.COUNT_DURABLE_CQ_EVENTS,
-      help = CliStrings.COUNT_DURABLE_CQ_EVENTS__HELP)
-  @CliMetaData()
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result countDurableCqEvents(
-      @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, mandatory = true,
-          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
-      @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME,
-          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME__HELP) final String cqName,
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__MEMBER__HELP,
-          optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
-          optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
-
-    Result result;
-    try {
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      String[] params = new String[2];
-      params[0] = durableClientId;
-      params[1] = cqName;
-      final ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(new GetSubscriptionQueueSizeFunction(), params, targetMembers);
-      final List<SubscriptionQueueSizeResult> funcResults =
-          (List<SubscriptionQueueSizeResult>) rc.getResult();
-
-      String queueSizeColumnName;
-
-      if (cqName != null && !cqName.isEmpty()) {
-        queueSizeColumnName = CliStrings
-            .format(CliStrings.COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT, cqName);
-      } else {
-        queueSizeColumnName = CliStrings.format(
-            CliStrings.COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT, durableClientId);
-      }
-      result = buildTableResultForQueueSize(funcResults, queueSizeColumnName);
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.CLOSE_DURABLE_CLIENTS,
-      help = CliStrings.CLOSE_DURABLE_CLIENTS__HELP)
-  @CliMetaData()
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.QUERY)
-  public Result closeDurableClient(
-      @CliOption(key = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, mandatory = true,
-          help = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID__HELP) final String durableClientId,
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          help = CliStrings.CLOSE_DURABLE_CLIENTS__MEMBER__HELP,
-          optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
-          optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
-
-    Result result;
-    try {
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      final ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(new CloseDurableClientFunction(), durableClientId, targetMembers);
-      final List<MemberResult> results = (List<MemberResult>) rc.getResult();
-      String failureHeader =
-          CliStrings.format(CliStrings.CLOSE_DURABLE_CLIENTS__FAILURE__HEADER, durableClientId);
-      String successHeader =
-          CliStrings.format(CliStrings.CLOSE_DURABLE_CLIENTS__SUCCESS, durableClientId);
-      result = buildResult(results, successHeader, failureHeader);
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-    return result;
-  }
-
-
-  @CliCommand(value = CliStrings.CLOSE_DURABLE_CQS, help = CliStrings.CLOSE_DURABLE_CQS__HELP)
-  @CliMetaData()
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.QUERY)
-  public Result closeDurableCqs(@CliOption(key = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID,
-      mandatory = true,
-      help = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
-
-      @CliOption(key = CliStrings.CLOSE_DURABLE_CQS__NAME, mandatory = true,
-          help = CliStrings.CLOSE_DURABLE_CQS__NAME__HELP) final String cqName,
-
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          help = CliStrings.CLOSE_DURABLE_CQS__MEMBER__HELP,
-          optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
-
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          help = CliStrings.CLOSE_DURABLE_CQS__GROUP__HELP,
-          optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
-    Result result;
-    try {
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      String[] params = new String[2];
-      params[0] = durableClientId;
-      params[1] = cqName;
-
-      final ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(new CloseDurableCqFunction(), params, targetMembers);
-      final List<MemberResult> results = (List<MemberResult>) rc.getResult();
-      String failureHeader =
-          CliStrings.format(CliStrings.CLOSE_DURABLE_CQS__FAILURE__HEADER, cqName, durableClientId);
-      String successHeader =
-          CliStrings.format(CliStrings.CLOSE_DURABLE_CQS__SUCCESS, cqName, durableClientId);
-      result = buildResult(results, successHeader, failureHeader);
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-    return result;
-  }
-
-
-  private Result buildResult(List<MemberResult> results, String successHeader,
-      String failureHeader) {
-    Result result;
-    boolean failure = true;
-    boolean partialFailure = false;
-    Map<String, List<String>> errorMap = new HashMap<>();
-    Map<String, List<String>> successMap = new HashMap<>();
-    Map<String, List<String>> exceptionMap = new HashMap<>();
-
-    /*
-     * Aggregate the results from the members
-     */
-    for (MemberResult memberResult : results) {
-
-      if (memberResult.isSuccessful()) {
-        failure = false;
-        groupByMessage(memberResult.getSuccessMessage(), memberResult.getMemberNameOrId(),
-            successMap);
-      } else {
-
-        if (memberResult.isOpPossible()) {
-          partialFailure = true;
-          groupByMessage(memberResult.getExceptionMessage(), memberResult.getMemberNameOrId(),
-              exceptionMap);
-
-        } else {
-          groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
-              errorMap);
-        }
-      }
-    }
-
-    if (!failure && !partialFailure) {
-      result = ResultBuilder.buildResult(buildSuccessData(successMap));
-    } else {
-      result = ResultBuilder
-          .buildResult(buildFailureData(successMap, exceptionMap, errorMap, failureHeader));
-    }
-    return result;
-  }
-
-  private Result buildTableResultForQueueSize(List<SubscriptionQueueSizeResult> results,
-      String queueSizeColumnName) {
-    Result result;
-    boolean failure = true;
-
-    Map<String, List<String>> failureMap = new HashMap<>();
-    Map<String, Long> memberQueueSizeTable = new TreeMap<>();
-
-    /*
-     * Aggregate the results from the members
-     */
-    for (SubscriptionQueueSizeResult memberResult : results) {
-
-      if (memberResult.isSuccessful()) {
-        failure = false;
-        memberQueueSizeTable.put(memberResult.getMemberNameOrId(),
-            memberResult.getSubscriptionQueueSize());
-      } else {
-        groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
-            failureMap);
-      }
-    }
-
-    if (!failure) {
-      TabularResultData table = ResultBuilder.createTabularResultData();
-
-      Set<String> members = memberQueueSizeTable.keySet();
-
-      for (String member : members) {
-        long queueSize = memberQueueSizeTable.get(member);
-        table.accumulate(CliStrings.MEMBER, member);
-        table.accumulate(queueSizeColumnName, queueSize);
-      }
-      result = ResultBuilder.buildResult(table);
-
-    } else {
-      ErrorResultData erd = ResultBuilder.createErrorResultData();
-      buildErrorResult(erd, failureMap);
-      result = ResultBuilder.buildResult(erd);
-    }
-    return result;
-  }
-
-  private void groupByMessage(String message, String memberNameOrId,
-      Map<String, List<String>> map) {
-    List<String> members = map.get(message);
-
-    if (members == null) {
-      members = new LinkedList<>();
-    }
-    members.add(memberNameOrId);
-    map.put(message, members);
-  }
-
-
-  private InfoResultData buildSuccessData(Map<String, List<String>> successMap) {
-    InfoResultData ird = ResultBuilder.createInfoResultData();
-    Set<String> successMessages = successMap.keySet();
-
-    for (String successMessage : successMessages) {
-      ird.addLine(CliStrings.format(CliStrings.ACTION_SUCCEEDED_ON_MEMBER, successMessage));
-
-      List<String> successfulMembers = successMap.get(successMessage);
-      int num = 0;
-      for (String member : successfulMembers) {
-        ird.addLine("" + ++num + "." + member);
-      }
-      ird.addLine("\n");
-    }
-    return ird;
-  }
-
-  private ErrorResultData buildFailureData(Map<String, List<String>> successMap,
-      Map<String, List<String>> exceptionMap, Map<String, List<String>> errorMap,
-      String errorHeader) {
-    ErrorResultData erd = ResultBuilder.createErrorResultData();
-    buildErrorResult(erd, successMap);
-    erd.addLine("\n");
-    erd.addLine(errorHeader);
-    buildErrorResult(erd, exceptionMap);
-    buildErrorResult(erd, errorMap);
-    return erd;
-  }
-
-  private void buildErrorResult(ErrorResultData erd, Map<String, List<String>> resultMap) {
-    if (resultMap != null && !resultMap.isEmpty()) {
-      Set<String> messages = resultMap.keySet();
-
-      for (String message : messages) {
-        erd.addLine("\n");
-        erd.addLine(message);
-        erd.addLine(CliStrings.OCCURRED_ON_MEMBERS);
-        List<String> members = resultMap.get(message);
-        int num = 0;
-        for (String member : members) {
-          ++num;
-          erd.addLine("" + num + "." + member);
-        }
-      }
-    }
-  }
-}
-

http://git-wip-us.apache.org/repos/asf/geode/blob/7ff95394/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsResultBuilder.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsResultBuilder.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsResultBuilder.java
new file mode 100644
index 0000000..743602a
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsResultBuilder.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.domain.MemberResult;
+import org.apache.geode.management.internal.cli.domain.SubscriptionQueueSizeResult;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+
+public class DurableClientCommandsResultBuilder {
+  public Result buildResult(List<MemberResult> results, String successHeader,
+      String failureHeader) {
+    Result result;
+    boolean failure = true;
+    boolean partialFailure = false;
+    Map<String, List<String>> errorMap = new HashMap<>();
+    Map<String, List<String>> successMap = new HashMap<>();
+    Map<String, List<String>> exceptionMap = new HashMap<>();
+
+    // Aggregate the results from the members
+    for (MemberResult memberResult : results) {
+      if (memberResult.isSuccessful()) {
+        failure = false;
+        groupByMessage(memberResult.getSuccessMessage(), memberResult.getMemberNameOrId(),
+            successMap);
+      } else {
+        if (memberResult.isOpPossible()) {
+          partialFailure = true;
+          groupByMessage(memberResult.getExceptionMessage(), memberResult.getMemberNameOrId(),
+              exceptionMap);
+        } else {
+          groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
+              errorMap);
+        }
+      }
+    }
+
+    if (!failure && !partialFailure) {
+      result = ResultBuilder.buildResult(buildSuccessData(successMap));
+    } else {
+      result = ResultBuilder
+          .buildResult(buildFailureData(successMap, exceptionMap, errorMap, failureHeader));
+    }
+    return result;
+  }
+
+  Result buildTableResultForQueueSize(List<SubscriptionQueueSizeResult> results,
+      String queueSizeColumnName) {
+    Result result;
+    boolean failure = true;
+
+    Map<String, List<String>> failureMap = new HashMap<>();
+    Map<String, Long> memberQueueSizeTable = new TreeMap<>();
+
+    // Aggregate the results from the members
+    for (SubscriptionQueueSizeResult memberResult : results) {
+      if (memberResult.isSuccessful()) {
+        failure = false;
+        memberQueueSizeTable.put(memberResult.getMemberNameOrId(),
+            memberResult.getSubscriptionQueueSize());
+      } else {
+        groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
+            failureMap);
+      }
+    }
+
+    if (!failure) {
+      TabularResultData table = ResultBuilder.createTabularResultData();
+      Set<String> members = memberQueueSizeTable.keySet();
+
+      for (String member : members) {
+        long queueSize = memberQueueSizeTable.get(member);
+        table.accumulate(CliStrings.MEMBER, member);
+        table.accumulate(queueSizeColumnName, queueSize);
+      }
+      result = ResultBuilder.buildResult(table);
+    } else {
+      ErrorResultData erd = ResultBuilder.createErrorResultData();
+      buildErrorResult(erd, failureMap);
+      result = ResultBuilder.buildResult(erd);
+    }
+    return result;
+  }
+
+  void groupByMessage(String message, String memberNameOrId, Map<String, List<String>> map) {
+    List<String> members = map.get(message);
+    if (members == null) {
+      members = new LinkedList<>();
+    }
+    members.add(memberNameOrId);
+    map.put(message, members);
+  }
+
+
+  private InfoResultData buildSuccessData(Map<String, List<String>> successMap) {
+    InfoResultData ird = ResultBuilder.createInfoResultData();
+    Set<String> successMessages = successMap.keySet();
+
+    for (String successMessage : successMessages) {
+      ird.addLine(CliStrings.format(CliStrings.ACTION_SUCCEEDED_ON_MEMBER, successMessage));
+      List<String> successfulMembers = successMap.get(successMessage);
+      int num = 0;
+      for (String member : successfulMembers) {
+        ird.addLine("" + ++num + "." + member);
+      }
+      ird.addLine("\n");
+    }
+    return ird;
+  }
+
+  ErrorResultData buildFailureData(Map<String, List<String>> successMap,
+      Map<String, List<String>> exceptionMap, Map<String, List<String>> errorMap,
+      String errorHeader) {
+    ErrorResultData erd = ResultBuilder.createErrorResultData();
+    buildErrorResult(erd, successMap);
+    erd.addLine("\n");
+    erd.addLine(errorHeader);
+    buildErrorResult(erd, exceptionMap);
+    buildErrorResult(erd, errorMap);
+    return erd;
+  }
+
+  private void buildErrorResult(ErrorResultData erd, Map<String, List<String>> resultMap) {
+    if (resultMap != null && !resultMap.isEmpty()) {
+      Set<String> messages = resultMap.keySet();
+
+      for (String message : messages) {
+        erd.addLine("\n");
+        erd.addLine(message);
+        erd.addLine(CliStrings.OCCURRED_ON_MEMBERS);
+        List<String> members = resultMap.get(message);
+        int num = 0;
+        for (String member : members) {
+          ++num;
+          erd.addLine("" + num + "." + member);
+        }
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/7ff95394/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDurableClientCQsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDurableClientCQsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDurableClientCQsCommand.java
new file mode 100644
index 0000000..011bfde
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDurableClientCQsCommand.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.DurableCqNamesResult;
+import org.apache.geode.management.internal.cli.functions.ListDurableCqNamesFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ListDurableClientCQsCommand implements GfshCommand {
+  DurableClientCommandsResultBuilder builder = new DurableClientCommandsResultBuilder();
+
+  @CliCommand(value = CliStrings.LIST_DURABLE_CQS, help = CliStrings.LIST_DURABLE_CQS__HELP)
+  @CliMetaData()
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result listDurableClientCQs(
+      @CliOption(key = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, mandatory = true,
+          help = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID__HELP) final String durableClientId,
+
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          help = CliStrings.LIST_DURABLE_CQS__MEMBER__HELP,
+          optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
+
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.LIST_DURABLE_CQS__GROUP__HELP,
+          optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
+    Result result;
+    try {
+
+      boolean noResults = true;
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      final ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(new ListDurableCqNamesFunction(), durableClientId, targetMembers);
+      final List<DurableCqNamesResult> results = (List<DurableCqNamesResult>) rc.getResult();
+      Map<String, List<String>> memberCqNamesMap = new TreeMap<>();
+      Map<String, List<String>> errorMessageNodes = new HashMap<>();
+      Map<String, List<String>> exceptionMessageNodes = new HashMap<>();
+
+      for (DurableCqNamesResult memberResult : results) {
+        if (memberResult != null) {
+          if (memberResult.isSuccessful()) {
+            memberCqNamesMap.put(memberResult.getMemberNameOrId(), memberResult.getCqNamesList());
+          } else {
+            if (memberResult.isOpPossible()) {
+              builder.groupByMessage(memberResult.getExceptionMessage(),
+                  memberResult.getMemberNameOrId(), exceptionMessageNodes);
+            } else {
+              builder.groupByMessage(memberResult.getErrorMessage(),
+                  memberResult.getMemberNameOrId(), errorMessageNodes);
+            }
+          }
+        }
+      }
+
+      if (!memberCqNamesMap.isEmpty()) {
+        TabularResultData table = ResultBuilder.createTabularResultData();
+        Set<String> members = memberCqNamesMap.keySet();
+
+        for (String member : members) {
+          boolean isFirst = true;
+          List<String> cqNames = memberCqNamesMap.get(member);
+          for (String cqName : cqNames) {
+            if (isFirst) {
+              isFirst = false;
+              table.accumulate(CliStrings.MEMBER, member);
+            } else {
+              table.accumulate(CliStrings.MEMBER, "");
+            }
+            table.accumulate(CliStrings.LIST_DURABLE_CQS__NAME, cqName);
+          }
+        }
+        result = ResultBuilder.buildResult(table);
+      } else {
+        String errorHeader =
+            CliStrings.format(CliStrings.LIST_DURABLE_CQS__FAILURE__HEADER, durableClientId);
+        result = ResultBuilder.buildResult(
+            builder.buildFailureData(null, exceptionMessageNodes, errorMessageNodes, errorHeader));
+      }
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/7ff95394/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java
index 4562cd5..0e62e71 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java
@@ -14,10 +14,6 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.distributed.ConfigurationProperties;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -25,13 +21,20 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
+import org.apache.geode.distributed.ConfigurationProperties;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+
 /**
  * The DurableClientCommandsController class implements GemFire Management REST API web service
  * endpoints for the durable client/CQs Gfsh commands.
  * <p/>
  * 
- * @see org.apache.geode.management.internal.cli.commands.DurableClientCommands
- * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
+ * @see org.apache.geode.management.internal.cli.commands.CloseDurableClientCommand
+ * @see org.apache.geode.management.internal.cli.commands.CloseDurableCQsCommand
+ * @see org.apache.geode.management.internal.cli.commands.CountDurableCQEventsCommand
+ * @see org.apache.geode.management.internal.cli.commands.ListDurableClientCQsCommand
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.PathVariable
  * @see org.springframework.web.bind.annotation.RequestMapping

http://git-wip-us.apache.org/repos/asf/geode/blob/7ff95394/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index 3456e8c..f681f5c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -171,14 +171,15 @@ public class TestCommand {
     createTestCommand("alter disk-store --name=foo --region=xyz --disk-dirs=bar");
     createTestCommand("destroy disk-store --name=foo", clusterManageDisk);
 
-    // DurableClientCommands
+    // CloseDurableClientCommand, CloseDurableCQsCommand, CountDurableCQEventsCommand,
+    // ListDurableClientCQsCommand
     createTestCommand("close durable-client --durable-client-id=client1", clusterManageQuery);
     createTestCommand("close durable-cq --durable-client-id=client1 --durable-cq-name=cq1",
         clusterManageQuery);
     createTestCommand("show subscription-queue-size --durable-client-id=client1", clusterRead);
     createTestCommand("list durable-cqs --durable-client-id=client1", clusterRead);
 
-    // ExportIMportSharedConfigurationCommands
+    // ExportImportSharedConfigurationCommands
     createTestCommand("export cluster-configuration --zip-file-name=mySharedConfig.zip",
         clusterRead);
     createTestCommand("import cluster-configuration --zip-file-name=value.zip", clusterManage);


[43/47] geode git commit: GEODE-3539: add test for invalid command

Posted by ds...@apache.org.
GEODE-3539: add test for invalid command

* also rework GfshCommandIntegrationTest in assembly module


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

Branch: refs/heads/feature/GEODE-3543
Commit: 17662cd46de7939577b4fc20183319288c655932
Parents: ca0dca5
Author: Jinmei Liao <ji...@pivotal.io>
Authored: Tue Aug 29 15:11:56 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Wed Aug 30 13:37:58 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/GemfireCoreClasspathTest.java  | 101 +++++++++++
 .../commands/GfshCommandIntegrationTest.java    | 177 -------------------
 .../commands/GfshCommandIntegrationTest.java    |  49 +++++
 .../cli/commands/StartMemberUtilsTest.java      |  91 ++++++++++
 4 files changed, 241 insertions(+), 177 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/17662cd4/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireCoreClasspathTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireCoreClasspathTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireCoreClasspathTest.java
new file mode 100644
index 0000000..3546b79
--- /dev/null
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireCoreClasspathTest.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.test.junit.categories.IntegrationTest;
+
+@Category(IntegrationTest.class)
+public class GemfireCoreClasspathTest {
+  @Test
+  public void testGemFireCoreClasspath() throws IOException {
+    File coreDependenciesJar = new File(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME);
+    assertNotNull(coreDependenciesJar);
+    assertTrue(coreDependenciesJar + " is not a file", coreDependenciesJar.isFile());
+    Collection<String> expectedJarDependencies =
+        Arrays.asList("antlr", "commons-io", "commons-lang", "commons-logging", "geode",
+            "jackson-annotations", "jackson-core", "jackson-databind", "jansi", "jline", "snappy",
+            "spring-core", "spring-shell", "jetty-server", "jetty-servlet", "jetty-webapp",
+            "jetty-util", "jetty-http", "servlet-api", "jetty-io", "jetty-security", "jetty-xml");
+    assertJarFileManifestClassPath(coreDependenciesJar, expectedJarDependencies);
+  }
+
+  private void assertJarFileManifestClassPath(final File dependenciesJar,
+      final Collection<String> expectedJarDependencies) throws IOException {
+    JarFile dependenciesJarFile = new JarFile(dependenciesJar);
+    Manifest manifest = dependenciesJarFile.getManifest();
+
+    assertNotNull(manifest);
+
+    Attributes attributes = manifest.getMainAttributes();
+
+    assertNotNull(attributes);
+    assertTrue(attributes.containsKey(Attributes.Name.CLASS_PATH));
+
+    String[] actualJarDependencies = attributes.getValue(Attributes.Name.CLASS_PATH).split(" ");
+
+    assertNotNull(actualJarDependencies);
+    assertTrue(
+        String.format(
+            "Expected the actual number of JAR dependencies to be (%1$d); but was (%2$d)!",
+            expectedJarDependencies.size(), actualJarDependencies.length),
+        actualJarDependencies.length >= expectedJarDependencies.size());
+    // assertTrue(Arrays.asList(actualJarDependencies).containsAll(expectedJarDependencies));
+
+    List<String> actualJarDependenciesList = new ArrayList<>(Arrays.asList(actualJarDependencies));
+    List<String> missingExpectedJarDependenciesList =
+        new ArrayList<>(expectedJarDependencies.size());
+
+    for (String expectedJarDependency : expectedJarDependencies) {
+      boolean containsExpectedJar = false;
+
+      for (int index = 0, size = actualJarDependenciesList.size(); index < size; index++) {
+        if (actualJarDependenciesList.get(index).toLowerCase()
+            .contains(expectedJarDependency.toLowerCase())) {
+          actualJarDependenciesList.remove(index);
+          containsExpectedJar = true;
+          break;
+        }
+      }
+
+      if (!containsExpectedJar) {
+        missingExpectedJarDependenciesList.add(expectedJarDependency);
+      }
+    }
+
+    assertTrue(
+        String.format(
+            "GemFire dependencies JAR file (%1$s) does not contain the expected dependencies (%2$s) in the Manifest Class-Path attribute (%3$s)!",
+            dependenciesJar, missingExpectedJarDependenciesList,
+            attributes.getValue(Attributes.Name.CLASS_PATH)),
+        missingExpectedJarDependenciesList.isEmpty());
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/17662cd4/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
deleted file mode 100644
index 263b12c..0000000
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package org.apache.geode.management.internal.cli.commands;
-
-import static org.assertj.core.api.Java6Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.jar.Attributes;
-import java.util.jar.JarFile;
-import java.util.jar.Manifest;
-
-import org.apache.commons.io.FileUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TemporaryFolder;
-import org.junit.rules.TestName;
-
-import org.apache.geode.internal.util.IOUtils;
-import org.apache.geode.test.junit.categories.IntegrationTest;
-
-@Category(IntegrationTest.class)
-public class GfshCommandIntegrationTest {
-  @Rule
-  public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
-  @Rule
-  public TestName testName = new TestName();
-
-  @Test
-  public void workingDirDefaultsToMemberName() {
-    StartServerCommand startServer = new StartServerCommand();
-    String workingDir = StartMemberUtils.resolveWorkingDir(null, "server1");
-    assertThat(new File(workingDir)).exists();
-    assertThat(workingDir).endsWith("server1");
-  }
-
-  @Test
-  public void workingDirGetsCreatedIfNecessary() throws Exception {
-    File workingDir = temporaryFolder.newFolder("foo");
-    FileUtils.deleteQuietly(workingDir);
-    String workingDirString = workingDir.getAbsolutePath();
-
-    StartServerCommand startServer = new StartServerCommand();
-
-    String resolvedWorkingDir = StartMemberUtils.resolveWorkingDir(workingDirString, "server1");
-    assertThat(new File(resolvedWorkingDir)).exists();
-    assertThat(workingDirString).endsWith("foo");
-  }
-
-  @Test
-  public void testWorkingDirWithRelativePath() throws Exception {
-    Path relativePath = Paths.get("some").resolve("relative").resolve("path");
-    assertThat(relativePath.isAbsolute()).isFalse();
-
-    StartServerCommand startServer = new StartServerCommand();
-
-    String resolvedWorkingDir =
-        StartMemberUtils.resolveWorkingDir(relativePath.toString(), "server1");
-
-    assertThat(resolvedWorkingDir).isEqualTo(relativePath.toAbsolutePath().toString());
-  }
-
-  @Test
-  public void testReadPid() throws IOException {
-    final int expectedPid = 12345;
-
-    File folder = temporaryFolder.newFolder();
-    File pidFile =
-        new File(folder, getClass().getSimpleName() + "_" + testName.getMethodName() + ".pid");
-
-    assertTrue(pidFile.createNewFile());
-
-    pidFile.deleteOnExit();
-    writePid(pidFile, expectedPid);
-
-    final int actualPid = StartMemberUtils.readPid(pidFile);
-
-    assertEquals(expectedPid, actualPid);
-  }
-
-  @Test
-  public void testGemFireCoreClasspath() throws IOException {
-    File coreDependenciesJar = new File(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME);
-    assertNotNull(coreDependenciesJar);
-    assertTrue(coreDependenciesJar + " is not a file", coreDependenciesJar.isFile());
-    Collection<String> expectedJarDependencies =
-        Arrays.asList("antlr", "commons-io", "commons-lang", "commons-logging", "geode",
-            "jackson-annotations", "jackson-core", "jackson-databind", "jansi", "jline", "snappy",
-            "spring-core", "spring-shell", "jetty-server", "jetty-servlet", "jetty-webapp",
-            "jetty-util", "jetty-http", "servlet-api", "jetty-io", "jetty-security", "jetty-xml");
-    assertJarFileManifestClassPath(coreDependenciesJar, expectedJarDependencies);
-  }
-
-  private void assertJarFileManifestClassPath(final File dependenciesJar,
-      final Collection<String> expectedJarDependencies) throws IOException {
-    JarFile dependenciesJarFile = new JarFile(dependenciesJar);
-    Manifest manifest = dependenciesJarFile.getManifest();
-
-    assertNotNull(manifest);
-
-    Attributes attributes = manifest.getMainAttributes();
-
-    assertNotNull(attributes);
-    assertTrue(attributes.containsKey(Attributes.Name.CLASS_PATH));
-
-    String[] actualJarDependencies = attributes.getValue(Attributes.Name.CLASS_PATH).split(" ");
-
-    assertNotNull(actualJarDependencies);
-    assertTrue(
-        String.format(
-            "Expected the actual number of JAR dependencies to be (%1$d); but was (%2$d)!",
-            expectedJarDependencies.size(), actualJarDependencies.length),
-        actualJarDependencies.length >= expectedJarDependencies.size());
-    // assertTrue(Arrays.asList(actualJarDependencies).containsAll(expectedJarDependencies));
-
-    List<String> actualJarDependenciesList = new ArrayList<>(Arrays.asList(actualJarDependencies));
-    List<String> missingExpectedJarDependenciesList =
-        new ArrayList<>(expectedJarDependencies.size());
-
-    for (String expectedJarDependency : expectedJarDependencies) {
-      boolean containsExpectedJar = false;
-
-      for (int index = 0, size = actualJarDependenciesList.size(); index < size; index++) {
-        if (actualJarDependenciesList.get(index).toLowerCase()
-            .contains(expectedJarDependency.toLowerCase())) {
-          actualJarDependenciesList.remove(index);
-          containsExpectedJar = true;
-          break;
-        }
-      }
-
-      if (!containsExpectedJar) {
-        missingExpectedJarDependenciesList.add(expectedJarDependency);
-      }
-    }
-
-    assertTrue(
-        String.format(
-            "GemFire dependencies JAR file (%1$s) does not contain the expected dependencies (%2$s) in the Manifest Class-Path attribute (%3$s)!",
-            dependenciesJar, missingExpectedJarDependenciesList,
-            attributes.getValue(Attributes.Name.CLASS_PATH)),
-        missingExpectedJarDependenciesList.isEmpty());
-  }
-
-  private void writePid(final File pidFile, final int pid) throws IOException {
-    final FileWriter fileWriter = new FileWriter(pidFile, false);
-    fileWriter.write(String.valueOf(pid));
-    fileWriter.write("\n");
-    fileWriter.flush();
-    IOUtils.close(fileWriter);
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/17662cd4/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
new file mode 100644
index 0000000..6aebdfe
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.test.dunit.rules.GfshShellConnectionRule;
+import org.apache.geode.test.dunit.rules.LocatorStarterRule;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+
+@Category(IntegrationTest.class)
+public class GfshCommandIntegrationTest {
+  @ClassRule
+  public static LocatorStarterRule locator = new LocatorStarterRule().withAutoStart();
+
+  @Rule
+  public GfshShellConnectionRule gfsh = new GfshShellConnectionRule();
+
+  @Test
+  public void invalidCommandWhenNotConnected() throws Exception {
+    String result = gfsh.execute("abc");
+    assertThat(result).contains("Command 'abc' not found");
+  }
+
+  @Test
+  public void invalidCommandWhenConnected() throws Exception {
+    gfsh.connectAndVerify(locator);
+    String result = gfsh.execute("abc");
+    assertThat(result).contains("Command 'abc' not found");
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/17662cd4/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartMemberUtilsTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartMemberUtilsTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartMemberUtilsTest.java
new file mode 100644
index 0000000..d84f788
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartMemberUtilsTest.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import org.apache.commons.io.FileUtils;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
+
+import org.apache.geode.internal.util.IOUtils;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+
+@Category(IntegrationTest.class)
+public class StartMemberUtilsTest {
+
+  @Rule
+  public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+  @Test
+  public void workingDirDefaultsToMemberName() {
+    String workingDir = StartMemberUtils.resolveWorkingDir(null, "server1");
+    assertThat(new File(workingDir)).exists();
+    assertThat(workingDir).endsWith("server1");
+  }
+
+  @Test
+  public void workingDirGetsCreatedIfNecessary() throws Exception {
+    File workingDir = temporaryFolder.newFolder("foo");
+    FileUtils.deleteQuietly(workingDir);
+    String workingDirString = workingDir.getAbsolutePath();
+    String resolvedWorkingDir = StartMemberUtils.resolveWorkingDir(workingDirString, "server1");
+    assertThat(new File(resolvedWorkingDir)).exists();
+    assertThat(workingDirString).endsWith("foo");
+  }
+
+  @Test
+  public void testWorkingDirWithRelativePath() throws Exception {
+    Path relativePath = Paths.get("some").resolve("relative").resolve("path");
+    assertThat(relativePath.isAbsolute()).isFalse();
+    String resolvedWorkingDir =
+        StartMemberUtils.resolveWorkingDir(relativePath.toString(), "server1");
+    assertThat(resolvedWorkingDir).isEqualTo(relativePath.toAbsolutePath().toString());
+  }
+
+  @Test
+  public void testReadPid() throws IOException {
+    final int expectedPid = 12345;
+    File folder = temporaryFolder.newFolder();
+    File pidFile = new File(folder, "my.pid");
+
+    assertTrue(pidFile.createNewFile());
+
+    pidFile.deleteOnExit();
+    writePid(pidFile, expectedPid);
+
+    final int actualPid = StartMemberUtils.readPid(pidFile);
+    assertEquals(expectedPid, actualPid);
+  }
+
+  private void writePid(final File pidFile, final int pid) throws IOException {
+    final FileWriter fileWriter = new FileWriter(pidFile, false);
+    fileWriter.write(String.valueOf(pid));
+    fileWriter.write("\n");
+    fileWriter.flush();
+    IOUtils.close(fileWriter);
+  }
+}


[33/47] geode git commit: GEODE-3529 move new client/server security classes to a different package

Posted by ds...@apache.org.
GEODE-3529 move new client/server security classes to a different package

The new classes/interfaces have been moved to org.apache.geode.security.server.

A package.html is now provided that describes the purpose of the package.

The word "Stream" has been removed from the names of these classes.  Those
names make sense in the context of the Protobuf support classes in
org.apache.geode.internal.cache.tier.sockets classes but not when taken
as a separate group of classes.

The method Authenticator.receiveMessage() has been renamed to
Authenticator.authenticate().

This closes #746


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

Branch: refs/heads/feature/GEODE-3543
Commit: 00a0490d568c7f6b672d83cb2ee064bfe52d787a
Parents: 2637bd8
Author: Bruce Schuchardt <bs...@pivotal.io>
Authored: Mon Aug 28 14:43:45 2017 -0700
Committer: Bruce Schuchardt <bs...@pivotal.io>
Committed: Tue Aug 29 14:24:45 2017 -0700

----------------------------------------------------------------------
 .../sockets/ClientProtocolMessageHandler.java   |  3 -
 .../GenericProtocolServerConnection.java        |  8 +--
 .../tier/sockets/MessageExecutionContext.java   | 14 ++---
 .../tier/sockets/ServerConnectionFactory.java   | 15 +++--
 .../geode/security/NoOpStreamAuthenticator.java | 46 ---------------
 .../geode/security/NoOpStreamAuthorizer.java    | 26 ---------
 .../geode/security/StreamAuthenticator.java     | 56 -------------------
 .../apache/geode/security/StreamAuthorizer.java | 19 -------
 .../geode/security/server/Authenticator.java    | 59 ++++++++++++++++++++
 .../geode/security/server/Authorizer.java       | 21 +++++++
 .../security/server/NoOpAuthenticator.java      | 48 ++++++++++++++++
 .../geode/security/server/NoOpAuthorizer.java   | 27 +++++++++
 .../apache/geode/security/server/package.html   | 45 +++++++++++++++
 ...rg.apache.geode.security.StreamAuthenticator |  1 -
 ...g.apache.geode.security.server.Authenticator |  1 +
 .../geode/cache30/ClientServerCCEDUnitTest.java | 12 ++--
 .../GenericProtocolServerConnectionTest.java    |  4 +-
 .../protocol/protobuf/ProtobufOpsProcessor.java |  2 -
 .../protobuf/ProtobufSimpleAuthenticator.java   | 11 ++--
 .../protobuf/ProtobufSimpleAuthorizer.java      | 12 +---
 .../protobuf/ProtobufStreamProcessor.java       |  1 -
 ...rg.apache.geode.security.StreamAuthenticator |  1 -
 ...g.apache.geode.security.server.Authenticator |  1 +
 .../ProtobufSimpleAuthenticatorJUnitTest.java   |  7 +--
 .../protobuf/ProtobufStreamProcessorTest.java   |  4 +-
 .../GetAllRequestOperationHandlerJUnitTest.java | 12 ++--
 ...onNamesRequestOperationHandlerJUnitTest.java |  6 +-
 ...tRegionRequestOperationHandlerJUnitTest.java |  6 +-
 .../GetRequestOperationHandlerJUnitTest.java    | 12 ++--
 .../PutAllRequestOperationHandlerJUnitTest.java |  8 +--
 .../PutRequestOperationHandlerJUnitTest.java    | 10 ++--
 .../RemoveRequestOperationHandlerJUnitTest.java | 10 ++--
 32 files changed, 271 insertions(+), 237 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ClientProtocolMessageHandler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ClientProtocolMessageHandler.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ClientProtocolMessageHandler.java
index 0d1dfd9..0ced3aa 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ClientProtocolMessageHandler.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ClientProtocolMessageHandler.java
@@ -15,9 +15,6 @@
 
 package org.apache.geode.internal.cache.tier.sockets;
 
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.security.StreamAuthorizer;
-
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnection.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnection.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnection.java
index 0b53cb7..6c81028 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnection.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnection.java
@@ -20,7 +20,7 @@ import org.apache.geode.internal.cache.tier.Acceptor;
 import org.apache.geode.internal.cache.tier.CachedRegionHelper;
 import org.apache.geode.internal.security.SecurityService;
 import org.apache.geode.security.SecurityManager;
-import org.apache.geode.security.StreamAuthenticator;
+import org.apache.geode.security.server.Authenticator;
 
 import java.io.EOFException;
 import java.io.IOException;
@@ -35,7 +35,7 @@ public class GenericProtocolServerConnection extends ServerConnection {
   // The new protocol lives in a separate module and gets loaded when this class is instantiated.
   private final ClientProtocolMessageHandler messageHandler;
   private final SecurityManager securityManager;
-  private final StreamAuthenticator authenticator;
+  private final Authenticator authenticator;
 
   /**
    * Creates a new <code>GenericProtocolServerConnection</code> that processes messages received
@@ -44,7 +44,7 @@ public class GenericProtocolServerConnection extends ServerConnection {
   public GenericProtocolServerConnection(Socket s, InternalCache c, CachedRegionHelper helper,
       CacheServerStats stats, int hsTimeout, int socketBufferSize, String communicationModeStr,
       byte communicationMode, Acceptor acceptor, ClientProtocolMessageHandler newClientProtocol,
-      SecurityService securityService, StreamAuthenticator authenticator) {
+      SecurityService securityService, Authenticator authenticator) {
     super(s, c, helper, stats, hsTimeout, socketBufferSize, communicationModeStr, communicationMode,
         acceptor, securityService);
     securityManager = securityService.getSecurityManager();
@@ -60,7 +60,7 @@ public class GenericProtocolServerConnection extends ServerConnection {
       OutputStream outputStream = socket.getOutputStream();
 
       if (!authenticator.isAuthenticated()) {
-        authenticator.receiveMessage(inputStream, outputStream, securityManager);
+        authenticator.authenticate(inputStream, outputStream, securityManager);
       } else {
         messageHandler.receiveMessage(inputStream, outputStream,
             new MessageExecutionContext(this.getCache(), authenticator.getAuthorizer()));

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageExecutionContext.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageExecutionContext.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageExecutionContext.java
index 817df0e..06d3b03 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageExecutionContext.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageExecutionContext.java
@@ -18,16 +18,16 @@ package org.apache.geode.internal.cache.tier.sockets;
 import org.apache.geode.annotations.Experimental;
 import org.apache.geode.cache.Cache;
 import org.apache.geode.distributed.internal.InternalLocator;
-import org.apache.geode.security.NoOpStreamAuthorizer;
-import org.apache.geode.security.StreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
+import org.apache.geode.security.server.Authorizer;
 
 @Experimental
 public class MessageExecutionContext {
   private Cache cache;
   private InternalLocator locator;
-  private StreamAuthorizer authorizer;
+  private Authorizer authorizer;
 
-  public MessageExecutionContext(Cache cache, StreamAuthorizer streamAuthorizer) {
+  public MessageExecutionContext(Cache cache, Authorizer streamAuthorizer) {
     this.cache = cache;
     this.authorizer = streamAuthorizer;
   }
@@ -36,7 +36,7 @@ public class MessageExecutionContext {
     this.locator = locator;
     // set a no-op authorizer until such time as locators implement authentication
     // and authorization checks
-    this.authorizer = new NoOpStreamAuthorizer();
+    this.authorizer = new NoOpAuthorizer();
   }
 
   /**
@@ -68,10 +68,10 @@ public class MessageExecutionContext {
   }
 
   /**
-   * Returns the StreamAuthorizer associated with this execution. This can be used to perform
+   * Returns the Authorizer associated with this execution. This can be used to perform
    * authorization checks for the user associated with this thread.
    */
-  public StreamAuthorizer getAuthorizer() {
+  public Authorizer getAuthorizer() {
     return authorizer;
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionFactory.java b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionFactory.java
index d2d85f6..00e8b88 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionFactory.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/ServerConnectionFactory.java
@@ -19,7 +19,7 @@ import org.apache.geode.internal.cache.InternalCache;
 import org.apache.geode.internal.cache.tier.Acceptor;
 import org.apache.geode.internal.cache.tier.CachedRegionHelper;
 import org.apache.geode.internal.security.SecurityService;
-import org.apache.geode.security.StreamAuthenticator;
+import org.apache.geode.security.server.Authenticator;
 
 import java.io.IOException;
 import java.net.Socket;
@@ -32,7 +32,7 @@ import java.util.ServiceLoader;
  */
 public class ServerConnectionFactory {
   private ClientProtocolMessageHandler protocolHandler;
-  private Map<String, Class<? extends StreamAuthenticator>> authenticators = null;
+  private Map<String, Class<? extends Authenticator>> authenticators = null;
 
   public ServerConnectionFactory() {}
 
@@ -41,8 +41,8 @@ public class ServerConnectionFactory {
       return;
     }
     authenticators = new HashMap<>();
-    ServiceLoader<StreamAuthenticator> loader = ServiceLoader.load(StreamAuthenticator.class);
-    for (StreamAuthenticator streamAuthenticator : loader) {
+    ServiceLoader<Authenticator> loader = ServiceLoader.load(Authenticator.class);
+    for (Authenticator streamAuthenticator : loader) {
       authenticators.put(streamAuthenticator.implementationID(), streamAuthenticator.getClass());
     }
   }
@@ -57,15 +57,14 @@ public class ServerConnectionFactory {
     return protocolHandler;
   }
 
-  private StreamAuthenticator findStreamAuthenticator(String implementationID) {
+  private Authenticator findStreamAuthenticator(String implementationID) {
     if (authenticators == null) {
       initializeAuthenticatorsMap();
     }
-    Class<? extends StreamAuthenticator> streamAuthenticatorClass =
-        authenticators.get(implementationID);
+    Class<? extends Authenticator> streamAuthenticatorClass = authenticators.get(implementationID);
     if (streamAuthenticatorClass == null) {
       throw new ServiceLoadingFailureException(
-          "Could not find implementation for StreamAuthenticator with implementation ID "
+          "Could not find implementation for Authenticator with implementation ID "
               + implementationID);
     } else {
       try {

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/NoOpStreamAuthenticator.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/NoOpStreamAuthenticator.java b/geode-core/src/main/java/org/apache/geode/security/NoOpStreamAuthenticator.java
deleted file mode 100644
index 62f49fe..0000000
--- a/geode-core/src/main/java/org/apache/geode/security/NoOpStreamAuthenticator.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.security;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * An implementation of {@link StreamAuthenticator} that doesn't use its parameters and always
- * returns true.
- */
-public class NoOpStreamAuthenticator implements StreamAuthenticator {
-  @Override
-  public void receiveMessage(InputStream inputStream, OutputStream outputStream,
-      SecurityManager securityManager) throws IOException {
-    // this method needs to do nothing as it is a pass-through implementation
-  }
-
-  @Override
-  public boolean isAuthenticated() {
-    return true;
-  }
-
-  @Override
-  public StreamAuthorizer getAuthorizer() {
-    return new NoOpStreamAuthorizer();
-  }
-
-  @Override
-  public String implementationID() {
-    return "NOOP";
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/NoOpStreamAuthorizer.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/NoOpStreamAuthorizer.java b/geode-core/src/main/java/org/apache/geode/security/NoOpStreamAuthorizer.java
deleted file mode 100644
index 1b21576..0000000
--- a/geode-core/src/main/java/org/apache/geode/security/NoOpStreamAuthorizer.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.security;
-
-/**
- * An implementation of {@link StreamAuthorizer} that doesn't use its parameters and always returns
- * true.
- */
-public class NoOpStreamAuthorizer implements StreamAuthorizer {
-  @Override
-  public boolean authorize(ResourcePermission permissionRequested) {
-    return true;
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/StreamAuthenticator.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/StreamAuthenticator.java b/geode-core/src/main/java/org/apache/geode/security/StreamAuthenticator.java
deleted file mode 100644
index 8bba60c..0000000
--- a/geode-core/src/main/java/org/apache/geode/security/StreamAuthenticator.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.security;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * Implementers of this interface do some message passing over a socket to authenticate a client,
- * then hand off the connection to the protocol that will talk on the socket.
- *
- * If authentication fails, an implementor may continue to wait for another valid authentication
- * exchange.
- */
-public interface StreamAuthenticator {
-  /**
-   *
-   * @param inputStream to read auth messages from.
-   * @param outputStream to send messages to.
-   * @param securityManager can be used for validating credentials against.
-   * @throws IOException if EOF or if invalid input is received.
-   */
-  void receiveMessage(InputStream inputStream, OutputStream outputStream,
-      SecurityManager securityManager) throws IOException;
-
-  /**
-   * Until authentication is complete, isAuthenticated() must return false, and the socket will
-   * always be passed to the StreamAuthenticator. Once authentication succeeds, calls to this
-   * function must always return true.
-   */
-  boolean isAuthenticated();
-
-  /**
-   * Return an authorization object which can be used to determine which permissions this stream has
-   * according to the provided securityManager.
-   */
-  StreamAuthorizer getAuthorizer() throws AuthenticationRequiredException;
-
-  /**
-   * @return a unique identifier for this particular implementation (NOOP, PASSTHROUGH, etc.)
-   */
-  String implementationID();
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/StreamAuthorizer.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/StreamAuthorizer.java b/geode-core/src/main/java/org/apache/geode/security/StreamAuthorizer.java
deleted file mode 100644
index fdb6b17..0000000
--- a/geode-core/src/main/java/org/apache/geode/security/StreamAuthorizer.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.security;
-
-public interface StreamAuthorizer {
-  boolean authorize(ResourcePermission permissionRequested);
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/server/Authenticator.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/server/Authenticator.java b/geode-core/src/main/java/org/apache/geode/security/server/Authenticator.java
new file mode 100644
index 0000000..7893b4b
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/security/server/Authenticator.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.security.server;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.geode.security.AuthenticationRequiredException;
+import org.apache.geode.security.SecurityManager;
+
+/**
+ * Implementers of this interface do some message passing over a socket to authenticate a client,
+ * then hand off the connection to the protocol that will talk on the socket.
+ *
+ * If authentication fails, an implementor may continue to wait for another valid authentication
+ * exchange.
+ */
+public interface Authenticator {
+  /**
+   *
+   * @param inputStream to read auth messages from.
+   * @param outputStream to send messages to.
+   * @param securityManager can be used for validating credentials against.
+   * @throws IOException if EOF or if invalid input is received.
+   */
+  void authenticate(InputStream inputStream, OutputStream outputStream,
+      SecurityManager securityManager) throws IOException;
+
+  /**
+   * Until authentication is complete, isAuthenticated() must return false, and the socket will
+   * always be passed to the Authenticator. Once authentication succeeds, calls to this function
+   * must always return true.
+   */
+  boolean isAuthenticated();
+
+  /**
+   * Return an authorization object which can be used to determine which permissions this stream has
+   * according to the provided securityManager.
+   */
+  Authorizer getAuthorizer() throws AuthenticationRequiredException;
+
+  /**
+   * @return a unique identifier for this particular implementation (NOOP, PASSTHROUGH, etc.)
+   */
+  String implementationID();
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/server/Authorizer.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/server/Authorizer.java b/geode-core/src/main/java/org/apache/geode/security/server/Authorizer.java
new file mode 100644
index 0000000..fea2198
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/security/server/Authorizer.java
@@ -0,0 +1,21 @@
+/*
+ * 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.security.server;
+
+import org.apache.geode.security.ResourcePermission;
+
+public interface Authorizer {
+  boolean authorize(ResourcePermission permissionRequested);
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/server/NoOpAuthenticator.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/server/NoOpAuthenticator.java b/geode-core/src/main/java/org/apache/geode/security/server/NoOpAuthenticator.java
new file mode 100644
index 0000000..bf435d2
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/security/server/NoOpAuthenticator.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.security.server;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.geode.security.SecurityManager;
+
+/**
+ * An implementation of {@link Authenticator} that doesn't use its parameters and always returns
+ * true.
+ */
+public class NoOpAuthenticator implements Authenticator {
+  @Override
+  public void authenticate(InputStream inputStream, OutputStream outputStream,
+      SecurityManager securityManager) throws IOException {
+    // this method needs to do nothing as it is a pass-through implementation
+  }
+
+  @Override
+  public boolean isAuthenticated() {
+    return true;
+  }
+
+  @Override
+  public Authorizer getAuthorizer() {
+    return new NoOpAuthorizer();
+  }
+
+  @Override
+  public String implementationID() {
+    return "NOOP";
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/server/NoOpAuthorizer.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/server/NoOpAuthorizer.java b/geode-core/src/main/java/org/apache/geode/security/server/NoOpAuthorizer.java
new file mode 100644
index 0000000..1491f04
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/security/server/NoOpAuthorizer.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.security.server;
+
+import org.apache.geode.security.ResourcePermission;
+
+/**
+ * An implementation of {@link Authorizer} that doesn't use its parameters and always returns true.
+ */
+public class NoOpAuthorizer implements Authorizer {
+  @Override
+  public boolean authorize(ResourcePermission permissionRequested) {
+    return true;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/java/org/apache/geode/security/server/package.html
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/security/server/package.html b/geode-core/src/main/java/org/apache/geode/security/server/package.html
new file mode 100644
index 0000000..15a2114
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/security/server/package.html
@@ -0,0 +1,45 @@
+<!--
+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.
+-->
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+</head>
+<body>
+<p>This package provides authentication and authorization for a client.  There is a default
+"no-op" implementation that is overridden by the Protobuf form of client/server
+   communication.</p>
+<p>This can also be overridden by _you_ in order to use a different mechanism
+on the server by setting the property geode.protocol-authentication-mode to the name
+   of your implementation.  This is the string returned by your class's
+   implementationID method.</p>
+
+<p>The Authenticator.authenticate() method
+   is first given the i/o streams connected to the client so that it
+can interact with the client to get credentials.  A simple mechanism might expect a
+username and password on the input stream.</p>
+
+<p>Once the client is authenticated the Authenticator will be asked for an authorizer each time
+a message is received.  The authorizer will be asked if the authenticated principal
+is authorized for permissions associated with the request sent by the client.</p>
+
+<p><i>Note: the legacy "GemFire" client/server authorization mechanism is hardcoded
+to get credentials using a non-documented interchange and is not affected by this package.
+It interacts directly with the SecurityManager, as does the default mechanism used in
+Protobuf communications.</i></p>
+</body>
+</html>

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/resources/META-INF/services/org.apache.geode.security.StreamAuthenticator
----------------------------------------------------------------------
diff --git a/geode-core/src/main/resources/META-INF/services/org.apache.geode.security.StreamAuthenticator b/geode-core/src/main/resources/META-INF/services/org.apache.geode.security.StreamAuthenticator
deleted file mode 100644
index 3b93815..0000000
--- a/geode-core/src/main/resources/META-INF/services/org.apache.geode.security.StreamAuthenticator
+++ /dev/null
@@ -1 +0,0 @@
-org.apache.geode.security.NoOpStreamAuthenticator
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/main/resources/META-INF/services/org.apache.geode.security.server.Authenticator
----------------------------------------------------------------------
diff --git a/geode-core/src/main/resources/META-INF/services/org.apache.geode.security.server.Authenticator b/geode-core/src/main/resources/META-INF/services/org.apache.geode.security.server.Authenticator
new file mode 100644
index 0000000..4f34d2a
--- /dev/null
+++ b/geode-core/src/main/resources/META-INF/services/org.apache.geode.security.server.Authenticator
@@ -0,0 +1 @@
+org.apache.geode.security.server.NoOpAuthenticator

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java b/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java
index b9301dd..4d72f50 100644
--- a/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/cache30/ClientServerCCEDUnitTest.java
@@ -195,11 +195,11 @@ public class ClientServerCCEDUnitTest extends JUnit4CacheTestCase {
         case 4:
           region.replace(key, value, value);
           break;
-//        case 5:
-//          remove(k,v) can't be included in this test as it checks the old value
-//          against what is in the local cache before sending the operation to the server
-//          region.remove(key, value);
-//          break;
+        // case 5:
+        // remove(k,v) can't be included in this test as it checks the old value
+        // against what is in the local cache before sending the operation to the server
+        // region.remove(key, value);
+        // break;
         default:
           throw new RuntimeException("" + j + " % 5 == " + operation + "?");
       }
@@ -930,7 +930,7 @@ public class ClientServerCCEDUnitTest extends JUnit4CacheTestCase {
   }
 
   private int createServerRegion(VM vm, final String regionName, final boolean replicatedRegion,
-                                 Scope regionScope) {
+      Scope regionScope) {
     SerializableCallable createRegion = new SerializableCallable() {
       public Object call() throws Exception {
         // TombstoneService.VERBOSE = true;

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnectionTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnectionTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnectionTest.java
index 383fbf0..ea00018 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnectionTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/sockets/GenericProtocolServerConnectionTest.java
@@ -24,7 +24,7 @@ import org.apache.geode.internal.cache.InternalCache;
 import org.apache.geode.internal.cache.tier.Acceptor;
 import org.apache.geode.internal.cache.tier.CachedRegionHelper;
 import org.apache.geode.internal.security.SecurityService;
-import org.apache.geode.security.NoOpStreamAuthenticator;
+import org.apache.geode.security.server.NoOpAuthenticator;
 import org.apache.geode.test.junit.categories.UnitTest;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -58,6 +58,6 @@ public class GenericProtocolServerConnectionTest {
     return new GenericProtocolServerConnection(socketMock, mock(InternalCache.class),
         mock(CachedRegionHelper.class), mock(CacheServerStats.class), 0, 0, "",
         Acceptor.PROTOBUF_CLIENT_SERVER_PROTOCOL, mock(AcceptorImpl.class), clientProtocolMock,
-        mock(SecurityService.class), new NoOpStreamAuthenticator());
+        mock(SecurityService.class), new NoOpAuthenticator());
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufOpsProcessor.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufOpsProcessor.java b/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufOpsProcessor.java
index a2f752d..b95b405 100644
--- a/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufOpsProcessor.java
+++ b/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufOpsProcessor.java
@@ -15,13 +15,11 @@
 package org.apache.geode.protocol.protobuf;
 
 import org.apache.geode.annotations.Experimental;
-import org.apache.geode.internal.cache.Token;
 import org.apache.geode.internal.cache.tier.sockets.MessageExecutionContext;
 import org.apache.geode.internal.cache.tier.sockets.InvalidExecutionContextException;
 import org.apache.geode.internal.protocol.protobuf.ClientProtocol;
 import org.apache.geode.protocol.protobuf.registry.OperationContextRegistry;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufResponseUtilities;
-import org.apache.geode.security.StreamAuthorizer;
 import org.apache.geode.serialization.SerializationService;
 
 /**

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticator.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticator.java b/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticator.java
index 1bb0678..5fadadd 100644
--- a/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticator.java
+++ b/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticator.java
@@ -17,10 +17,10 @@ package org.apache.geode.protocol.protobuf;
 import org.apache.geode.management.internal.security.ResourceConstants;
 import org.apache.geode.internal.protocol.protobuf.AuthenticationAPI;
 import org.apache.geode.security.AuthenticationRequiredException;
-import org.apache.geode.security.StreamAuthenticator;
+import org.apache.geode.security.server.Authenticator;
 import org.apache.geode.security.AuthenticationFailedException;
 import org.apache.geode.security.SecurityManager;
-import org.apache.geode.security.StreamAuthorizer;
+import org.apache.geode.security.server.Authorizer;
 
 import java.io.EOFException;
 import java.io.IOException;
@@ -28,12 +28,11 @@ import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.Properties;
 
-public class ProtobufSimpleAuthenticator implements StreamAuthenticator {
-  private boolean authenticated;
+public class ProtobufSimpleAuthenticator implements Authenticator {
   private ProtobufSimpleAuthorizer authorizer = null;
 
   @Override
-  public void receiveMessage(InputStream inputStream, OutputStream outputStream,
+  public void authenticate(InputStream inputStream, OutputStream outputStream,
       SecurityManager securityManager) throws IOException {
     AuthenticationAPI.SimpleAuthenticationRequest authenticationRequest =
         AuthenticationAPI.SimpleAuthenticationRequest.parseDelimitedFrom(inputStream);
@@ -66,7 +65,7 @@ public class ProtobufSimpleAuthenticator implements StreamAuthenticator {
   }
 
   @Override
-  public StreamAuthorizer getAuthorizer() throws AuthenticationRequiredException {
+  public Authorizer getAuthorizer() throws AuthenticationRequiredException {
     if (authorizer == null) {
       throw new AuthenticationRequiredException("Not yet authenticated");
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthorizer.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthorizer.java b/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthorizer.java
index 872632a..e29abfa 100644
--- a/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthorizer.java
+++ b/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthorizer.java
@@ -14,19 +14,11 @@
  */
 package org.apache.geode.protocol.protobuf;
 
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Properties;
-
-import org.apache.geode.security.AuthenticationFailedException;
 import org.apache.geode.security.ResourcePermission;
 import org.apache.geode.security.SecurityManager;
-import org.apache.geode.security.StreamAuthenticator;
-import org.apache.geode.security.StreamAuthorizer;
+import org.apache.geode.security.server.Authorizer;
 
-public class ProtobufSimpleAuthorizer implements StreamAuthorizer {
+public class ProtobufSimpleAuthorizer implements Authorizer {
   private final Object authenticatedPrincipal;
   private final SecurityManager securityManager;
 

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessor.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessor.java b/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessor.java
index 23924db..f28c310 100644
--- a/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessor.java
+++ b/geode-protobuf/src/main/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessor.java
@@ -27,7 +27,6 @@ import org.apache.geode.internal.protocol.protobuf.ClientProtocol;
 import org.apache.geode.protocol.protobuf.registry.OperationContextRegistry;
 import org.apache.geode.protocol.protobuf.serializer.ProtobufProtocolSerializer;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufUtilities;
-import org.apache.geode.security.StreamAuthorizer;
 import org.apache.geode.serialization.registry.exception.CodecAlreadyRegisteredForTypeException;
 
 /**

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/main/resources/META-INF/services/org.apache.geode.security.StreamAuthenticator
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/main/resources/META-INF/services/org.apache.geode.security.StreamAuthenticator b/geode-protobuf/src/main/resources/META-INF/services/org.apache.geode.security.StreamAuthenticator
deleted file mode 100644
index 45e4eea..0000000
--- a/geode-protobuf/src/main/resources/META-INF/services/org.apache.geode.security.StreamAuthenticator
+++ /dev/null
@@ -1 +0,0 @@
-org.apache.geode.protocol.protobuf.ProtobufSimpleAuthenticator
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/main/resources/META-INF/services/org.apache.geode.security.server.Authenticator
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/main/resources/META-INF/services/org.apache.geode.security.server.Authenticator b/geode-protobuf/src/main/resources/META-INF/services/org.apache.geode.security.server.Authenticator
new file mode 100644
index 0000000..45e4eea
--- /dev/null
+++ b/geode-protobuf/src/main/resources/META-INF/services/org.apache.geode.security.server.Authenticator
@@ -0,0 +1 @@
+org.apache.geode.protocol.protobuf.ProtobufSimpleAuthenticator
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticatorJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticatorJUnitTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticatorJUnitTest.java
index c80b7c8..33424a3 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticatorJUnitTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufSimpleAuthenticatorJUnitTest.java
@@ -19,7 +19,6 @@ import org.apache.geode.examples.security.ExampleSecurityManager;
 import org.apache.geode.management.internal.security.ResourceConstants;
 import org.apache.geode.internal.protocol.protobuf.AuthenticationAPI;
 import org.apache.geode.security.AuthenticationFailedException;
-import org.apache.geode.security.ResourcePermission;
 import org.apache.geode.security.SecurityManager;
 import org.apache.geode.test.junit.categories.UnitTest;
 import org.junit.Before;
@@ -77,7 +76,7 @@ public class ProtobufSimpleAuthenticatorJUnitTest {
   public void successfulAuthentication() throws IOException {
     assertFalse(protobufSimpleAuthenticator.isAuthenticated());
 
-    protobufSimpleAuthenticator.receiveMessage(byteArrayInputStream, byteArrayOutputStream,
+    protobufSimpleAuthenticator.authenticate(byteArrayInputStream, byteArrayOutputStream,
         mockSecurityManager);
 
     AuthenticationAPI.SimpleAuthenticationResponse simpleAuthenticationResponse =
@@ -97,7 +96,7 @@ public class ProtobufSimpleAuthenticatorJUnitTest {
     when(mockSecurityManager.authenticate(expectedAuthProperties))
         .thenThrow(new AuthenticationFailedException("BOOM!"));
 
-    protobufSimpleAuthenticator.receiveMessage(byteArrayInputStream, byteArrayOutputStream,
+    protobufSimpleAuthenticator.authenticate(byteArrayInputStream, byteArrayOutputStream,
         mockSecurityManager);
 
     AuthenticationAPI.SimpleAuthenticationResponse simpleAuthenticationResponse =
@@ -111,7 +110,7 @@ public class ProtobufSimpleAuthenticatorJUnitTest {
   public void testExampleSecurityManager() throws IOException {
     assertFalse(protobufSimpleAuthenticator.isAuthenticated());
 
-    protobufSimpleAuthenticator.receiveMessage(byteArrayInputStream, byteArrayOutputStream,
+    protobufSimpleAuthenticator.authenticate(byteArrayInputStream, byteArrayOutputStream,
         mockSecurityManager);
 
     new ExampleSecurityManager().init(expectedAuthProperties);

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessorTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessorTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessorTest.java
index bebbfde..50d7b40 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessorTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/ProtobufStreamProcessorTest.java
@@ -27,7 +27,7 @@ import org.junit.experimental.categories.Category;
 
 import org.apache.geode.internal.cache.InternalCache;
 import org.apache.geode.internal.cache.tier.sockets.MessageExecutionContext;
-import org.apache.geode.security.NoOpStreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
 import org.apache.geode.test.junit.categories.UnitTest;
 
 @Category(UnitTest.class)
@@ -40,6 +40,6 @@ public class ProtobufStreamProcessorTest {
     ProtobufStreamProcessor protobufStreamProcessor = new ProtobufStreamProcessor();
     InternalCache mockInternalCache = mock(InternalCache.class);
     protobufStreamProcessor.receiveMessage(inputStream, outputStream,
-        new MessageExecutionContext(mockInternalCache, new NoOpStreamAuthorizer()));
+        new MessageExecutionContext(mockInternalCache, new NoOpAuthorizer()));
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetAllRequestOperationHandlerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetAllRequestOperationHandlerJUnitTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetAllRequestOperationHandlerJUnitTest.java
index b8613b6..f4d9c92 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetAllRequestOperationHandlerJUnitTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetAllRequestOperationHandlerJUnitTest.java
@@ -35,7 +35,7 @@ import org.apache.geode.protocol.protobuf.Result;
 import org.apache.geode.protocol.protobuf.Success;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufRequestUtilities;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufUtilities;
-import org.apache.geode.security.NoOpStreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
 import org.apache.geode.serialization.exception.UnsupportedEncodingTypeException;
 import org.apache.geode.serialization.registry.exception.CodecAlreadyRegisteredForTypeException;
 import org.apache.geode.serialization.registry.exception.CodecNotRegisteredForTypeException;
@@ -79,9 +79,8 @@ public class GetAllRequestOperationHandlerJUnitTest extends OperationHandlerJUni
   public void processReturnsExpectedValuesForValidKeys()
       throws CodecAlreadyRegisteredForTypeException, UnsupportedEncodingTypeException,
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
-    Result<RegionAPI.GetAllResponse> result =
-        operationHandler.process(serializationServiceStub, generateTestRequest(true),
-            new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+    Result<RegionAPI.GetAllResponse> result = operationHandler.process(serializationServiceStub,
+        generateTestRequest(true), new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     Assert.assertTrue(result instanceof Success);
 
@@ -100,9 +99,8 @@ public class GetAllRequestOperationHandlerJUnitTest extends OperationHandlerJUni
   @Test
   public void processReturnsNoEntriesForNoKeysRequested() throws UnsupportedEncodingTypeException,
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
-    Result<RegionAPI.GetAllResponse> result =
-        operationHandler.process(serializationServiceStub, generateTestRequest(false),
-            new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+    Result<RegionAPI.GetAllResponse> result = operationHandler.process(serializationServiceStub,
+        generateTestRequest(false), new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     Assert.assertTrue(result instanceof Success);
 

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionNamesRequestOperationHandlerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionNamesRequestOperationHandlerJUnitTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionNamesRequestOperationHandlerJUnitTest.java
index 323048e..8566fd6 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionNamesRequestOperationHandlerJUnitTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionNamesRequestOperationHandlerJUnitTest.java
@@ -33,7 +33,7 @@ import org.apache.geode.internal.protocol.protobuf.RegionAPI;
 import org.apache.geode.protocol.protobuf.Result;
 import org.apache.geode.protocol.protobuf.Success;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufRequestUtilities;
-import org.apache.geode.security.NoOpStreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
 import org.apache.geode.serialization.exception.UnsupportedEncodingTypeException;
 import org.apache.geode.serialization.registry.exception.CodecAlreadyRegisteredForTypeException;
 import org.apache.geode.serialization.registry.exception.CodecNotRegisteredForTypeException;
@@ -68,7 +68,7 @@ public class GetRegionNamesRequestOperationHandlerJUnitTest extends OperationHan
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
     Result<RegionAPI.GetRegionNamesResponse> result = operationHandler.process(
         serializationServiceStub, ProtobufRequestUtilities.createGetRegionNamesRequest(),
-        new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
     Assert.assertTrue(result instanceof Success);
 
     RegionAPI.GetRegionNamesResponse getRegionsResponse = result.getMessage();
@@ -94,7 +94,7 @@ public class GetRegionNamesRequestOperationHandlerJUnitTest extends OperationHan
         .thenReturn(Collections.unmodifiableSet(new HashSet<Region<String, String>>()));
     Result<RegionAPI.GetRegionNamesResponse> result = operationHandler.process(
         serializationServiceStub, ProtobufRequestUtilities.createGetRegionNamesRequest(),
-        new MessageExecutionContext(emptyCache, new NoOpStreamAuthorizer()));
+        new MessageExecutionContext(emptyCache, new NoOpAuthorizer()));
     Assert.assertTrue(result instanceof Success);
 
     RegionAPI.GetRegionNamesResponse getRegionsResponse = result.getMessage();

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionRequestOperationHandlerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionRequestOperationHandlerJUnitTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionRequestOperationHandlerJUnitTest.java
index 88950b7..0ba0fee 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionRequestOperationHandlerJUnitTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRegionRequestOperationHandlerJUnitTest.java
@@ -28,7 +28,7 @@ import org.apache.geode.protocol.protobuf.Failure;
 import org.apache.geode.protocol.protobuf.ProtocolErrorCode;
 import org.apache.geode.internal.protocol.protobuf.RegionAPI;
 import org.apache.geode.protocol.protobuf.Result;
-import org.apache.geode.security.NoOpStreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
 import org.apache.geode.serialization.exception.UnsupportedEncodingTypeException;
 import org.apache.geode.serialization.registry.exception.CodecAlreadyRegisteredForTypeException;
 import org.apache.geode.serialization.registry.exception.CodecNotRegisteredForTypeException;
@@ -77,7 +77,7 @@ public class GetRegionRequestOperationHandlerJUnitTest extends OperationHandlerJ
 
     Result<RegionAPI.GetRegionResponse> result = operationHandler.process(serializationServiceStub,
         MessageUtil.makeGetRegionRequest(TEST_REGION1),
-        new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
     RegionAPI.GetRegionResponse response = result.getMessage();
     BasicTypes.Region region = response.getRegion();
     Assert.assertEquals(TEST_REGION1, region.getName());
@@ -103,7 +103,7 @@ public class GetRegionRequestOperationHandlerJUnitTest extends OperationHandlerJ
     String unknownRegionName = "UNKNOWN_REGION";
     Result<RegionAPI.GetRegionResponse> result = operationHandler.process(serializationServiceStub,
         MessageUtil.makeGetRegionRequest(unknownRegionName),
-        new MessageExecutionContext(emptyCache, new NoOpStreamAuthorizer()));
+        new MessageExecutionContext(emptyCache, new NoOpAuthorizer()));
     Assert.assertTrue(result instanceof Failure);
     Assert.assertEquals(ProtocolErrorCode.REGION_NOT_FOUND.codeValue,
         result.getErrorMessage().getError().getErrorCode());

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRequestOperationHandlerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRequestOperationHandlerJUnitTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRequestOperationHandlerJUnitTest.java
index f104fb0..58945dd 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRequestOperationHandlerJUnitTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/GetRequestOperationHandlerJUnitTest.java
@@ -26,7 +26,7 @@ import org.apache.geode.protocol.protobuf.Result;
 import org.apache.geode.protocol.protobuf.Success;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufRequestUtilities;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufUtilities;
-import org.apache.geode.security.NoOpStreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
 import org.apache.geode.serialization.exception.UnsupportedEncodingTypeException;
 import org.apache.geode.serialization.registry.exception.CodecAlreadyRegisteredForTypeException;
 import org.apache.geode.serialization.registry.exception.CodecNotRegisteredForTypeException;
@@ -73,7 +73,7 @@ public class GetRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
     RegionAPI.GetRequest getRequest = generateTestRequest(false, false, false);
     Result<RegionAPI.GetResponse> result = operationHandler.process(serializationServiceStub,
-        getRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        getRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     Assert.assertTrue(result instanceof Success);
     Assert.assertEquals(BasicTypes.EncodedValue.ValueCase.STRINGRESULT,
@@ -88,7 +88,7 @@ public class GetRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
     RegionAPI.GetRequest getRequest = generateTestRequest(true, false, false);
     Result<RegionAPI.GetResponse> response = operationHandler.process(serializationServiceStub,
-        getRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        getRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     Assert.assertTrue(response instanceof Failure);
     Assert.assertEquals(ProtocolErrorCode.REGION_NOT_FOUND.codeValue,
@@ -101,7 +101,7 @@ public class GetRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
     RegionAPI.GetRequest getRequest = generateTestRequest(false, true, false);
     Result<RegionAPI.GetResponse> response = operationHandler.process(serializationServiceStub,
-        getRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        getRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     Assert.assertTrue(response instanceof Success);
   }
@@ -112,7 +112,7 @@ public class GetRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
     RegionAPI.GetRequest getRequest = generateTestRequest(false, false, true);
     Result<RegionAPI.GetResponse> response = operationHandler.process(serializationServiceStub,
-        getRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        getRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     Assert.assertTrue(response instanceof Success);
   }
@@ -134,7 +134,7 @@ public class GetRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
     RegionAPI.GetRequest getRequest =
         ProtobufRequestUtilities.createGetRequest(TEST_REGION, encodedKey).getGetRequest();
     Result<RegionAPI.GetResponse> response = operationHandler.process(serializationServiceStub,
-        getRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        getRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     Assert.assertTrue(response instanceof Failure);
     Assert.assertEquals(ProtocolErrorCode.VALUE_ENCODING_ERROR.codeValue,

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutAllRequestOperationHandlerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutAllRequestOperationHandlerJUnitTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutAllRequestOperationHandlerJUnitTest.java
index 71d6a51..4958a40 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutAllRequestOperationHandlerJUnitTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutAllRequestOperationHandlerJUnitTest.java
@@ -23,7 +23,7 @@ import org.apache.geode.protocol.protobuf.Result;
 import org.apache.geode.protocol.protobuf.Success;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufRequestUtilities;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufUtilities;
-import org.apache.geode.security.NoOpStreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
 import org.apache.geode.serialization.exception.UnsupportedEncodingTypeException;
 import org.apache.geode.serialization.registry.exception.CodecAlreadyRegisteredForTypeException;
 import org.apache.geode.serialization.registry.exception.CodecNotRegisteredForTypeException;
@@ -76,7 +76,7 @@ public class PutAllRequestOperationHandlerJUnitTest extends OperationHandlerJUni
 
     Result<RegionAPI.PutAllResponse> result =
         operationHandler.process(serializationServiceStub, generateTestRequest(false, true),
-            new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+            new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     Assert.assertTrue(result instanceof Success);
 
@@ -91,7 +91,7 @@ public class PutAllRequestOperationHandlerJUnitTest extends OperationHandlerJUni
 
     Result<RegionAPI.PutAllResponse> result =
         operationHandler.process(serializationServiceStub, generateTestRequest(true, true),
-            new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+            new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Success);
     verify(regionMock).put(TEST_KEY1, TEST_VALUE1);
@@ -111,7 +111,7 @@ public class PutAllRequestOperationHandlerJUnitTest extends OperationHandlerJUni
 
     Result<RegionAPI.PutAllResponse> result =
         operationHandler.process(serializationServiceStub, generateTestRequest(false, false),
-            new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+            new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Success);
 

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutRequestOperationHandlerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutRequestOperationHandlerJUnitTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutRequestOperationHandlerJUnitTest.java
index cbd897a..c2b9af3 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutRequestOperationHandlerJUnitTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/PutRequestOperationHandlerJUnitTest.java
@@ -26,7 +26,7 @@ import org.apache.geode.protocol.protobuf.Result;
 import org.apache.geode.protocol.protobuf.Success;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufRequestUtilities;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufUtilities;
-import org.apache.geode.security.NoOpStreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
 import org.apache.geode.serialization.exception.UnsupportedEncodingTypeException;
 import org.apache.geode.serialization.registry.exception.CodecAlreadyRegisteredForTypeException;
 import org.apache.geode.serialization.registry.exception.CodecNotRegisteredForTypeException;
@@ -69,7 +69,7 @@ public class PutRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
       CodecAlreadyRegisteredForTypeException, InvalidExecutionContextException {
     PutRequestOperationHandler operationHandler = new PutRequestOperationHandler();
     Result<RegionAPI.PutResponse> result = operationHandler.process(serializationServiceStub,
-        generateTestRequest(), new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        generateTestRequest(), new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Success);
 
@@ -100,7 +100,7 @@ public class PutRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
     RegionAPI.PutRequest putRequest =
         ProtobufRequestUtilities.createPutRequest(TEST_REGION, testEntry).getPutRequest();
     Result<RegionAPI.PutResponse> result = operationHandler.process(serializationServiceStub,
-        putRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        putRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Failure);
     assertEquals(ProtocolErrorCode.VALUE_ENCODING_ERROR.codeValue,
@@ -114,7 +114,7 @@ public class PutRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
     when(cacheStub.getRegion(TEST_REGION)).thenReturn(null);
     PutRequestOperationHandler operationHandler = new PutRequestOperationHandler();
     Result<RegionAPI.PutResponse> result = operationHandler.process(serializationServiceStub,
-        generateTestRequest(), new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        generateTestRequest(), new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Failure);
     assertEquals(ProtocolErrorCode.REGION_NOT_FOUND.codeValue,
@@ -129,7 +129,7 @@ public class PutRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTe
 
     PutRequestOperationHandler operationHandler = new PutRequestOperationHandler();
     Result<RegionAPI.PutResponse> result = operationHandler.process(serializationServiceStub,
-        generateTestRequest(), new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        generateTestRequest(), new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Failure);
     assertEquals(ProtocolErrorCode.CONSTRAINT_VIOLATION.codeValue,

http://git-wip-us.apache.org/repos/asf/geode/blob/00a0490d/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/RemoveRequestOperationHandlerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/RemoveRequestOperationHandlerJUnitTest.java b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/RemoveRequestOperationHandlerJUnitTest.java
index 5d38e61..5d8a31c 100644
--- a/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/RemoveRequestOperationHandlerJUnitTest.java
+++ b/geode-protobuf/src/test/java/org/apache/geode/protocol/protobuf/operations/RemoveRequestOperationHandlerJUnitTest.java
@@ -27,7 +27,7 @@ import org.apache.geode.protocol.protobuf.Result;
 import org.apache.geode.protocol.protobuf.Success;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufRequestUtilities;
 import org.apache.geode.protocol.protobuf.utilities.ProtobufUtilities;
-import org.apache.geode.security.NoOpStreamAuthorizer;
+import org.apache.geode.security.server.NoOpAuthorizer;
 import org.apache.geode.serialization.exception.UnsupportedEncodingTypeException;
 import org.apache.geode.serialization.registry.exception.CodecAlreadyRegisteredForTypeException;
 import org.apache.geode.serialization.registry.exception.CodecNotRegisteredForTypeException;
@@ -74,7 +74,7 @@ public class RemoveRequestOperationHandlerJUnitTest extends OperationHandlerJUni
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
     RegionAPI.RemoveRequest removeRequest = generateTestRequest(false, false).getRemoveRequest();
     Result<RegionAPI.RemoveResponse> result = operationHandler.process(serializationServiceStub,
-        removeRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        removeRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Success);
     verify(regionStub).remove(TEST_KEY);
@@ -86,7 +86,7 @@ public class RemoveRequestOperationHandlerJUnitTest extends OperationHandlerJUni
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
     RegionAPI.RemoveRequest removeRequest = generateTestRequest(true, false).getRemoveRequest();
     Result<RegionAPI.RemoveResponse> result = operationHandler.process(serializationServiceStub,
-        removeRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        removeRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Failure);
     assertEquals(ProtocolErrorCode.REGION_NOT_FOUND.codeValue,
@@ -99,7 +99,7 @@ public class RemoveRequestOperationHandlerJUnitTest extends OperationHandlerJUni
       CodecNotRegisteredForTypeException, InvalidExecutionContextException {
     RegionAPI.RemoveRequest removeRequest = generateTestRequest(false, true).getRemoveRequest();
     Result<RegionAPI.RemoveResponse> result = operationHandler.process(serializationServiceStub,
-        removeRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        removeRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Success);
   }
@@ -122,7 +122,7 @@ public class RemoveRequestOperationHandlerJUnitTest extends OperationHandlerJUni
     RegionAPI.RemoveRequest removeRequest =
         ProtobufRequestUtilities.createRemoveRequest(TEST_REGION, encodedKey).getRemoveRequest();;
     Result<RegionAPI.RemoveResponse> result = operationHandler.process(serializationServiceStub,
-        removeRequest, new MessageExecutionContext(cacheStub, new NoOpStreamAuthorizer()));
+        removeRequest, new MessageExecutionContext(cacheStub, new NoOpAuthorizer()));
 
     assertTrue(result instanceof Failure);
     assertEquals(ProtocolErrorCode.VALUE_ENCODING_ERROR.codeValue,


[16/47] geode git commit: GEODE-3436: Restore refactoring of IndexCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of IndexCommands

* See initial commit GEODE-3262 (ed293e817e547fb5ecd399bf4ba10d694af51e0a)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 0dc67f0e7798a38afff906aa26e9bb89ab42b53c
Parents: 3bfe7a2
Author: YehEmily <em...@gmail.com>
Authored: Mon Aug 7 12:35:14 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:26 2017 -0700

----------------------------------------------------------------------
 .../commands/ClearDefinedIndexesCommand.java    |  40 ++
 .../commands/CreateDefinedIndexesCommand.java   | 155 +++++
 .../cli/commands/CreateIndexCommand.java        | 197 ++++++
 .../cli/commands/DefineIndexCommand.java        |  95 +++
 .../cli/commands/DestroyIndexCommand.java       | 174 +++++
 .../internal/cli/commands/IndexCommands.java    | 668 -------------------
 .../internal/cli/commands/IndexDefinition.java  |  27 +
 .../internal/cli/commands/ListIndexCommand.java | 158 +++++
 .../functions/CreateDefinedIndexesFunction.java |   3 +-
 .../controllers/IndexCommandsController.java    |  13 +-
 .../cli/commands/IndexCommandsJUnitTest.java    | 223 -------
 .../cli/commands/ListIndexCommandDUnitTest.java |  38 +-
 .../cli/commands/ListIndexCommandJUnitTest.java | 223 +++++++
 .../internal/security/TestCommand.java          |   3 +-
 14 files changed, 1103 insertions(+), 914 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClearDefinedIndexesCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClearDefinedIndexesCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClearDefinedIndexesCommand.java
new file mode 100644
index 0000000..d12f2c7
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClearDefinedIndexesCommand.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import org.springframework.shell.core.annotation.CliCommand;
+
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ClearDefinedIndexesCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.CLEAR_DEFINED_INDEXES, help = CliStrings.CLEAR_DEFINED__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
+  // TODO : Add optionContext for indexName
+  public Result clearDefinedIndexes() {
+    IndexDefinition.indexDefinitions.clear();
+    InfoResultData infoResult = ResultBuilder.createInfoResultData();
+    infoResult.addLine(CliStrings.CLEAR_DEFINED_INDEX__SUCCESS__MSG);
+    return ResultBuilder.buildResult(infoResult);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
new file mode 100644
index 0000000..3487279
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.CreateDefinedIndexesFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CreateDefinedIndexesCommand implements GfshCommand {
+  private static final CreateDefinedIndexesFunction createDefinedIndexesFunction =
+      new CreateDefinedIndexesFunction();
+
+  @CliCommand(value = CliStrings.CREATE_DEFINED_INDEXES, help = CliStrings.CREATE_DEFINED__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
+  // TODO : Add optionContext for indexName
+  public Result createDefinedIndexes(
+
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          optionContext = ConverterHint.MEMBERIDNAME,
+          help = CliStrings.CREATE_DEFINED_INDEXES__MEMBER__HELP) final String[] memberNameOrID,
+
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.CREATE_DEFINED_INDEXES__GROUP__HELP) final String[] group) {
+
+    Result result;
+    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+
+    if (IndexDefinition.indexDefinitions.isEmpty()) {
+      final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+      infoResult.addLine(CliStrings.DEFINE_INDEX__FAILURE__MSG);
+      return ResultBuilder.buildResult(infoResult);
+    }
+
+    try {
+      final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      // TODO PSR: is this safe to remove?
+      CacheFactory.getAnyInstance();
+      final ResultCollector<?, ?> rc = CliUtil.executeFunction(createDefinedIndexesFunction,
+          IndexDefinition.indexDefinitions, targetMembers);
+
+      final List<Object> funcResults = (List<Object>) rc.getResult();
+      final Set<String> successfulMembers = new TreeSet<>();
+      final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
+
+      for (final Object funcResult : funcResults) {
+        if (funcResult instanceof CliFunctionResult) {
+          final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
+
+          if (cliFunctionResult.isSuccessful()) {
+            successfulMembers.add(cliFunctionResult.getMemberIdOrName());
+
+            if (xmlEntity.get() == null) {
+              xmlEntity.set(cliFunctionResult.getXmlEntity());
+            }
+          } else {
+            final String exceptionMessage = cliFunctionResult.getMessage();
+            Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
+
+            if (failedMembers == null) {
+              failedMembers = new TreeSet<>();
+            }
+            failedMembers.add(cliFunctionResult.getMemberIdOrName());
+            indexOpFailMap.put(exceptionMessage, failedMembers);
+          }
+        }
+      }
+
+      if (!successfulMembers.isEmpty()) {
+        final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+        infoResult.addLine(CliStrings.CREATE_DEFINED_INDEXES__SUCCESS__MSG);
+
+        int num = 0;
+
+        for (final String memberId : successfulMembers) {
+          ++num;
+          infoResult.addLine(CliStrings
+              .format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER, num, memberId));
+        }
+        result = ResultBuilder.buildResult(infoResult);
+
+      } else {
+        // Group members by the exception thrown.
+        final ErrorResultData erd = ResultBuilder.createErrorResultData();
+
+        final Set<String> exceptionMessages = indexOpFailMap.keySet();
+
+        for (final String exceptionMessage : exceptionMessages) {
+          erd.addLine(exceptionMessage);
+          erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
+          final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
+
+          int num = 0;
+          for (final String memberId : memberIds) {
+            ++num;
+            erd.addLine(CliStrings.format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER,
+                num, memberId));
+          }
+        }
+        result = ResultBuilder.buildResult(erd);
+      }
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+
+    if (xmlEntity.get() != null) {
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
new file mode 100644
index 0000000..5bae92d
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.IndexInfo;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.CreateIndexFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class CreateIndexCommand implements GfshCommand {
+  private static final CreateIndexFunction createIndexFunction = new CreateIndexFunction();
+
+  @CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+  // TODO : Add optionContext for indexName
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
+  public Result createIndex(@CliOption(key = CliStrings.CREATE_INDEX__NAME, mandatory = true,
+      help = CliStrings.CREATE_INDEX__NAME__HELP) final String indexName,
+
+      @CliOption(key = CliStrings.CREATE_INDEX__EXPRESSION, mandatory = true,
+          help = CliStrings.CREATE_INDEX__EXPRESSION__HELP) final String indexedExpression,
+
+      @CliOption(key = CliStrings.CREATE_INDEX__REGION, mandatory = true,
+          optionContext = ConverterHint.REGION_PATH,
+          help = CliStrings.CREATE_INDEX__REGION__HELP) String regionPath,
+
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          optionContext = ConverterHint.MEMBERIDNAME,
+          help = CliStrings.CREATE_INDEX__MEMBER__HELP) final String[] memberNameOrID,
+
+      @CliOption(key = CliStrings.CREATE_INDEX__TYPE, unspecifiedDefaultValue = "range",
+          optionContext = ConverterHint.INDEX_TYPE,
+          help = CliStrings.CREATE_INDEX__TYPE__HELP) final String indexType,
+
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.CREATE_INDEX__GROUP__HELP) final String[] group) {
+
+    Result result;
+    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+
+    try {
+      // TODO PSR: Is this safe to remove?
+      CacheFactory.getAnyInstance();
+      int idxType;
+
+      // Index type check
+      if ("range".equalsIgnoreCase(indexType)) {
+        idxType = IndexInfo.RANGE_INDEX;
+      } else if ("hash".equalsIgnoreCase(indexType)) {
+        idxType = IndexInfo.HASH_INDEX;
+      } else if ("key".equalsIgnoreCase(indexType)) {
+        idxType = IndexInfo.KEY_INDEX;
+      } else {
+        return ResultBuilder
+            .createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
+      }
+
+      if (indexName == null || indexName.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__NAME);
+      }
+
+      if (indexedExpression == null || indexedExpression.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__EXPRESSION);
+      }
+
+      if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
+        return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__REGIONPATH);
+      }
+
+      if (!regionPath.startsWith(Region.SEPARATOR)) {
+        regionPath = Region.SEPARATOR + regionPath;
+      }
+
+      IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
+      final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      final ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(createIndexFunction, indexInfo, targetMembers);
+
+      final List<Object> funcResults = (List<Object>) rc.getResult();
+      final Set<String> successfulMembers = new TreeSet<>();
+      final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
+
+      for (final Object funcResult : funcResults) {
+        if (funcResult instanceof CliFunctionResult) {
+          final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
+
+          if (cliFunctionResult.isSuccessful()) {
+            successfulMembers.add(cliFunctionResult.getMemberIdOrName());
+
+            if (xmlEntity.get() == null) {
+              xmlEntity.set(cliFunctionResult.getXmlEntity());
+            }
+          } else {
+            final String exceptionMessage = cliFunctionResult.getMessage();
+            Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
+
+            if (failedMembers == null) {
+              failedMembers = new TreeSet<>();
+            }
+            failedMembers.add(cliFunctionResult.getMemberIdOrName());
+            indexOpFailMap.put(exceptionMessage, failedMembers);
+          }
+        }
+      }
+
+      if (!successfulMembers.isEmpty()) {
+        final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+        infoResult.addLine(CliStrings.CREATE_INDEX__SUCCESS__MSG);
+        infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__NAME__MSG, indexName));
+        infoResult.addLine(
+            CliStrings.format(CliStrings.CREATE_INDEX__EXPRESSION__MSG, indexedExpression));
+        infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__REGIONPATH__MSG, regionPath));
+        infoResult.addLine(CliStrings.CREATE_INDEX__MEMBER__MSG);
+
+        int num = 0;
+
+        for (final String memberId : successfulMembers) {
+          ++num;
+          infoResult.addLine(
+              CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
+        }
+        result = ResultBuilder.buildResult(infoResult);
+
+      } else {
+        // Group members by the exception thrown.
+        final ErrorResultData erd = ResultBuilder.createErrorResultData();
+        erd.addLine(CliStrings.format(CliStrings.CREATE_INDEX__FAILURE__MSG, indexName));
+        final Set<String> exceptionMessages = indexOpFailMap.keySet();
+
+        for (final String exceptionMessage : exceptionMessages) {
+          erd.addLine(exceptionMessage);
+          erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
+          final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
+          int num = 0;
+          for (final String memberId : memberIds) {
+            ++num;
+            erd.addLine(
+                CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
+          }
+        }
+        result = ResultBuilder.buildResult(erd);
+      }
+    } catch (Exception e) {
+      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+    if (xmlEntity.get() != null) {
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
new file mode 100644
index 0000000..1102cd8
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.Region;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.domain.IndexInfo;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DefineIndexCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.DEFINE_INDEX, help = CliStrings.DEFINE_INDEX__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+  // TODO : Add optionContext for indexName
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
+  public Result defineIndex(
+      @CliOption(key = CliStrings.DEFINE_INDEX_NAME, mandatory = true,
+          help = CliStrings.DEFINE_INDEX__HELP) final String indexName,
+      @CliOption(key = CliStrings.DEFINE_INDEX__EXPRESSION, mandatory = true,
+          help = CliStrings.DEFINE_INDEX__EXPRESSION__HELP) final String indexedExpression,
+      @CliOption(key = CliStrings.DEFINE_INDEX__REGION, mandatory = true,
+          optionContext = ConverterHint.REGION_PATH,
+          help = CliStrings.DEFINE_INDEX__REGION__HELP) String regionPath,
+      @CliOption(key = CliStrings.DEFINE_INDEX__TYPE, unspecifiedDefaultValue = "range",
+          optionContext = ConverterHint.INDEX_TYPE,
+          help = CliStrings.DEFINE_INDEX__TYPE__HELP) final String indexType) {
+
+    Result result;
+    int idxType;
+
+    // Index type check
+    if ("range".equalsIgnoreCase(indexType)) {
+      idxType = IndexInfo.RANGE_INDEX;
+    } else if ("hash".equalsIgnoreCase(indexType)) {
+      idxType = IndexInfo.HASH_INDEX;
+    } else if ("key".equalsIgnoreCase(indexType)) {
+      idxType = IndexInfo.KEY_INDEX;
+    } else {
+      return ResultBuilder
+          .createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
+    }
+
+    if (indexName == null || indexName.isEmpty()) {
+      return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__NAME);
+    }
+
+    if (indexedExpression == null || indexedExpression.isEmpty()) {
+      return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__EXPRESSION);
+    }
+
+    if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
+      return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__REGIONPATH);
+    }
+
+    if (!regionPath.startsWith(Region.SEPARATOR)) {
+      regionPath = Region.SEPARATOR + regionPath;
+    }
+
+    IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
+    IndexDefinition.indexDefinitions.add(indexInfo);
+
+    final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+    infoResult.addLine(CliStrings.DEFINE_INDEX__SUCCESS__MSG);
+    infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__NAME__MSG, indexName));
+    infoResult
+        .addLine(CliStrings.format(CliStrings.DEFINE_INDEX__EXPRESSION__MSG, indexedExpression));
+    infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__REGIONPATH__MSG, regionPath));
+    result = ResultBuilder.buildResult(infoResult);
+
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyIndexCommand.java
new file mode 100644
index 0000000..c9f2b64
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyIndexCommand.java
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.IndexInfo;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.DestroyIndexFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DestroyIndexCommand implements GfshCommand {
+  private static final DestroyIndexFunction destroyIndexFunction = new DestroyIndexFunction();
+
+  @CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
+  public Result destroyIndex(
+      @CliOption(key = CliStrings.DESTROY_INDEX__NAME, unspecifiedDefaultValue = "",
+          help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName,
+
+      @CliOption(key = CliStrings.DESTROY_INDEX__REGION, optionContext = ConverterHint.REGION_PATH,
+          help = CliStrings.DESTROY_INDEX__REGION__HELP) final String regionPath,
+
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          optionContext = ConverterHint.MEMBERIDNAME,
+          help = CliStrings.DESTROY_INDEX__MEMBER__HELP) final String[] memberNameOrID,
+
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.DESTROY_INDEX__GROUP__HELP) final String[] group) {
+
+    Result result;
+
+    if (StringUtils.isBlank(indexName) && StringUtils.isBlank(regionPath)
+        && ArrayUtils.isEmpty(group) && ArrayUtils.isEmpty(memberNameOrID)) {
+      return ResultBuilder.createUserErrorResult(
+          CliStrings.format(CliStrings.PROVIDE_ATLEAST_ONE_OPTION, CliStrings.DESTROY_INDEX));
+    }
+
+    final Cache cache = CacheFactory.getAnyInstance();
+    String regionName = null;
+    if (regionPath != null) {
+      regionName = regionPath.startsWith("/") ? regionPath.substring(1) : regionPath;
+    }
+    IndexInfo indexInfo = new IndexInfo(indexName, regionName);
+    Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
+
+    if (targetMembers.isEmpty()) {
+      return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+    }
+
+    ResultCollector rc = CliUtil.executeFunction(destroyIndexFunction, indexInfo, targetMembers);
+    List<Object> funcResults = (List<Object>) rc.getResult();
+
+    Set<String> successfulMembers = new TreeSet<>();
+    Map<String, Set<String>> indexOpFailMap = new HashMap<>();
+
+    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+    for (Object funcResult : funcResults) {
+      if (!(funcResult instanceof CliFunctionResult)) {
+        continue;
+      }
+      CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
+
+      if (cliFunctionResult.isSuccessful()) {
+        successfulMembers.add(cliFunctionResult.getMemberIdOrName());
+        if (xmlEntity.get() == null) {
+          xmlEntity.set(cliFunctionResult.getXmlEntity());
+        }
+      } else {
+        String exceptionMessage = cliFunctionResult.getMessage();
+        Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
+
+        if (failedMembers == null) {
+          failedMembers = new TreeSet<>();
+        }
+        failedMembers.add(cliFunctionResult.getMemberIdOrName());
+        indexOpFailMap.put(exceptionMessage, failedMembers);
+      }
+    }
+    if (!successfulMembers.isEmpty()) {
+      InfoResultData infoResult = ResultBuilder.createInfoResultData();
+      if (StringUtils.isNotBlank(indexName)) {
+        if (StringUtils.isNotBlank(regionPath)) {
+          infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__SUCCESS__MSG,
+              indexName, regionPath));
+        } else {
+          infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__SUCCESS__MSG, indexName));
+        }
+      } else {
+        if (StringUtils.isNotBlank(regionPath)) {
+          infoResult.addLine(CliStrings
+              .format(CliStrings.DESTROY_INDEX__ON__REGION__ONLY__SUCCESS__MSG, regionPath));
+        } else {
+          infoResult.addLine(CliStrings.DESTROY_INDEX__ON__MEMBERS__ONLY__SUCCESS__MSG);
+        }
+      }
+      int num = 0;
+      for (String memberId : successfulMembers) {
+        infoResult.addLine(CliStrings.format(
+            CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
+      }
+      result = ResultBuilder.buildResult(infoResult);
+    } else {
+      ErrorResultData erd = ResultBuilder.createErrorResultData();
+      if (StringUtils.isNotBlank(indexName)) {
+        erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__FAILURE__MSG, indexName));
+      } else {
+        erd.addLine("Indexes could not be destroyed for following reasons");
+      }
+
+      Set<String> exceptionMessages = indexOpFailMap.keySet();
+
+      for (String exceptionMessage : exceptionMessages) {
+        erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__REASON_MESSAGE, exceptionMessage));
+        erd.addLine(CliStrings.DESTROY_INDEX__EXCEPTION__OCCURRED__ON);
+
+        Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
+        int num = 0;
+
+        for (String memberId : memberIds) {
+          erd.addLine(CliStrings.format(
+              CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
+        }
+        erd.addLine("");
+      }
+      result = ResultBuilder.buildResult(erd);
+    }
+    if (xmlEntity.get() != null) {
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), group));
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
deleted file mode 100644
index 4734b4c..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
+++ /dev/null
@@ -1,668 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.execute.AbstractExecution;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.IndexDetails;
-import org.apache.geode.management.internal.cli.domain.IndexDetails.IndexStatisticsDetails;
-import org.apache.geode.management.internal.cli.domain.IndexInfo;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.CreateDefinedIndexesFunction;
-import org.apache.geode.management.internal.cli.functions.CreateIndexFunction;
-import org.apache.geode.management.internal.cli.functions.DestroyIndexFunction;
-import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.geode.security.ResourcePermission.Target;
-
-/**
- * The IndexCommands class encapsulates all GemFire shell (Gfsh) commands related to indexes defined
- * in GemFire.
- *
- * @see GfshCommand
- * @see org.apache.geode.management.internal.cli.domain.IndexDetails
- * @see org.apache.geode.management.internal.cli.functions.ListIndexFunction
- * @since GemFire 7.0
- */
-@SuppressWarnings("unused")
-public class IndexCommands implements GfshCommand {
-
-  private static final CreateIndexFunction createIndexFunction = new CreateIndexFunction();
-  private static final DestroyIndexFunction destroyIndexFunction = new DestroyIndexFunction();
-  private static final CreateDefinedIndexesFunction createDefinedIndexesFunction =
-      new CreateDefinedIndexesFunction();
-  private static final Set<IndexInfo> indexDefinitions =
-      Collections.synchronizedSet(new HashSet<IndexInfo>());
-
-  @CliCommand(value = CliStrings.LIST_INDEX, help = CliStrings.LIST_INDEX__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ, target = Target.QUERY)
-  public Result listIndex(@CliOption(key = CliStrings.LIST_INDEX__STATS,
-      specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
-      help = CliStrings.LIST_INDEX__STATS__HELP) final boolean showStats) {
-    try {
-      return toTabularResult(getIndexListing(), showStats);
-    } catch (FunctionInvocationTargetException ignore) {
-      return ResultBuilder.createGemFireErrorResult(
-          CliStrings.format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_INDEX));
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable t) {
-      SystemFailure.checkFailure();
-      getCache().getLogger().error(t);
-      return ResultBuilder.createGemFireErrorResult(
-          String.format(CliStrings.LIST_INDEX__ERROR_MESSAGE, toString(t, isDebugging())));
-    }
-  }
-
-  @SuppressWarnings("unchecked")
-  protected List<IndexDetails> getIndexListing() {
-    final Execution functionExecutor = getMembersFunctionExecutor(getMembers(getCache()));
-
-    if (functionExecutor instanceof AbstractExecution) {
-      ((AbstractExecution) functionExecutor).setIgnoreDepartedMembers(true);
-    }
-
-    final ResultCollector<?, ?> resultsCollector =
-        functionExecutor.execute(new ListIndexFunction());
-
-    final List<?> results = (List<?>) resultsCollector.getResult();
-    final List<IndexDetails> indexDetailsList = new ArrayList<>(results.size());
-
-    for (Object result : results) {
-      if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other Exceptions
-        indexDetailsList.addAll((Set<IndexDetails>) result);
-      }
-    }
-
-    Collections.sort(indexDetailsList);
-
-    return indexDetailsList;
-  }
-
-  protected Result toTabularResult(final List<IndexDetails> indexDetailsList,
-      final boolean showStats) {
-    if (!indexDetailsList.isEmpty()) {
-      final TabularResultData indexData = ResultBuilder.createTabularResultData();
-
-      for (final IndexDetails indexDetails : indexDetailsList) {
-        indexData.accumulate("Member Name",
-            StringUtils.defaultString(indexDetails.getMemberName()));
-        indexData.accumulate("Member ID", indexDetails.getMemberId());
-        indexData.accumulate("Region Path", indexDetails.getRegionPath());
-        indexData.accumulate("Name", indexDetails.getIndexName());
-        indexData.accumulate("Type", StringUtils.defaultString(indexDetails.getIndexType()));
-        indexData.accumulate("Indexed Expression", indexDetails.getIndexedExpression());
-        indexData.accumulate("From Clause", indexDetails.getFromClause());
-
-        if (showStats) {
-          final IndexStatisticsDetailsAdapter adapter =
-              new IndexStatisticsDetailsAdapter(indexDetails.getIndexStatisticsDetails());
-
-          indexData.accumulate("Uses", adapter.getTotalUses());
-          indexData.accumulate("Updates", adapter.getNumberOfUpdates());
-          indexData.accumulate("Update Time", adapter.getTotalUpdateTime());
-          indexData.accumulate("Keys", adapter.getNumberOfKeys());
-          indexData.accumulate("Values", adapter.getNumberOfValues());
-        }
-      }
-
-      return ResultBuilder.buildResult(indexData);
-    } else {
-      return ResultBuilder.createInfoResult(CliStrings.LIST_INDEX__INDEXES_NOT_FOUND_MESSAGE);
-    }
-  }
-
-  @CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
-  // TODO : Add optionContext for indexName
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.QUERY)
-  public Result createIndex(@CliOption(key = CliStrings.CREATE_INDEX__NAME, mandatory = true,
-      help = CliStrings.CREATE_INDEX__NAME__HELP) final String indexName,
-
-      @CliOption(key = CliStrings.CREATE_INDEX__EXPRESSION, mandatory = true,
-          help = CliStrings.CREATE_INDEX__EXPRESSION__HELP) final String indexedExpression,
-
-      @CliOption(key = CliStrings.CREATE_INDEX__REGION, mandatory = true,
-          optionContext = ConverterHint.REGION_PATH,
-          help = CliStrings.CREATE_INDEX__REGION__HELP) String regionPath,
-
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          optionContext = ConverterHint.MEMBERIDNAME,
-          help = CliStrings.CREATE_INDEX__MEMBER__HELP) final String[] memberNameOrID,
-
-      @CliOption(key = CliStrings.CREATE_INDEX__TYPE, unspecifiedDefaultValue = "range",
-          optionContext = ConverterHint.INDEX_TYPE,
-          help = CliStrings.CREATE_INDEX__TYPE__HELP) final String indexType,
-
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.CREATE_INDEX__GROUP__HELP) final String[] group) {
-
-    Result result;
-    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
-    try {
-      final Cache cache = CacheFactory.getAnyInstance();
-
-      int idxType;
-
-      // Index type check
-      if ("range".equalsIgnoreCase(indexType)) {
-        idxType = IndexInfo.RANGE_INDEX;
-      } else if ("hash".equalsIgnoreCase(indexType)) {
-        idxType = IndexInfo.HASH_INDEX;
-      } else if ("key".equalsIgnoreCase(indexType)) {
-        idxType = IndexInfo.KEY_INDEX;
-      } else {
-        return ResultBuilder
-            .createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
-      }
-
-      if (indexName == null || indexName.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__NAME);
-      }
-
-      if (indexedExpression == null || indexedExpression.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__EXPRESSION);
-      }
-
-      if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
-        return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__REGIONPATH);
-      }
-
-      if (!regionPath.startsWith(Region.SEPARATOR)) {
-        regionPath = Region.SEPARATOR + regionPath;
-      }
-
-      IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
-
-      final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      final ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(createIndexFunction, indexInfo, targetMembers);
-
-      final List<Object> funcResults = (List<Object>) rc.getResult();
-      final Set<String> successfulMembers = new TreeSet<>();
-      final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
-
-      for (final Object funcResult : funcResults) {
-        if (funcResult instanceof CliFunctionResult) {
-          final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
-
-          if (cliFunctionResult.isSuccessful()) {
-            successfulMembers.add(cliFunctionResult.getMemberIdOrName());
-
-            if (xmlEntity.get() == null) {
-              xmlEntity.set(cliFunctionResult.getXmlEntity());
-            }
-          } else {
-            final String exceptionMessage = cliFunctionResult.getMessage();
-            Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
-
-            if (failedMembers == null) {
-              failedMembers = new TreeSet<>();
-            }
-            failedMembers.add(cliFunctionResult.getMemberIdOrName());
-            indexOpFailMap.put(exceptionMessage, failedMembers);
-          }
-        }
-      }
-
-      if (!successfulMembers.isEmpty()) {
-
-        final InfoResultData infoResult = ResultBuilder.createInfoResultData();
-        infoResult.addLine(CliStrings.CREATE_INDEX__SUCCESS__MSG);
-        infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__NAME__MSG, indexName));
-        infoResult.addLine(
-            CliStrings.format(CliStrings.CREATE_INDEX__EXPRESSION__MSG, indexedExpression));
-        infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__REGIONPATH__MSG, regionPath));
-        infoResult.addLine(CliStrings.CREATE_INDEX__MEMBER__MSG);
-
-        int num = 0;
-
-        for (final String memberId : successfulMembers) {
-          ++num;
-          infoResult.addLine(
-              CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
-        }
-        result = ResultBuilder.buildResult(infoResult);
-
-      } else {
-        // Group members by the exception thrown.
-        final ErrorResultData erd = ResultBuilder.createErrorResultData();
-        erd.addLine(CliStrings.format(CliStrings.CREATE_INDEX__FAILURE__MSG, indexName));
-
-        final Set<String> exceptionMessages = indexOpFailMap.keySet();
-
-        for (final String exceptionMessage : exceptionMessages) {
-          erd.addLine(exceptionMessage);
-          erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
-          final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
-
-          int num = 0;
-          for (final String memberId : memberIds) {
-            ++num;
-            erd.addLine(
-                CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
-          }
-        }
-        result = ResultBuilder.buildResult(erd);
-      }
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-
-    if (xmlEntity.get() != null) {
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
-    }
-
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.QUERY)
-  public Result destroyIndex(
-      @CliOption(key = CliStrings.DESTROY_INDEX__NAME, unspecifiedDefaultValue = "",
-          help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName,
-
-      @CliOption(key = CliStrings.DESTROY_INDEX__REGION, optionContext = ConverterHint.REGION_PATH,
-          help = CliStrings.DESTROY_INDEX__REGION__HELP) final String regionPath,
-
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          optionContext = ConverterHint.MEMBERIDNAME,
-          help = CliStrings.DESTROY_INDEX__MEMBER__HELP) final String[] memberNameOrID,
-
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.DESTROY_INDEX__GROUP__HELP) final String[] group) {
-
-    Result result;
-
-    if (StringUtils.isBlank(indexName) && StringUtils.isBlank(regionPath)
-        && ArrayUtils.isEmpty(group) && ArrayUtils.isEmpty(memberNameOrID)) {
-      return ResultBuilder.createUserErrorResult(
-          CliStrings.format(CliStrings.PROVIDE_ATLEAST_ONE_OPTION, CliStrings.DESTROY_INDEX));
-    }
-
-    final Cache cache = CacheFactory.getAnyInstance();
-    String regionName = null;
-    if (regionPath != null) {
-      regionName = regionPath.startsWith("/") ? regionPath.substring(1) : regionPath;
-    }
-    IndexInfo indexInfo = new IndexInfo(indexName, regionName);
-    Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
-
-    if (targetMembers.isEmpty()) {
-      return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-    }
-
-    ResultCollector rc = CliUtil.executeFunction(destroyIndexFunction, indexInfo, targetMembers);
-    List<Object> funcResults = (List<Object>) rc.getResult();
-
-    Set<String> successfulMembers = new TreeSet<>();
-    Map<String, Set<String>> indexOpFailMap = new HashMap<>();
-
-    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-    for (Object funcResult : funcResults) {
-      if (!(funcResult instanceof CliFunctionResult)) {
-        continue;
-      }
-
-      CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
-
-      if (cliFunctionResult.isSuccessful()) {
-        successfulMembers.add(cliFunctionResult.getMemberIdOrName());
-        if (xmlEntity.get() == null) {
-          xmlEntity.set(cliFunctionResult.getXmlEntity());
-        }
-      } else {
-        String exceptionMessage = cliFunctionResult.getMessage();
-        Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
-
-        if (failedMembers == null) {
-          failedMembers = new TreeSet<>();
-        }
-        failedMembers.add(cliFunctionResult.getMemberIdOrName());
-        indexOpFailMap.put(exceptionMessage, failedMembers);
-      }
-    }
-
-    if (!successfulMembers.isEmpty()) {
-      InfoResultData infoResult = ResultBuilder.createInfoResultData();
-
-      if (StringUtils.isNotBlank(indexName)) {
-        if (StringUtils.isNotBlank(regionPath)) {
-          infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__SUCCESS__MSG,
-              indexName, regionPath));
-        } else {
-          infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__SUCCESS__MSG, indexName));
-        }
-      } else {
-        if (StringUtils.isNotBlank(regionPath)) {
-          infoResult.addLine(CliStrings
-              .format(CliStrings.DESTROY_INDEX__ON__REGION__ONLY__SUCCESS__MSG, regionPath));
-        } else {
-          infoResult.addLine(CliStrings.DESTROY_INDEX__ON__MEMBERS__ONLY__SUCCESS__MSG);
-        }
-      }
-
-      int num = 0;
-      for (String memberId : successfulMembers) {
-        infoResult.addLine(CliStrings.format(
-            CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
-      }
-      result = ResultBuilder.buildResult(infoResult);
-
-    } else {
-
-      ErrorResultData erd = ResultBuilder.createErrorResultData();
-      if (StringUtils.isNotBlank(indexName)) {
-        erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__FAILURE__MSG, indexName));
-      } else {
-        erd.addLine("Indexes could not be destroyed for following reasons");
-      }
-
-      Set<String> exceptionMessages = indexOpFailMap.keySet();
-
-      for (String exceptionMessage : exceptionMessages) {
-        erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__REASON_MESSAGE, exceptionMessage));
-        erd.addLine(CliStrings.DESTROY_INDEX__EXCEPTION__OCCURRED__ON);
-
-        Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
-        int num = 0;
-
-        for (String memberId : memberIds) {
-          erd.addLine(CliStrings.format(
-              CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
-        }
-        erd.addLine("");
-      }
-      result = ResultBuilder.buildResult(erd);
-    }
-    if (xmlEntity.get() != null) {
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), group));
-    }
-
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.DEFINE_INDEX, help = CliStrings.DEFINE_INDEX__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
-  // TODO : Add optionContext for indexName
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.QUERY)
-  public Result defineIndex(@CliOption(key = CliStrings.DEFINE_INDEX_NAME, mandatory = true,
-      help = CliStrings.DEFINE_INDEX__HELP) final String indexName,
-
-      @CliOption(key = CliStrings.DEFINE_INDEX__EXPRESSION, mandatory = true,
-          help = CliStrings.DEFINE_INDEX__EXPRESSION__HELP) final String indexedExpression,
-
-      @CliOption(key = CliStrings.DEFINE_INDEX__REGION, mandatory = true,
-          optionContext = ConverterHint.REGION_PATH,
-          help = CliStrings.DEFINE_INDEX__REGION__HELP) String regionPath,
-
-      @CliOption(key = CliStrings.DEFINE_INDEX__TYPE, unspecifiedDefaultValue = "range",
-          optionContext = ConverterHint.INDEX_TYPE,
-          help = CliStrings.DEFINE_INDEX__TYPE__HELP) final String indexType) {
-
-    Result result;
-    XmlEntity xmlEntity = null;
-
-    int idxType;
-
-    // Index type check
-    if ("range".equalsIgnoreCase(indexType)) {
-      idxType = IndexInfo.RANGE_INDEX;
-    } else if ("hash".equalsIgnoreCase(indexType)) {
-      idxType = IndexInfo.HASH_INDEX;
-    } else if ("key".equalsIgnoreCase(indexType)) {
-      idxType = IndexInfo.KEY_INDEX;
-    } else {
-      return ResultBuilder
-          .createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
-    }
-
-    if (indexName == null || indexName.isEmpty()) {
-      return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__NAME);
-    }
-
-    if (indexedExpression == null || indexedExpression.isEmpty()) {
-      return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__EXPRESSION);
-    }
-
-    if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
-      return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__REGIONPATH);
-    }
-
-    if (!regionPath.startsWith(Region.SEPARATOR)) {
-      regionPath = Region.SEPARATOR + regionPath;
-    }
-
-    IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
-    indexDefinitions.add(indexInfo);
-
-    final InfoResultData infoResult = ResultBuilder.createInfoResultData();
-    infoResult.addLine(CliStrings.DEFINE_INDEX__SUCCESS__MSG);
-    infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__NAME__MSG, indexName));
-    infoResult
-        .addLine(CliStrings.format(CliStrings.DEFINE_INDEX__EXPRESSION__MSG, indexedExpression));
-    infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__REGIONPATH__MSG, regionPath));
-    result = ResultBuilder.buildResult(infoResult);
-
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.CREATE_DEFINED_INDEXES, help = CliStrings.CREATE_DEFINED__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.QUERY)
-  // TODO : Add optionContext for indexName
-  public Result createDefinedIndexes(
-
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          optionContext = ConverterHint.MEMBERIDNAME,
-          help = CliStrings.CREATE_DEFINED_INDEXES__MEMBER__HELP) final String[] memberNameOrID,
-
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.CREATE_DEFINED_INDEXES__GROUP__HELP) final String[] group) {
-
-    Result result;
-    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
-    if (indexDefinitions.isEmpty()) {
-      final InfoResultData infoResult = ResultBuilder.createInfoResultData();
-      infoResult.addLine(CliStrings.DEFINE_INDEX__FAILURE__MSG);
-      return ResultBuilder.buildResult(infoResult);
-    }
-
-    try {
-      final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      final Cache cache = CacheFactory.getAnyInstance();
-      final ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(createDefinedIndexesFunction, indexDefinitions, targetMembers);
-
-      final List<Object> funcResults = (List<Object>) rc.getResult();
-      final Set<String> successfulMembers = new TreeSet<>();
-      final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
-
-      for (final Object funcResult : funcResults) {
-        if (funcResult instanceof CliFunctionResult) {
-          final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
-
-          if (cliFunctionResult.isSuccessful()) {
-            successfulMembers.add(cliFunctionResult.getMemberIdOrName());
-
-            if (xmlEntity.get() == null) {
-              xmlEntity.set(cliFunctionResult.getXmlEntity());
-            }
-          } else {
-            final String exceptionMessage = cliFunctionResult.getMessage();
-            Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
-
-            if (failedMembers == null) {
-              failedMembers = new TreeSet<>();
-            }
-            failedMembers.add(cliFunctionResult.getMemberIdOrName());
-            indexOpFailMap.put(exceptionMessage, failedMembers);
-          }
-        }
-      }
-
-      if (!successfulMembers.isEmpty()) {
-        final InfoResultData infoResult = ResultBuilder.createInfoResultData();
-        infoResult.addLine(CliStrings.CREATE_DEFINED_INDEXES__SUCCESS__MSG);
-
-        int num = 0;
-
-        for (final String memberId : successfulMembers) {
-          ++num;
-          infoResult.addLine(CliStrings
-              .format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER, num, memberId));
-        }
-        result = ResultBuilder.buildResult(infoResult);
-
-      } else {
-        // Group members by the exception thrown.
-        final ErrorResultData erd = ResultBuilder.createErrorResultData();
-
-        final Set<String> exceptionMessages = indexOpFailMap.keySet();
-
-        for (final String exceptionMessage : exceptionMessages) {
-          erd.addLine(exceptionMessage);
-          erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
-          final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
-
-          int num = 0;
-          for (final String memberId : memberIds) {
-            ++num;
-            erd.addLine(CliStrings.format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER,
-                num, memberId));
-          }
-        }
-        result = ResultBuilder.buildResult(erd);
-      }
-    } catch (Exception e) {
-      result = ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-
-    if (xmlEntity.get() != null) {
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
-    }
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.CLEAR_DEFINED_INDEXES, help = CliStrings.CLEAR_DEFINED__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
-      target = Target.QUERY)
-  // TODO : Add optionContext for indexName
-  public Result clearDefinedIndexes() {
-    indexDefinitions.clear();
-    final InfoResultData infoResult = ResultBuilder.createInfoResultData();
-    infoResult.addLine(CliStrings.CLEAR_DEFINED_INDEX__SUCCESS__MSG);
-    return ResultBuilder.buildResult(infoResult);
-  }
-
-  protected static class IndexStatisticsDetailsAdapter {
-
-    private final IndexStatisticsDetails indexStatisticsDetails;
-
-    protected IndexStatisticsDetailsAdapter(final IndexStatisticsDetails indexStatisticsDetails) {
-      this.indexStatisticsDetails = indexStatisticsDetails;
-    }
-
-    public IndexStatisticsDetails getIndexStatisticsDetails() {
-      return indexStatisticsDetails;
-    }
-
-    public String getNumberOfKeys() {
-      return getIndexStatisticsDetails() != null
-          ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfKeys()) : "";
-    }
-
-    public String getNumberOfUpdates() {
-      return getIndexStatisticsDetails() != null
-          ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfUpdates()) : "";
-    }
-
-    public String getNumberOfValues() {
-      return getIndexStatisticsDetails() != null
-          ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfValues()) : "";
-    }
-
-    public String getTotalUpdateTime() {
-      return getIndexStatisticsDetails() != null
-          ? StringUtils.defaultString(getIndexStatisticsDetails().getTotalUpdateTime()) : "";
-    }
-
-    public String getTotalUses() {
-      return getIndexStatisticsDetails() != null
-          ? StringUtils.defaultString(getIndexStatisticsDetails().getTotalUses()) : "";
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexDefinition.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexDefinition.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexDefinition.java
new file mode 100644
index 0000000..2cf9f83
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexDefinition.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.geode.management.internal.cli.domain.IndexInfo;
+
+class IndexDefinition {
+  static final Set<IndexInfo> indexDefinitions =
+      Collections.synchronizedSet(new HashSet<IndexInfo>());
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListIndexCommand.java
new file mode 100644
index 0000000..847426c
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListIndexCommand.java
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.internal.cache.execute.AbstractExecution;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.domain.IndexDetails;
+import org.apache.geode.management.internal.cli.domain.IndexDetails.IndexStatisticsDetails;
+import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ListIndexCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.LIST_INDEX, help = CliStrings.LIST_INDEX__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ, target = ResourcePermission.Target.QUERY)
+  public Result listIndex(@CliOption(key = CliStrings.LIST_INDEX__STATS,
+      specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
+      help = CliStrings.LIST_INDEX__STATS__HELP) final boolean showStats) {
+    try {
+      return toTabularResult(getIndexListing(), showStats);
+    } catch (FunctionInvocationTargetException ignore) {
+      return ResultBuilder.createGemFireErrorResult(
+          CliStrings.format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_INDEX));
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable t) {
+      SystemFailure.checkFailure();
+      getCache().getLogger().error(t);
+      return ResultBuilder.createGemFireErrorResult(
+          String.format(CliStrings.LIST_INDEX__ERROR_MESSAGE, toString(t, isDebugging())));
+    }
+  }
+
+  private Result toTabularResult(final List<IndexDetails> indexDetailsList,
+      final boolean showStats) {
+    if (!indexDetailsList.isEmpty()) {
+      final TabularResultData indexData = ResultBuilder.createTabularResultData();
+
+      for (final IndexDetails indexDetails : indexDetailsList) {
+        indexData.accumulate("Member Name",
+            StringUtils.defaultString(indexDetails.getMemberName()));
+        indexData.accumulate("Member ID", indexDetails.getMemberId());
+        indexData.accumulate("Region Path", indexDetails.getRegionPath());
+        indexData.accumulate("Name", indexDetails.getIndexName());
+        indexData.accumulate("Type", StringUtils.defaultString(indexDetails.getIndexType()));
+        indexData.accumulate("Indexed Expression", indexDetails.getIndexedExpression());
+        indexData.accumulate("From Clause", indexDetails.getFromClause());
+
+        if (showStats) {
+          final IndexStatisticsDetailsAdapter adapter =
+              new IndexStatisticsDetailsAdapter(indexDetails.getIndexStatisticsDetails());
+
+          indexData.accumulate("Uses", adapter.getTotalUses());
+          indexData.accumulate("Updates", adapter.getNumberOfUpdates());
+          indexData.accumulate("Update Time", adapter.getTotalUpdateTime());
+          indexData.accumulate("Keys", adapter.getNumberOfKeys());
+          indexData.accumulate("Values", adapter.getNumberOfValues());
+        }
+      }
+
+      return ResultBuilder.buildResult(indexData);
+    } else {
+      return ResultBuilder.createInfoResult(CliStrings.LIST_INDEX__INDEXES_NOT_FOUND_MESSAGE);
+    }
+  }
+
+  List<IndexDetails> getIndexListing() {
+    final Execution functionExecutor = getMembersFunctionExecutor(getMembers(getCache()));
+
+    if (functionExecutor instanceof AbstractExecution) {
+      ((AbstractExecution) functionExecutor).setIgnoreDepartedMembers(true);
+    }
+
+    final ResultCollector<?, ?> resultsCollector =
+        functionExecutor.execute(new ListIndexFunction());
+    final List<?> results = (List<?>) resultsCollector.getResult();
+    final List<IndexDetails> indexDetailsList = new ArrayList<>(results.size());
+
+    for (Object result : results) {
+      if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other Exceptions
+        indexDetailsList.addAll((Set<IndexDetails>) result);
+      }
+    }
+    Collections.sort(indexDetailsList);
+    return indexDetailsList;
+  }
+
+  protected static class IndexStatisticsDetailsAdapter {
+
+    private final IndexStatisticsDetails indexStatisticsDetails;
+
+    protected IndexStatisticsDetailsAdapter(final IndexStatisticsDetails indexStatisticsDetails) {
+      this.indexStatisticsDetails = indexStatisticsDetails;
+    }
+
+    public IndexStatisticsDetails getIndexStatisticsDetails() {
+      return indexStatisticsDetails;
+    }
+
+    public String getNumberOfKeys() {
+      return getIndexStatisticsDetails() != null
+          ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfKeys()) : "";
+    }
+
+    public String getNumberOfUpdates() {
+      return getIndexStatisticsDetails() != null
+          ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfUpdates()) : "";
+    }
+
+    public String getNumberOfValues() {
+      return getIndexStatisticsDetails() != null
+          ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfValues()) : "";
+    }
+
+    public String getTotalUpdateTime() {
+      return getIndexStatisticsDetails() != null
+          ? StringUtils.defaultString(getIndexStatisticsDetails().getTotalUpdateTime()) : "";
+    }
+
+    public String getTotalUses() {
+      return getIndexStatisticsDetails() != null
+          ? StringUtils.defaultString(getIndexStatisticsDetails().getTotalUses()) : "";
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java
index 742840c..47cdb27 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java
@@ -14,7 +14,6 @@
  */
 package org.apache.geode.management.internal.cli.functions;
 
-import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -38,7 +37,7 @@ public class CreateDefinedIndexesFunction extends FunctionAdapter implements Int
   public void execute(FunctionContext context) {
     String memberId = null;
     List<Index> indexes = null;
-    Cache cache = null;
+    Cache cache;
     try {
       cache = CacheFactory.getAnyInstance();
       memberId = cache.getDistributedSystem().getDistributedMember().getId();

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java
index 296156f..09d7f9a 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java
@@ -14,9 +14,6 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -24,11 +21,19 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+
 /**
  * The IndexCommandsController class implements the REST API calls for the Gfsh Index commands.
  * </p>
  * 
- * @see org.apache.geode.management.internal.cli.commands.IndexCommands
+ * @see org.apache.geode.management.internal.cli.commands.ClearDefinedIndexesCommand
+ * @see org.apache.geode.management.internal.cli.commands.CreateDefinedIndexesCommand
+ * @see org.apache.geode.management.internal.cli.commands.CreateIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.DefineIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.DestroyIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.ListIndexCommand
  * @see org.apache.geode.management.internal.cli.util.CommandStringBuilder
  * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
  * @see org.springframework.stereotype.Controller

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/IndexCommandsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/IndexCommandsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/IndexCommandsJUnitTest.java
deleted file mode 100644
index 0d1f340..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/IndexCommandsJUnitTest.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.cache.execute.AbstractExecution;
-import org.apache.geode.internal.util.CollectionUtils;
-import org.apache.geode.management.internal.cli.domain.IndexDetails;
-import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
-import org.apache.geode.test.junit.categories.UnitTest;
-
-/**
- * The IndexCommandsJUnitTest class is a test suite of test cases testing the contract and
- * functionality of the IndexCommands class.
- * </p>
- * 
- * @see org.apache.geode.management.internal.cli.commands.IndexCommands
- * @see org.apache.geode.management.internal.cli.domain.IndexDetails
- * @see org.apache.geode.management.internal.cli.functions.ListIndexFunction
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.jmock.lib.legacy.ClassImposteriser
- * @see org.junit.Assert
- * @see org.junit.Test
- * @since GemFire 7.0
- */
-@Category(UnitTest.class)
-public class IndexCommandsJUnitTest {
-
-  private Mockery mockContext;
-
-  @Before
-  public void setup() {
-    mockContext = new Mockery() {
-      {
-        setImposteriser(ClassImposteriser.INSTANCE);
-        setThreadingPolicy(new Synchroniser());
-      }
-    };
-  }
-
-  @After
-  public void tearDown() {
-    mockContext.assertIsSatisfied();
-    mockContext = null;
-  }
-
-  private IndexCommands createIndexCommands(final InternalCache cache,
-      final Execution functionExecutor) {
-    return new TestIndexCommands(cache, functionExecutor);
-  }
-
-  private IndexDetails createIndexDetails(final String memberId, final String regionPath,
-      final String indexName) {
-    return new IndexDetails(memberId, regionPath, indexName);
-  }
-
-  @Test
-  public void testGetIndexListing() {
-    final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
-    final AbstractExecution mockFunctionExecutor =
-        mockContext.mock(AbstractExecution.class, "Function Executor");
-
-    final ResultCollector mockResultCollector =
-        mockContext.mock(ResultCollector.class, "ResultCollector");
-
-    final IndexDetails indexDetails1 = createIndexDetails("memberOne", "/Employees", "empIdIdx");
-    final IndexDetails indexDetails2 =
-        createIndexDetails("memberOne", "/Employees", "empLastNameIdx");
-    final IndexDetails indexDetails3 = createIndexDetails("memberTwo", "/Employees", "empDobIdx");
-
-    final List<IndexDetails> expectedIndexDetails =
-        Arrays.asList(indexDetails1, indexDetails2, indexDetails3);
-
-    final List<Set<IndexDetails>> results = new ArrayList<Set<IndexDetails>>(2);
-
-    results.add(CollectionUtils.asSet(indexDetails2, indexDetails1));
-    results.add(CollectionUtils.asSet(indexDetails3));
-
-    mockContext.checking(new Expectations() {
-      {
-        oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
-        oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
-        will(returnValue(mockResultCollector));
-        oneOf(mockResultCollector).getResult();
-        will(returnValue(results));
-      }
-    });
-
-    final IndexCommands commands = createIndexCommands(mockCache, mockFunctionExecutor);
-
-    final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
-
-    assertNotNull(actualIndexDetails);
-    assertEquals(expectedIndexDetails, actualIndexDetails);
-  }
-
-  @Test(expected = RuntimeException.class)
-  public void testGetIndexListingThrowsRuntimeException() {
-    final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
-    final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
-
-    mockContext.checking(new Expectations() {
-      {
-        oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
-        will(throwException(new RuntimeException("expected")));
-      }
-    });
-
-    final IndexCommands commands = createIndexCommands(mockCache, mockFunctionExecutor);
-
-    try {
-      commands.getIndexListing();
-    } catch (RuntimeException expected) {
-      assertEquals("expected", expected.getMessage());
-      throw expected;
-    }
-  }
-
-  @Test
-  public void testGetIndexListingReturnsFunctionInvocationTargetExceptionInResults() {
-    final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
-    final AbstractExecution mockFunctionExecutor =
-        mockContext.mock(AbstractExecution.class, "Function Executor");
-
-    final ResultCollector mockResultCollector =
-        mockContext.mock(ResultCollector.class, "ResultCollector");
-
-    final IndexDetails indexDetails = createIndexDetails("memberOne", "/Employees", "empIdIdx");
-
-    final List<IndexDetails> expectedIndexDetails = Arrays.asList(indexDetails);
-
-    final List<Object> results = new ArrayList<Object>(2);
-
-    results.add(CollectionUtils.asSet(indexDetails));
-    results.add(new FunctionInvocationTargetException("expected"));
-
-    mockContext.checking(new Expectations() {
-      {
-        oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
-        oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
-        will(returnValue(mockResultCollector));
-        oneOf(mockResultCollector).getResult();
-        will(returnValue(results));
-      }
-    });
-
-    final IndexCommands commands = createIndexCommands(mockCache, mockFunctionExecutor);
-
-    final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
-
-    assertNotNull(actualIndexDetails);
-    assertEquals(expectedIndexDetails, actualIndexDetails);
-  }
-
-  private static class TestIndexCommands extends IndexCommands {
-
-    private final InternalCache cache;
-    private final Execution functionExecutor;
-
-    protected TestIndexCommands(final InternalCache cache, final Execution functionExecutor) {
-      assert cache != null : "The InternalCache cannot be null!";
-      assert functionExecutor != null : "The function executor cannot be null!";
-      this.cache = cache;
-      this.functionExecutor = functionExecutor;
-    }
-
-    @Override
-    public InternalCache getCache() {
-      return this.cache;
-    }
-
-    @Override
-    public Set<DistributedMember> getMembers(final InternalCache cache) {
-      assertSame(getCache(), cache);
-      return Collections.emptySet();
-    }
-
-    @Override
-    public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
-      Assert.assertNotNull(members);
-      return functionExecutor;
-    }
-  }
-
-}


[08/47] geode git commit: GEODE-3436: Restore refactoring of RegionCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of RegionCommands

* See initial commits GEODE-3268 (64de3b69c2aecb4930bcfd0a1161569b1d5fda89), GEODE-3255 (756efe77c86bb03ac9984655e7bd040659e85890)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 6aab662413b22320a8342d1006f98fd4473de6df
Parents: 50dd10b
Author: YehEmily <em...@gmail.com>
Authored: Mon Aug 7 13:58:08 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:24 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/DescribeRegionCommand.java     | 372 +++++++++++++++
 .../cli/commands/ListRegionCommand.java         | 113 +++++
 .../internal/cli/commands/RegionCommands.java   | 474 -------------------
 .../controllers/RegionCommandsController.java   |   7 +-
 .../internal/security/TestCommand.java          |   2 +-
 5 files changed, 490 insertions(+), 478 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/6aab6624/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeRegionCommand.java
new file mode 100644
index 0000000..eb74793
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeRegionCommand.java
@@ -0,0 +1,372 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.domain.FixedPartitionAttributesInfo;
+import org.apache.geode.management.internal.cli.domain.RegionDescription;
+import org.apache.geode.management.internal.cli.domain.RegionDescriptionPerMember;
+import org.apache.geode.management.internal.cli.functions.GetRegionDescriptionFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.cli.util.RegionAttributesNames;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DescribeRegionCommand implements GfshCommand {
+  private static final GetRegionDescriptionFunction getRegionDescription =
+      new GetRegionDescriptionFunction();
+
+  @CliCommand(value = {CliStrings.DESCRIBE_REGION}, help = CliStrings.DESCRIBE_REGION__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_CONFIG})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result describeRegion(
+      @CliOption(key = CliStrings.DESCRIBE_REGION__NAME, optionContext = ConverterHint.REGION_PATH,
+          help = CliStrings.DESCRIBE_REGION__NAME__HELP, mandatory = true) String regionName) {
+
+    Result result;
+    try {
+
+      if (regionName == null || regionName.isEmpty()) {
+        return ResultBuilder.createUserErrorResult("Please provide a region name");
+      }
+
+      if (regionName.equals(Region.SEPARATOR)) {
+        return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
+      }
+
+      InternalCache cache = getCache();
+      ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(getRegionDescription, regionName, CliUtil.getAllMembers(cache));
+
+      List<?> resultList = (List<?>) rc.getResult();
+
+      // The returned result could be a region description with per member and /or single local
+      // region
+      Object[] results = resultList.toArray();
+      List<RegionDescription> regionDescriptionList = new ArrayList<>();
+
+      for (int i = 0; i < results.length; i++) {
+
+        if (results[i] instanceof RegionDescriptionPerMember) {
+          RegionDescriptionPerMember regionDescPerMember = (RegionDescriptionPerMember) results[i];
+
+          if (regionDescPerMember != null) {
+            RegionDescription regionDescription = new RegionDescription();
+            regionDescription.add(regionDescPerMember);
+
+            for (int j = i + 1; j < results.length; j++) {
+              if (results[j] != null && results[j] instanceof RegionDescriptionPerMember) {
+                RegionDescriptionPerMember preyRegionDescPerMember =
+                    (RegionDescriptionPerMember) results[j];
+                if (regionDescription.add(preyRegionDescPerMember)) {
+                  results[j] = null;
+                }
+              }
+            }
+            regionDescriptionList.add(regionDescription);
+          }
+        } else if (results[i] instanceof Throwable) {
+          Throwable t = (Throwable) results[i];
+          LogWrapper.getInstance().info(t.getMessage(), t);
+        }
+      }
+
+      if (regionDescriptionList.isEmpty()) {
+        return ResultBuilder
+            .createUserErrorResult(CliStrings.format(CliStrings.REGION_NOT_FOUND, regionName));
+      }
+
+      CompositeResultData crd = ResultBuilder.createCompositeResultData();
+
+      for (RegionDescription regionDescription : regionDescriptionList) {
+        // No point in displaying the scope for PR's
+        if (regionDescription.isPartition()) {
+          regionDescription.getCndRegionAttributes().remove(RegionAttributesNames.SCOPE);
+        } else {
+          String scope =
+              regionDescription.getCndRegionAttributes().get(RegionAttributesNames.SCOPE);
+          if (scope != null) {
+            scope = scope.toLowerCase().replace('_', '-');
+            regionDescription.getCndRegionAttributes().put(RegionAttributesNames.SCOPE, scope);
+          }
+        }
+        CompositeResultData.SectionResultData regionSection = crd.addSection();
+        regionSection.addSeparator('-');
+        regionSection.addData("Name", regionDescription.getName());
+
+        String dataPolicy =
+            regionDescription.getDataPolicy().toString().toLowerCase().replace('_', ' ');
+        regionSection.addData("Data Policy", dataPolicy);
+
+        String memberType;
+
+        if (regionDescription.isAccessor()) {
+          memberType = CliStrings.DESCRIBE_REGION__ACCESSOR__MEMBER;
+        } else {
+          memberType = CliStrings.DESCRIBE_REGION__HOSTING__MEMBER;
+        }
+        regionSection.addData(memberType,
+            CliUtil.convertStringSetToString(regionDescription.getHostingMembers(), '\n'));
+        regionSection.addSeparator('.');
+
+        TabularResultData commonNonDefaultAttrTable = regionSection.addSection().addTable();
+
+        commonNonDefaultAttrTable.setHeader(CliStrings
+            .format(CliStrings.DESCRIBE_REGION__NONDEFAULT__COMMONATTRIBUTES__HEADER, memberType));
+        // Common Non Default Region Attributes
+        Map<String, String> cndRegionAttrsMap = regionDescription.getCndRegionAttributes();
+
+        // Common Non Default Eviction Attributes
+        Map<String, String> cndEvictionAttrsMap = regionDescription.getCndEvictionAttributes();
+
+        // Common Non Default Partition Attributes
+        Map<String, String> cndPartitionAttrsMap = regionDescription.getCndPartitionAttributes();
+
+        writeCommonAttributesToTable(commonNonDefaultAttrTable,
+            CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, cndRegionAttrsMap);
+        writeCommonAttributesToTable(commonNonDefaultAttrTable,
+            CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION, cndEvictionAttrsMap);
+        writeCommonAttributesToTable(commonNonDefaultAttrTable,
+            CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__PARTITION, cndPartitionAttrsMap);
+
+        // Member-wise non default Attributes
+        Map<String, RegionDescriptionPerMember> regDescPerMemberMap =
+            regionDescription.getRegionDescriptionPerMemberMap();
+        Set<String> members = regDescPerMemberMap.keySet();
+
+        TabularResultData table = regionSection.addSection().addTable();
+
+        boolean setHeader = false;
+        for (String member : members) {
+          RegionDescriptionPerMember regDescPerMem = regDescPerMemberMap.get(member);
+          Map<String, String> ndRa = regDescPerMem.getNonDefaultRegionAttributes();
+          Map<String, String> ndEa = regDescPerMem.getNonDefaultEvictionAttributes();
+          Map<String, String> ndPa = regDescPerMem.getNonDefaultPartitionAttributes();
+
+          // Get all the member-specific non-default attributes by removing the common keys
+          ndRa.keySet().removeAll(cndRegionAttrsMap.keySet());
+          ndEa.keySet().removeAll(cndEvictionAttrsMap.keySet());
+          ndPa.keySet().removeAll(cndPartitionAttrsMap.keySet());
+
+          // Scope is not valid for PR's
+          if (regionDescription.isPartition()) {
+            if (ndRa.get(RegionAttributesNames.SCOPE) != null) {
+              ndRa.remove(RegionAttributesNames.SCOPE);
+            }
+          }
+
+          List<FixedPartitionAttributesInfo> fpaList = regDescPerMem.getFixedPartitionAttributes();
+
+          if (!(ndRa.isEmpty() && ndEa.isEmpty() && ndPa.isEmpty()) || fpaList != null) {
+            setHeader = true;
+            boolean memberNameAdded;
+            memberNameAdded = writeAttributesToTable(table,
+                CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, ndRa, member, false);
+            memberNameAdded =
+                writeAttributesToTable(table, CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION,
+                    ndEa, member, memberNameAdded);
+            memberNameAdded = writeAttributesToTable(table,
+                CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__PARTITION, ndPa, member,
+                memberNameAdded);
+
+            writeFixedPartitionAttributesToTable(table, fpaList, member, memberNameAdded);
+          }
+        }
+
+        if (setHeader) {
+          table.setHeader(CliStrings.format(
+              CliStrings.DESCRIBE_REGION__NONDEFAULT__PERMEMBERATTRIBUTES__HEADER, memberType));
+        }
+      }
+
+      result = ResultBuilder.buildResult(crd);
+    } catch (FunctionInvocationTargetException e) {
+      result = ResultBuilder.createGemFireErrorResult(CliStrings
+          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_REGION));
+    } catch (Exception e) {
+      String errorMessage = CliStrings.format(CliStrings.EXCEPTION_CLASS_AND_MESSAGE,
+          e.getClass().getName(), e.getMessage());
+      result = ResultBuilder.createGemFireErrorResult(errorMessage);
+    }
+    return result;
+  }
+
+  private void writeCommonAttributesToTable(TabularResultData table, String attributeType,
+      Map<String, String> attributesMap) {
+    if (!attributesMap.isEmpty()) {
+      Set<String> attributes = attributesMap.keySet();
+      boolean isTypeAdded = false;
+      final String blank = "";
+
+      for (String attributeName : attributes) {
+        String attributeValue = attributesMap.get(attributeName);
+        String type, memName;
+
+        if (!isTypeAdded) {
+          type = attributeType;
+          isTypeAdded = true;
+        } else {
+          type = blank;
+        }
+        writeCommonAttributeToTable(table, type, attributeName, attributeValue);
+      }
+    }
+  }
+
+  private void writeFixedPartitionAttributesToTable(TabularResultData table,
+      List<FixedPartitionAttributesInfo> fpaList, String member, boolean isMemberNameAdded) {
+
+    if (fpaList != null) {
+      boolean isTypeAdded = false;
+      final String blank = "";
+
+      Iterator<FixedPartitionAttributesInfo> fpaIter = fpaList.iterator();
+      String type, memName;
+
+      while (fpaIter.hasNext()) {
+        FixedPartitionAttributesInfo fpa = fpaIter.next();
+        StringBuilder fpaBuilder = new StringBuilder();
+        fpaBuilder.append(fpa.getPartitionName());
+        fpaBuilder.append(',');
+
+        if (fpa.isPrimary()) {
+          fpaBuilder.append("Primary");
+        } else {
+          fpaBuilder.append("Secondary");
+        }
+        fpaBuilder.append(',');
+        fpaBuilder.append(fpa.getNumBuckets());
+
+        if (!isTypeAdded) {
+          type = "";
+          isTypeAdded = true;
+        } else {
+          type = blank;
+        }
+
+        if (!isMemberNameAdded) {
+          memName = member;
+          isMemberNameAdded = true;
+        } else {
+          memName = blank;
+        }
+
+        writeAttributeToTable(table, memName, type, "Fixed Partition", fpaBuilder.toString());
+      }
+    }
+
+  }
+
+  private boolean writeAttributesToTable(TabularResultData table, String attributeType,
+      Map<String, String> attributesMap, String member, boolean isMemberNameAdded) {
+    if (!attributesMap.isEmpty()) {
+      Set<String> attributes = attributesMap.keySet();
+      boolean isTypeAdded = false;
+      final String blank = "";
+
+      for (String attributeName : attributes) {
+        String attributeValue = attributesMap.get(attributeName);
+        String type, memName;
+
+        if (!isTypeAdded) {
+          type = attributeType;
+          isTypeAdded = true;
+        } else {
+          type = blank;
+        }
+
+        if (!isMemberNameAdded) {
+          memName = member;
+          isMemberNameAdded = true;
+        } else {
+          memName = blank;
+        }
+
+        writeAttributeToTable(table, memName, type, attributeName, attributeValue);
+      }
+    }
+
+    return isMemberNameAdded;
+  }
+
+  private void writeAttributeToTable(TabularResultData table, String member, String attributeType,
+      String attributeName, String attributeValue) {
+
+    final String blank = "";
+    if (attributeValue != null) {
+      // Tokenize the attributeValue
+      String[] attributeValues = attributeValue.split(",");
+      boolean isFirstValue = true;
+
+      for (String value : attributeValues) {
+        if (isFirstValue) {
+          table.accumulate(CliStrings.DESCRIBE_REGION__MEMBER, member);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, attributeType);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, attributeName);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
+          isFirstValue = false;
+        } else {
+          table.accumulate(CliStrings.DESCRIBE_REGION__MEMBER, blank);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, blank);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, blank);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
+        }
+      }
+    }
+  }
+
+  private void writeCommonAttributeToTable(TabularResultData table, String attributeType,
+      String attributeName, String attributeValue) {
+    final String blank = "";
+    if (attributeValue != null) {
+      String[] attributeValues = attributeValue.split(",");
+      boolean isFirstValue = true;
+      for (String value : attributeValues) {
+        if (isFirstValue) {
+          isFirstValue = false;
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, attributeType);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, attributeName);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
+        } else {
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, blank);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, blank);
+          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
+        }
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/6aab6624/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListRegionCommand.java
new file mode 100644
index 0000000..1ca310c
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListRegionCommand.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.RegionInformation;
+import org.apache.geode.management.internal.cli.functions.GetRegionsFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ListRegionCommand implements GfshCommand {
+  private static final GetRegionsFunction getRegionsFunction = new GetRegionsFunction();
+
+  @CliCommand(value = {CliStrings.LIST_REGION}, help = CliStrings.LIST_REGION__HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result listRegion(
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.LIST_REGION__GROUP__HELP) String[] group,
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          optionContext = ConverterHint.MEMBERIDNAME,
+          help = CliStrings.LIST_REGION__MEMBER__HELP) String[] memberNameOrId) {
+    Result result = null;
+    try {
+      Set<RegionInformation> regionInfoSet = new LinkedHashSet<>();
+      ResultCollector<?, ?> rc;
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      TabularResultData resultData = ResultBuilder.createTabularResultData();
+      rc = CliUtil.executeFunction(getRegionsFunction, null, targetMembers);
+      ArrayList<?> resultList = (ArrayList<?>) rc.getResult();
+
+      if (resultList != null) {
+
+        for (Object resultObj : resultList) {
+          if (resultObj != null) {
+            if (resultObj instanceof Object[]) {
+              Object[] resultObjectArray = (Object[]) resultObj;
+              for (Object regionInfo : resultObjectArray) {
+                if (regionInfo instanceof RegionInformation) {
+                  regionInfoSet.add((RegionInformation) regionInfo);
+                }
+              }
+            }
+          }
+        }
+
+        Set<String> regionNames = new TreeSet<>();
+
+        for (RegionInformation regionInfo : regionInfoSet) {
+          regionNames.add(regionInfo.getName());
+          Set<String> subRegionNames = regionInfo.getSubRegionNames();
+
+          regionNames.addAll(subRegionNames);
+        }
+
+        for (String regionName : regionNames) {
+          resultData.accumulate("List of regions", regionName);
+        }
+
+        if (!regionNames.isEmpty()) {
+          result = ResultBuilder.buildResult(resultData);
+
+        } else {
+          result = ResultBuilder.createInfoResult(CliStrings.LIST_REGION__MSG__NOT_FOUND);
+        }
+      }
+    } catch (FunctionInvocationTargetException e) {
+      result = ResultBuilder.createGemFireErrorResult(CliStrings
+          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_REGION));
+    } catch (Exception e) {
+      result = ResultBuilder
+          .createGemFireErrorResult(CliStrings.LIST_REGION__MSG__ERROR + " : " + e.getMessage());
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/6aab6624/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
deleted file mode 100644
index 3222666..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
+++ /dev/null
@@ -1,474 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.domain.FixedPartitionAttributesInfo;
-import org.apache.geode.management.internal.cli.domain.RegionDescription;
-import org.apache.geode.management.internal.cli.domain.RegionDescriptionPerMember;
-import org.apache.geode.management.internal.cli.domain.RegionInformation;
-import org.apache.geode.management.internal.cli.functions.GetRegionDescriptionFunction;
-import org.apache.geode.management.internal.cli.functions.GetRegionsFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.util.RegionAttributesNames;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-
-/**
- * Class containing implementation of commands based on region:
- * <ul>
- * <li>list region
- * <li>describe region
- * </ul>
- * 
- * @since GemFire 7.0
- */
-public class RegionCommands implements GfshCommand {
-  private static final GetRegionsFunction getRegionsFunction = new GetRegionsFunction();
-  private static final GetRegionDescriptionFunction getRegionDescription =
-      new GetRegionDescriptionFunction();
-
-  @CliCommand(value = {CliStrings.LIST_REGION}, help = CliStrings.LIST_REGION__HELP)
-  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result listRegion(
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.LIST_REGION__GROUP__HELP) String[] group,
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          optionContext = ConverterHint.MEMBERIDNAME,
-          help = CliStrings.LIST_REGION__MEMBER__HELP) String[] memberNameOrId) {
-    Result result = null;
-    try {
-      Set<RegionInformation> regionInfoSet = new LinkedHashSet<>();
-      ResultCollector<?, ?> rc;
-
-      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
-      if (targetMembers.isEmpty()) {
-        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-      }
-
-      TabularResultData resultData = ResultBuilder.createTabularResultData();
-      rc = CliUtil.executeFunction(getRegionsFunction, null, targetMembers);
-
-      ArrayList<?> resultList = (ArrayList<?>) rc.getResult();
-
-      if (resultList != null) {
-
-        for (Object resultObj : resultList) {
-          if (resultObj != null) {
-            if (resultObj instanceof Object[]) {
-              Object[] resultObjectArray = (Object[]) resultObj;
-              for (Object regionInfo : resultObjectArray) {
-                if (regionInfo instanceof RegionInformation) {
-                  regionInfoSet.add((RegionInformation) regionInfo);
-                }
-              }
-            }
-          }
-        }
-
-        Set<String> regionNames = new TreeSet<>();
-
-        for (RegionInformation regionInfo : regionInfoSet) {
-          regionNames.add(regionInfo.getName());
-          Set<String> subRegionNames = regionInfo.getSubRegionNames();
-
-          regionNames.addAll(subRegionNames);
-        }
-
-        for (String regionName : regionNames) {
-          resultData.accumulate("List of regions", regionName);
-        }
-
-        if (!regionNames.isEmpty()) {
-          result = ResultBuilder.buildResult(resultData);
-
-        } else {
-          result = ResultBuilder.createInfoResult(CliStrings.LIST_REGION__MSG__NOT_FOUND);
-        }
-      }
-    } catch (FunctionInvocationTargetException e) {
-      result = ResultBuilder.createGemFireErrorResult(CliStrings
-          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_REGION));
-    } catch (Exception e) {
-      result = ResultBuilder
-          .createGemFireErrorResult(CliStrings.LIST_REGION__MSG__ERROR + " : " + e.getMessage());
-    }
-    return result;
-  }
-
-  @CliCommand(value = {CliStrings.DESCRIBE_REGION}, help = CliStrings.DESCRIBE_REGION__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_CONFIG})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result describeRegion(
-      @CliOption(key = CliStrings.DESCRIBE_REGION__NAME, optionContext = ConverterHint.REGION_PATH,
-          help = CliStrings.DESCRIBE_REGION__NAME__HELP, mandatory = true) String regionName) {
-
-    Result result;
-    try {
-
-      if (regionName == null || regionName.isEmpty()) {
-        return ResultBuilder.createUserErrorResult("Please provide a region name");
-      }
-
-      if (regionName.equals(Region.SEPARATOR)) {
-        return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
-      }
-
-      InternalCache cache = getCache();
-      ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(getRegionDescription, regionName, CliUtil.getAllMembers(cache));
-
-      List<?> resultList = (List<?>) rc.getResult();
-
-      // The returned result could be a region description with per member and /or single local
-      // region
-      Object[] results = resultList.toArray();
-      List<RegionDescription> regionDescriptionList = new ArrayList<>();
-
-      for (int i = 0; i < results.length; i++) {
-
-        if (results[i] instanceof RegionDescriptionPerMember) {
-          RegionDescriptionPerMember regionDescPerMember = (RegionDescriptionPerMember) results[i];
-
-          if (regionDescPerMember != null) {
-            RegionDescription regionDescription = new RegionDescription();
-            regionDescription.add(regionDescPerMember);
-
-            for (int j = i + 1; j < results.length; j++) {
-              if (results[j] != null && results[j] instanceof RegionDescriptionPerMember) {
-                RegionDescriptionPerMember preyRegionDescPerMember =
-                    (RegionDescriptionPerMember) results[j];
-                if (regionDescription.add(preyRegionDescPerMember)) {
-                  results[j] = null;
-                }
-              }
-            }
-            regionDescriptionList.add(regionDescription);
-          }
-        } else if (results[i] instanceof Throwable) {
-          Throwable t = (Throwable) results[i];
-          LogWrapper.getInstance().info(t.getMessage(), t);
-        }
-      }
-
-      if (regionDescriptionList.isEmpty()) {
-        return ResultBuilder
-            .createUserErrorResult(CliStrings.format(CliStrings.REGION_NOT_FOUND, regionName));
-      }
-
-      CompositeResultData crd = ResultBuilder.createCompositeResultData();
-
-      for (RegionDescription regionDescription : regionDescriptionList) {
-        // No point in displaying the scope for PR's
-        if (regionDescription.isPartition()) {
-          regionDescription.getCndRegionAttributes().remove(RegionAttributesNames.SCOPE);
-        } else {
-          String scope =
-              regionDescription.getCndRegionAttributes().get(RegionAttributesNames.SCOPE);
-          if (scope != null) {
-            scope = scope.toLowerCase().replace('_', '-');
-            regionDescription.getCndRegionAttributes().put(RegionAttributesNames.SCOPE, scope);
-          }
-        }
-        SectionResultData regionSection = crd.addSection();
-        regionSection.addSeparator('-');
-        regionSection.addData("Name", regionDescription.getName());
-
-        String dataPolicy =
-            regionDescription.getDataPolicy().toString().toLowerCase().replace('_', ' ');
-        regionSection.addData("Data Policy", dataPolicy);
-
-        String memberType;
-
-        if (regionDescription.isAccessor()) {
-          memberType = CliStrings.DESCRIBE_REGION__ACCESSOR__MEMBER;
-        } else {
-          memberType = CliStrings.DESCRIBE_REGION__HOSTING__MEMBER;
-        }
-        regionSection.addData(memberType,
-            CliUtil.convertStringSetToString(regionDescription.getHostingMembers(), '\n'));
-        regionSection.addSeparator('.');
-
-        TabularResultData commonNonDefaultAttrTable = regionSection.addSection().addTable();
-
-        commonNonDefaultAttrTable.setHeader(CliStrings
-            .format(CliStrings.DESCRIBE_REGION__NONDEFAULT__COMMONATTRIBUTES__HEADER, memberType));
-        // Common Non Default Region Attributes
-        Map<String, String> cndRegionAttrsMap = regionDescription.getCndRegionAttributes();
-
-        // Common Non Default Eviction Attributes
-        Map<String, String> cndEvictionAttrsMap = regionDescription.getCndEvictionAttributes();
-
-        // Common Non Default Partition Attributes
-        Map<String, String> cndPartitionAttrsMap = regionDescription.getCndPartitionAttributes();
-
-        writeCommonAttributesToTable(commonNonDefaultAttrTable,
-            CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, cndRegionAttrsMap);
-        writeCommonAttributesToTable(commonNonDefaultAttrTable,
-            CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION, cndEvictionAttrsMap);
-        writeCommonAttributesToTable(commonNonDefaultAttrTable,
-            CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__PARTITION, cndPartitionAttrsMap);
-
-        // Member-wise non default Attributes
-        Map<String, RegionDescriptionPerMember> regDescPerMemberMap =
-            regionDescription.getRegionDescriptionPerMemberMap();
-        Set<String> members = regDescPerMemberMap.keySet();
-
-        TabularResultData table = regionSection.addSection().addTable();
-
-        boolean setHeader = false;
-        for (String member : members) {
-          RegionDescriptionPerMember regDescPerMem = regDescPerMemberMap.get(member);
-          Map<String, String> ndRa = regDescPerMem.getNonDefaultRegionAttributes();
-          Map<String, String> ndEa = regDescPerMem.getNonDefaultEvictionAttributes();
-          Map<String, String> ndPa = regDescPerMem.getNonDefaultPartitionAttributes();
-
-          // Get all the member-specific non-default attributes by removing the common keys
-          ndRa.keySet().removeAll(cndRegionAttrsMap.keySet());
-          ndEa.keySet().removeAll(cndEvictionAttrsMap.keySet());
-          ndPa.keySet().removeAll(cndPartitionAttrsMap.keySet());
-
-          // Scope is not valid for PR's
-          if (regionDescription.isPartition()) {
-            if (ndRa.get(RegionAttributesNames.SCOPE) != null) {
-              ndRa.remove(RegionAttributesNames.SCOPE);
-            }
-          }
-
-          List<FixedPartitionAttributesInfo> fpaList = regDescPerMem.getFixedPartitionAttributes();
-
-          if (!(ndRa.isEmpty() && ndEa.isEmpty() && ndPa.isEmpty()) || fpaList != null) {
-            setHeader = true;
-            boolean memberNameAdded;
-            memberNameAdded = writeAttributesToTable(table,
-                CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, ndRa, member, false);
-            memberNameAdded =
-                writeAttributesToTable(table, CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION,
-                    ndEa, member, memberNameAdded);
-            memberNameAdded = writeAttributesToTable(table,
-                CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__PARTITION, ndPa, member,
-                memberNameAdded);
-
-            writeFixedPartitionAttributesToTable(table, "", fpaList, member, memberNameAdded);
-          }
-        }
-
-        if (setHeader) {
-          table.setHeader(CliStrings.format(
-              CliStrings.DESCRIBE_REGION__NONDEFAULT__PERMEMBERATTRIBUTES__HEADER, memberType));
-        }
-      }
-
-      result = ResultBuilder.buildResult(crd);
-    } catch (FunctionInvocationTargetException e) {
-      result = ResultBuilder.createGemFireErrorResult(CliStrings
-          .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_REGION));
-    } catch (Exception e) {
-      String errorMessage = CliStrings.format(CliStrings.EXCEPTION_CLASS_AND_MESSAGE,
-          e.getClass().getName(), e.getMessage());
-      result = ResultBuilder.createGemFireErrorResult(errorMessage);
-    }
-    return result;
-  }
-
-  private void writeCommonAttributesToTable(TabularResultData table, String attributeType,
-      Map<String, String> attributesMap) {
-    if (!attributesMap.isEmpty()) {
-      Set<String> attributes = attributesMap.keySet();
-      boolean isTypeAdded = false;
-      final String blank = "";
-
-      for (String attributeName : attributes) {
-        String attributeValue = attributesMap.get(attributeName);
-        String type, memName;
-
-        if (!isTypeAdded) {
-          type = attributeType;
-          isTypeAdded = true;
-        } else {
-          type = blank;
-        }
-        writeCommonAttributeToTable(table, type, attributeName, attributeValue);
-      }
-    }
-  }
-
-  private boolean writeFixedPartitionAttributesToTable(TabularResultData table,
-      String attributeType, List<FixedPartitionAttributesInfo> fpaList, String member,
-      boolean isMemberNameAdded) {
-
-    if (fpaList != null) {
-      boolean isTypeAdded = false;
-      final String blank = "";
-
-      Iterator<FixedPartitionAttributesInfo> fpaIter = fpaList.iterator();
-      String type, memName;
-
-      while (fpaIter.hasNext()) {
-        FixedPartitionAttributesInfo fpa = fpaIter.next();
-        StringBuilder fpaBuilder = new StringBuilder();
-        fpaBuilder.append(fpa.getPartitionName());
-        fpaBuilder.append(',');
-
-        if (fpa.isPrimary()) {
-          fpaBuilder.append("Primary");
-        } else {
-          fpaBuilder.append("Secondary");
-        }
-        fpaBuilder.append(',');
-        fpaBuilder.append(fpa.getNumBuckets());
-
-        if (!isTypeAdded) {
-          type = attributeType;
-          isTypeAdded = true;
-        } else {
-          type = blank;
-        }
-
-        if (!isMemberNameAdded) {
-          memName = member;
-          isMemberNameAdded = true;
-        } else {
-          memName = blank;
-        }
-
-        writeAttributeToTable(table, memName, type, "Fixed Partition", fpaBuilder.toString());
-      }
-    }
-
-    return isMemberNameAdded;
-  }
-
-  private boolean writeAttributesToTable(TabularResultData table, String attributeType,
-      Map<String, String> attributesMap, String member, boolean isMemberNameAdded) {
-    if (!attributesMap.isEmpty()) {
-      Set<String> attributes = attributesMap.keySet();
-      boolean isTypeAdded = false;
-      final String blank = "";
-
-      for (String attributeName : attributes) {
-        String attributeValue = attributesMap.get(attributeName);
-        String type, memName;
-
-        if (!isTypeAdded) {
-          type = attributeType;
-          isTypeAdded = true;
-        } else {
-          type = blank;
-        }
-
-        if (!isMemberNameAdded) {
-          memName = member;
-          isMemberNameAdded = true;
-        } else {
-          memName = blank;
-        }
-
-        writeAttributeToTable(table, memName, type, attributeName, attributeValue);
-      }
-    }
-
-    return isMemberNameAdded;
-  }
-
-  public void writeAttributeToTable(TabularResultData table, String member, String attributeType,
-      String attributeName, String attributeValue) {
-
-    final String blank = "";
-    if (attributeValue != null) {
-      // Tokenize the attributeValue
-      String[] attributeValues = attributeValue.split(",");
-      boolean isFirstValue = true;
-
-      for (String value : attributeValues) {
-        if (isFirstValue) {
-          table.accumulate(CliStrings.DESCRIBE_REGION__MEMBER, member);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, attributeType);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, attributeName);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
-          isFirstValue = false;
-        } else {
-          table.accumulate(CliStrings.DESCRIBE_REGION__MEMBER, blank);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, blank);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, blank);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
-        }
-      }
-    }
-  }
-
-
-  private void writeCommonAttributeToTable(TabularResultData table, String attributeType,
-      String attributeName, String attributeValue) {
-    final String blank = "";
-
-    if (attributeValue != null) {
-      String[] attributeValues = attributeValue.split(",");
-      boolean isFirstValue = true;
-      for (String value : attributeValues) {
-        if (isFirstValue) {
-          isFirstValue = false;
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, attributeType);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, attributeName);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
-        } else {
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, blank);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, blank);
-          table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
-        }
-      }
-    }
-  }
-
-  public void addChildSection(SectionResultData parentSection, Map<String, String> map,
-      String header) {
-    if (!map.isEmpty()) {
-      Set<String> attributes = map.keySet();
-      SectionResultData section = parentSection.addSection();
-      section.setHeader(header);
-      for (String attribute : attributes) {
-        section.addData(attribute, map.get(attribute));
-      }
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/6aab6624/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
index 21f85bf..6d30d74 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
@@ -26,11 +26,12 @@ import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.context.request.WebRequest;
 
 /**
- * The RegionCommands class implements GemFire Management REST API web service endpoints for the
- * Gfsh Region Commands.
+ * The ListRegionCommand and DescribeRegionCommand classes implement GemFire Management REST API web
+ * service endpoints for the Gfsh Region Commands.
  * <p/>
  * 
- * @see org.apache.geode.management.internal.cli.commands.RegionCommands
+ * @see org.apache.geode.management.internal.cli.commands.ListRegionCommand
+ * @see org.apache.geode.management.internal.cli.commands.DescribeRegionCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.PathVariable

http://git-wip-us.apache.org/repos/asf/geode/blob/6aab6624/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index f681f5c..d382646 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -246,7 +246,7 @@ public class TestCommand {
 
     createTestCommand("list async-event-queues", clusterRead);
 
-    // RegionCommands
+    // DescribeRegionCommand, ListRegionCommand
     createTestCommand("describe region --name=value", clusterRead);
     createTestCommand("list regions", clusterRead);
 


[46/47] geode git commit: GEODE-3330 Correct doc of CQ authorization permissions

Posted by ds...@apache.org.
GEODE-3330 Correct doc of CQ authorization permissions


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

Branch: refs/heads/feature/GEODE-3543
Commit: 6a7442c83307ce10b0d294736f717cd91e037bd5
Parents: 7417d73
Author: Karen Miller <km...@pivotal.io>
Authored: Wed Aug 30 15:49:56 2017 -0700
Committer: Karen Miller <km...@pivotal.io>
Committed: Wed Aug 30 16:00:54 2017 -0700

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


http://git-wip-us.apache.org/repos/asf/geode/blob/6a7442c8/geode-docs/managing/security/implementing_authorization.html.md.erb
----------------------------------------------------------------------
diff --git a/geode-docs/managing/security/implementing_authorization.html.md.erb b/geode-docs/managing/security/implementing_authorization.html.md.erb
index e78b294..9baa094 100644
--- a/geode-docs/managing/security/implementing_authorization.html.md.erb
+++ b/geode-docs/managing/security/implementing_authorization.html.md.erb
@@ -103,8 +103,8 @@ a Client-Server interaction.
 | Region.destroy(key)                | DATA:WRITE:RegionName:Key           |
 | Region.put(key)                    | DATA:WRITE:RegionName:Key           |
 | Region.replace                     | DATA:WRITE:RegionName:Key           |
-| CqQuery.execute                    | DATA:READ and CLUSTER:MANAGE:QUERY  |
-| CqQuery.executeWithInitialResults  | DATA:READ and CLUSTER:MANAGE:QUERY  |
+| CqQuery.execute                    | DATA:READ:RegionName and CLUSTER:MANAGE:QUERY  |
+| CqQuery.executeWithInitialResults  | DATA:READ:RegionName and CLUSTER:MANAGE:QUERY  |
 
 
 This table classifies the permissions assigned for `gfsh` operations.


[36/47] geode git commit: GEODE-3538: make RequiresGeodeHome Serializable

Posted by ds...@apache.org.
GEODE-3538: make RequiresGeodeHome Serializable


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

Branch: refs/heads/feature/GEODE-3543
Commit: 1ea345168cce3f0f20a1e24baf02b4ab48a810f9
Parents: c287d98
Author: Kirk Lund <kl...@apache.org>
Authored: Tue Aug 29 13:41:10 2017 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Tue Aug 29 14:32:53 2017 -0700

----------------------------------------------------------------------
 .../org/apache/geode/test/dunit/rules/RequiresGeodeHome.java    | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/1ea34516/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/RequiresGeodeHome.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/RequiresGeodeHome.java b/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/RequiresGeodeHome.java
index 02f474f..88e5f3a 100644
--- a/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/RequiresGeodeHome.java
+++ b/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/RequiresGeodeHome.java
@@ -20,13 +20,14 @@ import static org.junit.Assert.assertNotNull;
 
 import java.io.File;
 
-import org.junit.rules.ExternalResource;
+import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
 
 /**
  * This {@code Rule} is used to indicate tests that require the GEODE_HOME environment varible to be
  * set. (For example, any test that relies on the assembled Pulse WAR or GFSH binary.)
  */
-public class RequiresGeodeHome extends ExternalResource {
+public class RequiresGeodeHome extends SerializableExternalResource {
+
   private static final String GEODE_HOME_NOT_SET_MESSAGE =
       "This test requires a GEODE_HOME environment variable that points to the location "
           + "of geode-assembly/build/install/apache-geode." + LINE_SEPARATOR


[41/47] geode git commit: GEODE-3472: Remove a great deal of commented-out code.

Posted by ds...@apache.org.
GEODE-3472: Remove a great deal of commented-out code.

* this closes #748


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

Branch: refs/heads/feature/GEODE-3543
Commit: fb9a405f78a1efd3fb3033ff36e9065e8b545ec3
Parents: 76b4ef5
Author: Patrick Rhomberg <pr...@pivotal.io>
Authored: Fri Aug 18 13:59:44 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Wed Aug 30 09:34:06 2017 -0700

----------------------------------------------------------------------
 .../geode/management/GemFireProperties.java     |  43 +---
 .../cli/CommandProcessingException.java         |   1 -
 .../geode/management/cli/CommandService.java    |  47 +----
 .../management/internal/MBeanJMXAdapter.java    | 199 +++++++------------
 .../management/internal/ManagementAgent.java    |  70 ++++---
 .../internal/SystemManagementService.java       |   5 +-
 .../internal/beans/MBeanAggregator.java         |   7 +-
 .../internal/beans/ManagementAdapter.java       |  46 ++---
 .../internal/beans/stats/VMStatsMonitor.java    |  14 +-
 .../geode/management/internal/cli/CliUtil.java  | 107 +++-------
 .../internal/cli/CommandResponseBuilder.java    |  27 +--
 .../geode/management/internal/cli/Launcher.java |  11 +-
 .../management/internal/cli/LogWrapper.java     |  44 +---
 .../internal/cli/commands/ConnectCommand.java   |  68 +++----
 .../internal/cli/commands/ShellCommands.java    |  35 ++--
 .../cli/commands/ShowMetricsCommand.java        |   3 -
 .../internal/cli/commands/StartMemberUtils.java |  24 +--
 .../cli/converters/MemberGroupConverter.java    |  11 +-
 .../internal/cli/domain/DataCommandResult.java  |  14 +-
 .../cli/functions/DataCommandFunction.java      |  10 -
 .../internal/cli/i18n/CliStrings.java           |  54 +----
 .../cli/remote/CommandExecutionContext.java     |  15 +-
 .../internal/cli/result/AbstractResultData.java |  49 ++---
 .../internal/cli/result/CommandResult.java      |  96 +++------
 .../cli/result/CompositeResultData.java         |  19 +-
 .../internal/cli/result/ResultBuilder.java      |  17 +-
 .../internal/cli/result/ResultData.java         |   6 +-
 .../internal/cli/result/TableBuilder.java       |   9 +-
 .../management/internal/cli/shell/Gfsh.java     |  84 +++-----
 .../cli/shell/GfshExecutionStrategy.java        |  11 -
 .../internal/cli/shell/JmxOperationInvoker.java |  27 +--
 .../cli/shell/unsafe/GfshSignalHandler.java     |  13 +-
 .../internal/cli/util/ReadWriteFile.java        |  78 +++-----
 .../configuration/domain/CacheElement.java      |  20 +-
 .../configuration/domain/XmlEntity.java         |  50 +++--
 .../messages/ConfigurationRequest.java          |  18 +-
 .../internal/configuration/utils/XmlUtils.java  |  60 +++---
 .../web/controllers/DataCommandsController.java |   7 +-
 .../controllers/RegionCommandsController.java   |  13 +-
 .../controllers/ShellCommandsController.java    |  63 +++---
 .../cli/commands/FunctionCommandsDUnitTest.java |  19 +-
 41 files changed, 491 insertions(+), 1023 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/GemFireProperties.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/GemFireProperties.java b/geode-core/src/main/java/org/apache/geode/management/GemFireProperties.java
index 6257967..c892abd 100644
--- a/geode-core/src/main/java/org/apache/geode/management/GemFireProperties.java
+++ b/geode-core/src/main/java/org/apache/geode/management/GemFireProperties.java
@@ -94,7 +94,7 @@ public class GemFireProperties {
    * same package.
    * 
    * The peer and server parameters are optional. They specify whether the locator can be used for
-   * peers to discover eachother, or for clients to discover peers. By default both are true.
+   * peers to discover each other, or for clients to discover peers. By default both are true.
    * Default: "" (doesn't start a locator)
    **/
   private String startLocator;
@@ -163,26 +163,6 @@ public class GemFireProperties {
    * file deletion.
    **/
   private int logDiskSpaceLimit;
-  // /**
-  // * If true, all gemfire socket communication is configured to use SSL through
-  // * JSSE.
-  // **/
-  // private boolean sslEnabled;
-  // /**
-  // * A space seperated list of the SSL cipher suites to enable. Those listed
-  // * must be supported by the available providers.
-  // **/
-  // private String sslCiphers;
-  // /**
-  // * A space seperated list of the SSL protocols to enable. Those listed must be
-  // * supported by the available providers.
-  // **/
-  // private String sslProtocols;
-  // /**
-  // * If false, allow ciphers that do not require the client side of the
-  // * connection to be authenticated.
-  // **/
-  // private boolean sslRequireAuthentication;
   /**
    * The number of milliseconds a thread can keep exclusive access to a socket that it is not
    * actively using. Once a thread loses its lease to a socket it will need to re-acquire a socket
@@ -993,26 +973,6 @@ public class GemFireProperties {
 
   }
 
-  // public void setSSLEnabled(boolean sslEnabled) {
-  // this.sslEnabled = sslEnabled;
-  //
-  // }
-  //
-  // public void setSSLCiphers(String sslCiphers) {
-  // this.sslCiphers = sslCiphers;
-  //
-  // }
-  //
-  // public void setSSLProtocols(String sslProtocols) {
-  // this.sslProtocols = sslProtocols;
-  //
-  // }
-  //
-  // public void setSSLRequireAuthentication(boolean sslRequireAuthentication) {
-  // this.sslRequireAuthentication = sslRequireAuthentication;
-  //
-  // }
-
   public void setSocketLeaseTime(int socketLeaseTime) {
     this.socketLeaseTime = socketLeaseTime;
 
@@ -1288,7 +1248,6 @@ public class GemFireProperties {
   }
 
   public void setJmxManagerHttpPort(int jmxManagerHttpPort) {
-    // this.jmxManagerHttpPort = jmxManagerHttpPort;
     setHttpServicePort(jmxManagerHttpPort);
   }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/cli/CommandProcessingException.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/cli/CommandProcessingException.java b/geode-core/src/main/java/org/apache/geode/management/cli/CommandProcessingException.java
index 5f8c10f..1511da0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/cli/CommandProcessingException.java
+++ b/geode-core/src/main/java/org/apache/geode/management/cli/CommandProcessingException.java
@@ -53,7 +53,6 @@ public class CommandProcessingException extends RuntimeException {
    * Error Type indicating the absence of value for named parameter of a command.
    */
   public static int OPTION_VALUE_REQUIRED = 9;
-  // public static int ARGUMENT_VALUE_REQUIRED = 10;
   /**
    * Error Type indicating IO errors occurred while accessing File/Network resource
    */

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/cli/CommandService.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/cli/CommandService.java b/geode-core/src/main/java/org/apache/geode/management/cli/CommandService.java
index 55957b2..20f1c75 100644
--- a/geode-core/src/main/java/org/apache/geode/management/cli/CommandService.java
+++ b/geode-core/src/main/java/org/apache/geode/management/cli/CommandService.java
@@ -113,16 +113,12 @@ public abstract class CommandService {
           "Can not create command service as cache doesn't exist or cache is closed.");
     }
 
-    /*
-     * if (!cache.isServer()) { throw new IllegalArgumentException("Server cache is required."); }
-     */
-
     if (localCommandService == null || !localCommandService.isUsable()) {
       String nonExistingDependency = CliUtil.cliDependenciesExist(false);
       if (nonExistingDependency != null) {
         throw new DependenciesNotFoundException(
             LocalizedStrings.CommandServiceManager_COULD_NOT_FIND__0__LIB_NEEDED_FOR_CLI_GFSH
-                .toLocalizedString(new Object[] {nonExistingDependency}));
+                .toLocalizedString(nonExistingDependency));
       }
 
       localCommandService = new MemberCommandService((InternalCache) cache);
@@ -144,45 +140,4 @@ public abstract class CommandService {
 
     return null;
   }
-
-  // public static CommandService createCommandService(RegionService regionService) {
-  // if (regionService == null || regionService.isClosed()) {
-  // throw new CacheClosedException("Can not create command service as region service doesn't exist
-  // or cache is closed.");
-  // }
-  //
-  // CommandService commandService;
-  //
-  // if (Cache.class.isInstance(regionService) &&
-  // ((Cache) regionService).isServer() &&
-  // CacheFactory.getAnyInstance() == regionService) {
-  // commandService = createLocalCommandService((Cache) regionService);
-  // } else {
-  // Pool poolToUse = null;
-  // if (ProxyCache.class.isInstance(regionService)) {
-  // ProxyCache proxyCache = (ProxyCache) regionService;
-  // poolToUse = proxyCache.getUserAttributes().getPool();
-  // } else if (ClientCache.class.isInstance(regionService)) {
-  // ClientCache localCache = (ClientCache) regionService;
-  // poolToUse = localCache.getDefaultPool();
-  // } else {
-  // throw new IllegalArgumentException("Can not create Command Service for given Region Service: "
-  // + regionService);
-  // }
-  // commandService = new ProxyCommandService(poolToUse);
-  // }
-  //
-  // return commandService;
-  // }
-  //
-  // public static CommandService createRemoteCommandService(String poolName) {
-  // Pool poolToUse = PoolManager.find(poolName);
-  //
-  // if (poolToUse == null) {
-  // throw new IllegalArgumentException("Can not create Command Service as a Pool with name \"" +
-  // poolName+"\" was not found.");
-  // }
-  //
-  // return new ProxyCommandService(poolToUse);
-  // }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/MBeanJMXAdapter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/MBeanJMXAdapter.java b/geode-core/src/main/java/org/apache/geode/management/internal/MBeanJMXAdapter.java
index d375ac8..8d6b2e8 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/MBeanJMXAdapter.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/MBeanJMXAdapter.java
@@ -72,16 +72,11 @@ public class MBeanJMXAdapter implements ManagementConstants {
   private DistributedMember distMember;
 
   /**
-   * log writer, or null if there is no distributed system available
-   */
-  // private LogWriterI18n logger = InternalDistributedSystem.getLoggerI18n();
-
-  /**
    * public constructor
    */
 
   public MBeanJMXAdapter() {
-    this.localGemFireMBean = new ConcurrentHashMap<ObjectName, Object>();
+    this.localGemFireMBean = new ConcurrentHashMap<>();
     this.distMember = InternalDistributedSystem.getConnectedInstance().getDistributedMember();
   }
 
@@ -95,7 +90,7 @@ public class MBeanJMXAdapter implements ManagementConstants {
    * 
    * @param object
    * @param objectName
-   * @return modifed ObjectName
+   * @return modified ObjectName
    */
   public ObjectName registerMBean(Object object, ObjectName objectName, boolean isGemFireMBean) {
     ObjectName newObjectName = objectName;
@@ -110,15 +105,8 @@ public class MBeanJMXAdapter implements ManagementConstants {
       mbeanServer.registerMBean(object, newObjectName);
       this.localGemFireMBean.put(newObjectName, object);
 
-    } catch (InstanceAlreadyExistsException e) {
-      throw new ManagementException(e);
-    } catch (MBeanRegistrationException e) {
-      throw new ManagementException(e);
-    } catch (NotCompliantMBeanException e) {
-      throw new ManagementException(e);
-    } catch (MalformedObjectNameException e) {
-      throw new ManagementException(e);
-    } catch (NullPointerException e) {
+    } catch (InstanceAlreadyExistsException | NullPointerException | MalformedObjectNameException
+        | NotCompliantMBeanException | MBeanRegistrationException e) {
       throw new ManagementException(e);
     }
     return newObjectName;
@@ -139,19 +127,17 @@ public class MBeanJMXAdapter implements ManagementConstants {
       String className = instance.getClassName();
       Class cls = ClassLoadUtil.classFromName(className);
       Type[] intfTyps = cls.getGenericInterfaces();
-      for (int i = 0; i < intfTyps.length; i++) {
-        Class intfTyp = (Class) intfTyps[i];
+      for (Type intfTyp1 : intfTyps) {
+        Class intfTyp = (Class) intfTyp1;
         if (intfTyp.equals(NotificationEmitter.class)) {
           return true;
         }
       }
-      Class supreClassTyp = (Class) cls.getGenericSuperclass();
-      if (supreClassTyp != null && supreClassTyp.equals(NotificationBroadcasterSupport.class)) {
+      Class superClassType = (Class) cls.getGenericSuperclass();
+      if (superClassType != null && superClassType.equals(NotificationBroadcasterSupport.class)) {
         return true;
       }
-    } catch (InstanceNotFoundException e) {
-      throw new ManagementException(e);
-    } catch (ClassNotFoundException e) {
+    } catch (InstanceNotFoundException | ClassNotFoundException e) {
       throw new ManagementException(e);
     }
     return false;
@@ -174,13 +160,8 @@ public class MBeanJMXAdapter implements ManagementConstants {
 
       mbeanServer.registerMBean(object, objectName);
 
-    } catch (InstanceAlreadyExistsException e) {
-      throw new ManagementException(e);
-    } catch (MBeanRegistrationException e) {
-      throw new ManagementException(e);
-    } catch (NotCompliantMBeanException e) {
-      throw new ManagementException(e);
-    } catch (NullPointerException e) {
+    } catch (InstanceAlreadyExistsException | NullPointerException | NotCompliantMBeanException
+        | MBeanRegistrationException e) {
       throw new ManagementException(e);
     }
 
@@ -205,11 +186,7 @@ public class MBeanJMXAdapter implements ManagementConstants {
       if (localGemFireMBean.get(objectName) != null) {
         localGemFireMBean.remove(objectName);
       }
-    } catch (NullPointerException e) {
-      throw new ManagementException(e);
-    } catch (InstanceNotFoundException e) {
-      throw new ManagementException(e);
-    } catch (MBeanRegistrationException e) {
+    } catch (NullPointerException | MBeanRegistrationException | InstanceNotFoundException e) {
       throw new ManagementException(e);
     }
 
@@ -253,9 +230,7 @@ public class MBeanJMXAdapter implements ManagementConstants {
       for (ObjectName objectName : gemFireObjects) {
         unregisterMBean(objectName);
       }
-    } catch (MalformedObjectNameException e) {
-      throw new ManagementException(e);
-    } catch (NullPointerException e) {
+    } catch (MalformedObjectNameException | NullPointerException e) {
       throw new ManagementException(e);
     }
 
@@ -324,34 +299,13 @@ public class MBeanJMXAdapter implements ManagementConstants {
   }
 
   private static boolean containsSpecialChar(String value) {
-    if (value.contains(":")) {
-      return true;
-    }
-    if (value.contains("@")) {
-      return true;
-    }
-    if (value.contains("-")) {
-      return true;
-    }
-    if (value.contains("#")) {
-      return true;
-    }
-    if (value.contains("+")) {
-      return true;
-    }
-    if (value.contains("?")) {
-      return true;
-    }
-    return false;
+    return value.contains(":") || value.contains("@") || value.contains("-") || value.contains("#")
+        || value.contains("+") || value.contains("?");
   }
 
   private static boolean isQuoted(String value) {
     final int len = value.length();
-    if (len < 2 || value.charAt(0) != '"' || value.charAt(len - 1) != '"') {
-      return false;
-    } else {
-      return true;
-    }
+    return len >= 2 && value.charAt(0) == '"' && value.charAt(len - 1) == '"';
   }
 
   /**
@@ -428,7 +382,7 @@ public class MBeanJMXAdapter implements ManagementConstants {
   }
 
   public AsyncEventQueueMXBean getAsyncEventQueueMXBean(String queueId) {
-    ObjectName objName = getAsycnEventQueueMBeanName(distMember, queueId);
+    ObjectName objName = getAsyncEventQueueMBeanName(distMember, queueId);
     return (AsyncEventQueueMXBean) localGemFireMBean.get(objName);
   }
 
@@ -441,104 +395,102 @@ public class MBeanJMXAdapter implements ManagementConstants {
   public static ObjectName getObjectName(String name) {
     try {
       return ObjectName.getInstance(name);
-    } catch (MalformedObjectNameException e) {
-      throw new ManagementException(e);
-    } catch (NullPointerException e) {
+    } catch (MalformedObjectNameException | NullPointerException e) {
       throw new ManagementException(e);
     }
   }
 
   public static ObjectName getMemberMBeanName(DistributedMember member) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__MEMBER_MXBEAN,
-        new Object[] {getMemberNameOrId(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__MEMBER_MXBEAN, getMemberNameOrId(member))));
   }
 
   public static ObjectName getMemberMBeanName(String member) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__MEMBER_MXBEAN,
-        new Object[] {makeCompliantName(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__MEMBER_MXBEAN, makeCompliantName(member))));
   }
 
   public static ObjectName getRegionMBeanName(DistributedMember member, String regionPath) {
 
     return getObjectName((MessageFormat.format(OBJECTNAME__REGION_MXBEAN,
-        new Object[] {makeCompliantRegionPath(regionPath), getMemberNameOrId(member)})));
+        makeCompliantRegionPath(regionPath), getMemberNameOrId(member))));
   }
 
   public static ObjectName getRegionMBeanName(String member, String regionPath) {
     return getObjectName((MessageFormat.format(OBJECTNAME__REGION_MXBEAN,
-        new Object[] {makeCompliantRegionPath(regionPath), makeCompliantName(member)})));
+        makeCompliantRegionPath(regionPath), makeCompliantName(member))));
   }
 
   public static ObjectName getRegionMBeanName(ObjectName memberMBeanName, String regionPath) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__REGION_MXBEAN,
-        new Object[] {makeCompliantRegionPath(regionPath),
-            memberMBeanName.getKeyProperty(ManagementConstants.OBJECTNAME_MEMBER_APPENDER)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__REGION_MXBEAN, makeCompliantRegionPath(regionPath),
+            memberMBeanName.getKeyProperty(ManagementConstants.OBJECTNAME_MEMBER_APPENDER))));
   }
 
   public static ObjectName getDiskStoreMBeanName(DistributedMember member, String diskName) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__DISKSTORE_MXBEAN,
-        new Object[] {diskName, getMemberNameOrId(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__DISKSTORE_MXBEAN, diskName, getMemberNameOrId(member))));
   }
 
   public static ObjectName getDiskStoreMBeanName(String member, String diskName) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__DISKSTORE_MXBEAN,
-        new Object[] {diskName, makeCompliantName(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__DISKSTORE_MXBEAN, diskName, makeCompliantName(member))));
   }
 
   public static ObjectName getClientServiceMBeanName(int serverPort, DistributedMember member) {
     return getObjectName((MessageFormat.format(OBJECTNAME__CLIENTSERVICE_MXBEAN,
-        new Object[] {String.valueOf(serverPort), getMemberNameOrId(member)})));
+        String.valueOf(serverPort), getMemberNameOrId(member))));
   }
 
   public static ObjectName getClientServiceMBeanName(int serverPort, String member) {
     return getObjectName((MessageFormat.format(OBJECTNAME__CLIENTSERVICE_MXBEAN,
-        new Object[] {String.valueOf(serverPort), makeCompliantName(member)})));
+        String.valueOf(serverPort), makeCompliantName(member))));
   }
 
   public static ObjectName getLockServiceMBeanName(DistributedMember member,
       String lockServiceName) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__LOCKSERVICE_MXBEAN,
-        new Object[] {lockServiceName, getMemberNameOrId(member)})));
+    return getObjectName((MessageFormat.format(OBJECTNAME__LOCKSERVICE_MXBEAN, lockServiceName,
+        getMemberNameOrId(member))));
   }
 
   public static ObjectName getLockServiceMBeanName(String member, String lockServiceName) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__LOCKSERVICE_MXBEAN,
-        new Object[] {lockServiceName, makeCompliantName(member)})));
+    return getObjectName((MessageFormat.format(OBJECTNAME__LOCKSERVICE_MXBEAN, lockServiceName,
+        makeCompliantName(member))));
   }
 
   public static ObjectName getGatewayReceiverMBeanName(DistributedMember member) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__GATEWAYRECEIVER_MXBEAN,
-        new Object[] {getMemberNameOrId(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__GATEWAYRECEIVER_MXBEAN, getMemberNameOrId(member))));
   }
 
   public static ObjectName getGatewayReceiverMBeanName(String member) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__GATEWAYRECEIVER_MXBEAN,
-        new Object[] {makeCompliantName(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__GATEWAYRECEIVER_MXBEAN, makeCompliantName(member))));
   }
 
   public static ObjectName getGatewaySenderMBeanName(DistributedMember member, String id) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__GATEWAYSENDER_MXBEAN,
-        new Object[] {id, getMemberNameOrId(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__GATEWAYSENDER_MXBEAN, id, getMemberNameOrId(member))));
   }
 
   public static ObjectName getGatewaySenderMBeanName(String member, String id) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__GATEWAYSENDER_MXBEAN,
-        new Object[] {id, makeCompliantName(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__GATEWAYSENDER_MXBEAN, id, makeCompliantName(member))));
   }
 
-  public static ObjectName getAsycnEventQueueMBeanName(DistributedMember member, String queueId) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__ASYNCEVENTQUEUE_MXBEAN,
-        new Object[] {queueId, getMemberNameOrId(member)})));
+  public static ObjectName getAsyncEventQueueMBeanName(DistributedMember member, String queueId) {
+    return getObjectName((MessageFormat.format(OBJECTNAME__ASYNCEVENTQUEUE_MXBEAN, queueId,
+        getMemberNameOrId(member))));
   }
 
-  public static ObjectName getAsycnEventQueueMBeanName(String member, String queueId) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__ASYNCEVENTQUEUE_MXBEAN,
-        new Object[] {queueId, makeCompliantName(member)})));
+  public static ObjectName getAsyncEventQueueMBeanName(String member, String queueId) {
+    return getObjectName((MessageFormat.format(OBJECTNAME__ASYNCEVENTQUEUE_MXBEAN, queueId,
+        makeCompliantName(member))));
   }
 
   public static ObjectName getDistributedRegionMbeanName(String regionPath) {
     return getObjectName((MessageFormat.format(OBJECTNAME__DISTRIBUTEDREGION_MXBEAN,
-        new Object[] {makeCompliantRegionPath(regionPath)})));
+        makeCompliantRegionPath(regionPath))));
   }
 
   /**
@@ -548,13 +500,12 @@ public class MBeanJMXAdapter implements ManagementConstants {
    * @return ObjectName MBean name
    */
   public static ObjectName getDistributedRegionMbeanNameInternal(String regionPath) {
-    return getObjectName(
-        (MessageFormat.format(OBJECTNAME__DISTRIBUTEDREGION_MXBEAN, new Object[] {regionPath})));
+    return getObjectName((MessageFormat.format(OBJECTNAME__DISTRIBUTEDREGION_MXBEAN, regionPath)));
   }
 
   public static ObjectName getDistributedLockServiceName(String lockService) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__DISTRIBUTEDLOCKSERVICE_MXBEAN,
-        new Object[] {lockService})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__DISTRIBUTEDLOCKSERVICE_MXBEAN, lockService)));
   }
 
   public static ObjectName getDistributedSystemName() {
@@ -564,23 +515,23 @@ public class MBeanJMXAdapter implements ManagementConstants {
   public static ObjectName getManagerName() {
     String member =
         getMemberNameOrId(InternalDistributedSystem.getConnectedInstance().getDistributedMember());
-    return getObjectName((MessageFormat.format(OBJECTNAME__MANAGER_MXBEAN, new Object[] {member})));
+    return getObjectName((MessageFormat.format(OBJECTNAME__MANAGER_MXBEAN, member)));
   }
 
   public static ObjectName getLocatorMBeanName(DistributedMember member) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__LOCATOR_MXBEAN,
-        new Object[] {getMemberNameOrId(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__LOCATOR_MXBEAN, getMemberNameOrId(member))));
   }
 
   public static ObjectName getLocatorMBeanName(String member) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__LOCATOR_MXBEAN,
-        new Object[] {makeCompliantName(member)})));
+    return getObjectName(
+        (MessageFormat.format(OBJECTNAME__LOCATOR_MXBEAN, makeCompliantName(member))));
   }
 
   public static ObjectName getCacheServiceMBeanName(DistributedMember member,
       String cacheServiceId) {
-    return getObjectName((MessageFormat.format(OBJECTNAME__CACHESERVICE_MXBEAN,
-        new Object[] {cacheServiceId, getMemberNameOrId(member)})));
+    return getObjectName((MessageFormat.format(OBJECTNAME__CACHESERVICE_MXBEAN, cacheServiceId,
+        getMemberNameOrId(member))));
   }
 
   public Map<ObjectName, Object> getLocalGemFireMBean() {
@@ -592,12 +543,12 @@ public class MBeanJMXAdapter implements ManagementConstants {
     InternalDistributedMember iMember = (InternalDistributedMember) member;
     final StringBuilder sb = new StringBuilder();
     sb.append(iMember.getInetAddress().getHostAddress());
-    sb.append("<v" + iMember.getVmViewId() + ">"); // View ID will be 0 for
-    // Loner, but in that case no
-    // federation as well
+    // View ID will be 0 for Loner, but in that case no federation as well
+    sb.append("<v").append(iMember.getVmViewId()).append(">");
     sb.append(iMember.getPort());
-    return makeCompliantName(sb.toString().toLowerCase());// Lower case to
-    // handle IPv6
+    // Lower case to handle IPv6
+    return makeCompliantName(sb.toString().toLowerCase());
+
   }
 
   public static boolean isAttributeAvailable(String attributeName, String objectName) {
@@ -605,24 +556,12 @@ public class MBeanJMXAdapter implements ManagementConstants {
     try {
       ObjectName objName = new ObjectName(objectName);
       mbeanServer.getAttribute(objName, attributeName);
-    } catch (MalformedObjectNameException e) {
-      return false;
-    } catch (NullPointerException e) {
-      return false;
-    } catch (AttributeNotFoundException e) {
-      return false;
-    } catch (InstanceNotFoundException e) {
-      return false;
-    } catch (MBeanException e) {
-      return false;
-    } catch (ReflectionException e) {
+    } catch (MalformedObjectNameException | ReflectionException | MBeanException
+        | InstanceNotFoundException | AttributeNotFoundException | NullPointerException e) {
       return false;
     }
 
     return true;
 
   }
-
-  public static int VALUE_NOT_AVAILABLE = -1;
-
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/ManagementAgent.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/ManagementAgent.java b/geode-core/src/main/java/org/apache/geode/management/internal/ManagementAgent.java
index 11590cf..39ad703 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/ManagementAgent.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/ManagementAgent.java
@@ -14,32 +14,6 @@
  */
 package org.apache.geode.management.internal;
 
-import org.apache.commons.lang.StringUtils;
-import org.apache.geode.GemFireConfigException;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.distributed.internal.DistributionConfig;
-import org.apache.geode.distributed.internal.DistributionManager;
-import org.apache.geode.internal.GemFireVersion;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.internal.net.SSLConfigurationFactory;
-import org.apache.geode.internal.net.SocketCreator;
-import org.apache.geode.internal.net.SocketCreatorFactory;
-import org.apache.geode.internal.security.SecurableCommunicationChannel;
-import org.apache.geode.internal.security.SecurityService;
-import org.apache.geode.internal.security.shiro.JMXShiroAuthenticator;
-import org.apache.geode.internal.tcp.TCPConduit;
-import org.apache.geode.management.ManagementException;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.ManagerMXBean;
-import org.apache.geode.management.internal.security.AccessControlMBean;
-import org.apache.geode.management.internal.security.MBeanServerWrapper;
-import org.apache.geode.management.internal.security.ResourceConstants;
-import org.apache.geode.management.internal.unsafe.ReadOpFileAccessController;
-import org.apache.logging.log4j.Logger;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-
 import java.io.IOException;
 import java.io.Serializable;
 import java.lang.management.ManagementFactory;
@@ -55,6 +29,7 @@ import java.rmi.server.RMIServerSocketFactory;
 import java.rmi.server.UnicastRemoteObject;
 import java.util.HashMap;
 import java.util.Set;
+
 import javax.management.InstanceAlreadyExistsException;
 import javax.management.MBeanRegistrationException;
 import javax.management.MBeanServer;
@@ -68,6 +43,33 @@ import javax.management.remote.rmi.RMIJRMPServerImpl;
 import javax.management.remote.rmi.RMIServerImpl;
 import javax.rmi.ssl.SslRMIClientSocketFactory;
 
+import org.apache.commons.lang.StringUtils;
+import org.apache.logging.log4j.Logger;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+
+import org.apache.geode.GemFireConfigException;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.distributed.internal.DistributionConfig;
+import org.apache.geode.distributed.internal.DistributionManager;
+import org.apache.geode.internal.GemFireVersion;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.internal.net.SSLConfigurationFactory;
+import org.apache.geode.internal.net.SocketCreator;
+import org.apache.geode.internal.net.SocketCreatorFactory;
+import org.apache.geode.internal.security.SecurableCommunicationChannel;
+import org.apache.geode.internal.security.SecurityService;
+import org.apache.geode.internal.security.shiro.JMXShiroAuthenticator;
+import org.apache.geode.internal.tcp.TCPConduit;
+import org.apache.geode.management.ManagementException;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.ManagerMXBean;
+import org.apache.geode.management.internal.security.AccessControlMBean;
+import org.apache.geode.management.internal.security.MBeanServerWrapper;
+import org.apache.geode.management.internal.security.ResourceConstants;
+import org.apache.geode.management.internal.unsafe.ReadOpFileAccessController;
+
 /**
  * Agent implementation that controls the JMX server end points for JMX clients to connect, such as
  * an RMI server.
@@ -390,7 +392,7 @@ public class ManagementAgent {
       logger.debug("Starting jmx manager agent on port {}{}", port,
           (bindAddr != null ? (" bound to " + bindAddr) : "") + (ssl ? " using SSL" : ""));
     }
-    RMIClientSocketFactory rmiClientSocketFactory = ssl ? new SslRMIClientSocketFactory() : null;// RMISocketFactory.getDefaultSocketFactory();
+    RMIClientSocketFactory rmiClientSocketFactory = ssl ? new SslRMIClientSocketFactory() : null;
     RMIServerSocketFactory rmiServerSocketFactory =
         new GemFireRMIServerSocketFactory(socketCreator, bindAddr);
 
@@ -410,7 +412,7 @@ public class ManagementAgent {
     MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
 
     // Environment map. why is this declared as HashMap?
-    final HashMap<String, Object> env = new HashMap<String, Object>();
+    final HashMap<String, Object> env = new HashMap<>();
 
     // Manually creates and binds a JMX RMI Connector Server stub with the
     // registry created above: the port we pass here is the port that can
@@ -459,8 +461,7 @@ public class ManagementAgent {
             try {
               registry.bind("jmxrmi", stub);
             } catch (AlreadyBoundException x) {
-              final IOException io = new IOException(x.getMessage());
-              io.initCause(x);
+              final IOException io = new IOException(x.getMessage(), x);
               throw io;
             }
             super.start();
@@ -487,12 +488,9 @@ public class ManagementAgent {
 
       String accessFile = this.config.getJmxManagerAccessFile();
       if (accessFile != null && accessFile.length() > 0) {
-        // Lets not use default connector based authorization
-        // env.put("jmx.remote.x.access.file", accessFile);
         // Rewire the mbs hierarchy to set accessController
         ReadOpFileAccessController controller = new ReadOpFileAccessController(accessFile);
         controller.setMBeanServer(mbs);
-        mbs = controller;
       }
     }
 
@@ -529,7 +527,7 @@ public class ManagementAgent {
 
     private static final long serialVersionUID = -7604285019188827617L;
 
-    private/* final hack to prevent serialization */ transient SocketCreator sc;
+    private transient SocketCreator sc;
 
     public GemFireRMIClientSocketFactory(SocketCreator sc) {
       this.sc = sc;
@@ -537,7 +535,7 @@ public class ManagementAgent {
 
     @Override
     public Socket createSocket(String host, int port) throws IOException {
-      return this.sc.connectForClient(host, port, 0/* no timeout */);
+      return this.sc.connectForClient(host, port, 0);
     }
   }
 
@@ -545,7 +543,7 @@ public class ManagementAgent {
       implements RMIServerSocketFactory, Serializable {
 
     private static final long serialVersionUID = -811909050641332716L;
-    private/* final hack to prevent serialization */ transient SocketCreator sc;
+    private transient SocketCreator sc;
     private final InetAddress bindAddr;
 
     public GemFireRMIServerSocketFactory(SocketCreator sc, InetAddress bindAddr) {

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java b/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
index c770f89..9a92eaa 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
@@ -320,8 +320,7 @@ public class SystemManagementService extends BaseManagementService {
     return jmxAdapter.getLocalRegionMXBean(regionPath);
   }
 
-  public <T> T getMBeanProxy(ObjectName objectName, Class<T> interfaceClass) { // TODO: this is too
-                                                                               // generic
+  public <T> T getMBeanProxy(ObjectName objectName, Class<T> interfaceClass) {
     if (!isStartedAndOpen()) {
       return null;
     }
@@ -556,7 +555,7 @@ public class SystemManagementService extends BaseManagementService {
 
   @Override
   public ObjectName getAsyncEventQueueMBeanName(DistributedMember member, String queueId) {
-    return MBeanJMXAdapter.getAsycnEventQueueMBeanName(member, queueId);
+    return MBeanJMXAdapter.getAsyncEventQueueMBeanName(member, queueId);
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/beans/MBeanAggregator.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/MBeanAggregator.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/MBeanAggregator.java
index d0a6e35..98d1810 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/MBeanAggregator.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/MBeanAggregator.java
@@ -42,7 +42,7 @@ import org.apache.geode.management.internal.SystemManagementService;
  */
 public class MBeanAggregator implements ProxyListener {
 
-  private static final List<Class> distributedMBeanList = new ArrayList<Class>();
+  private static final List<Class> distributedMBeanList = new ArrayList<>();
 
 
   /**
@@ -405,10 +405,7 @@ public class MBeanAggregator implements ProxyListener {
   }
 
   public void quorumLost(Set<InternalDistributedMember> failures,
-      List<InternalDistributedMember> remaining) {
-    // [bruce] does this need to propagate through this bridge object?
-    // distributedSystemBridge.quorumLost(failures, remaining);
-  }
+      List<InternalDistributedMember> remaining) {}
 
   @Override
   public void memberSuspect(InternalDistributedMember id, InternalDistributedMember whoSuspected,

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/beans/ManagementAdapter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/ManagementAdapter.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/ManagementAdapter.java
index 8ea84f5..e35e97b 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/ManagementAdapter.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/ManagementAdapter.java
@@ -14,7 +14,24 @@
  */
 package org.apache.geode.management.internal.beans;
 
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.Notification;
+import javax.management.NotificationBroadcasterSupport;
+import javax.management.ObjectInstance;
+import javax.management.ObjectName;
+
 import org.apache.commons.lang.StringUtils;
+import org.apache.logging.log4j.Logger;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.DiskStore;
 import org.apache.geode.cache.Region;
@@ -58,21 +75,6 @@ import org.apache.geode.management.membership.ClientMembershipEvent;
 import org.apache.geode.management.membership.ClientMembershipListener;
 import org.apache.geode.management.membership.ClientMembershipListenerAdapter;
 import org.apache.geode.pdx.internal.PeerTypeRegistration;
-import org.apache.logging.log4j.Logger;
-
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.Notification;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.ObjectInstance;
-import javax.management.ObjectName;
 
 /**
  * Acts as an intermediate between MBean layer and Federation Layer. Handles all Call backs from
@@ -151,8 +153,7 @@ public class ManagementAdapter {
 
       // Type casting to MemberMXBean to expose only those methods described in
       // the interface;
-      ObjectName changedMBeanName =
-          service.registerInternalMBean((MemberMXBean) memberBean, memberMBeanName);
+      ObjectName changedMBeanName = service.registerInternalMBean(memberBean, memberMBeanName);
       service.federate(changedMBeanName, MemberMXBean.class, true);
 
       this.serviceInitialised = true;
@@ -530,7 +531,7 @@ public class ManagementAdapter {
     }
     AsyncEventQueueMBeanBridge bridge = new AsyncEventQueueMBeanBridge(queue);
     AsyncEventQueueMXBean queueMBean = new AsyncEventQueueMBean(bridge);
-    ObjectName senderObjectName = MBeanJMXAdapter.getAsycnEventQueueMBeanName(
+    ObjectName senderObjectName = MBeanJMXAdapter.getAsyncEventQueueMBeanName(
         internalCache.getDistributedSystem().getDistributedMember(), queue.getId());
 
     ObjectName changedMBeanName = service.registerInternalMBean(queueMBean, senderObjectName);
@@ -553,7 +554,7 @@ public class ManagementAdapter {
       return;
     }
 
-    ObjectName asycnEventQueueMBeanName = MBeanJMXAdapter.getAsycnEventQueueMBeanName(
+    ObjectName asycnEventQueueMBeanName = MBeanJMXAdapter.getAsyncEventQueueMBeanName(
         internalCache.getDistributedSystem().getDistributedMember(), queue.getId());
     AsyncEventQueueMBean bean;
     try {
@@ -612,7 +613,7 @@ public class ManagementAdapter {
     userData.put(JMXNotificationUserData.THREAD, source);
 
     InternalDistributedMember sender = details.getSender();
-    String nameOrId = memberSource; // TODO: what if sender is null?
+    String nameOrId = memberSource;
     if (sender != null) {
       nameOrId = sender.getName();
       nameOrId = StringUtils.isNotBlank(nameOrId) ? nameOrId : sender.getId();
@@ -642,7 +643,7 @@ public class ManagementAdapter {
         cacheServer.getPort(), internalCache.getDistributedSystem().getDistributedMember());
 
     ObjectName changedMBeanName =
-        service.registerInternalMBean((CacheServerMXBean) cacheServerMBean, cacheServerMBeanName);
+        service.registerInternalMBean(cacheServerMBean, cacheServerMBeanName);
 
     ClientMembershipListener managementClientListener = new CacheServerMembershipListenerAdapter(
         cacheServerMBean, memberLevelNotifEmitter, changedMBeanName);
@@ -895,8 +896,7 @@ public class ManagementAdapter {
     LocatorMBeanBridge bridge = new LocatorMBeanBridge(locator);
     LocatorMBean locatorMBean = new LocatorMBean(bridge);
 
-    ObjectName changedMBeanName =
-        service.registerInternalMBean((LocatorMXBean) locatorMBean, locatorMBeanName);
+    ObjectName changedMBeanName = service.registerInternalMBean(locatorMBean, locatorMBeanName);
 
     service.federate(changedMBeanName, LocatorMXBean.class, true);
 

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/VMStatsMonitor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/VMStatsMonitor.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/VMStatsMonitor.java
index dd24942..a62f926 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/VMStatsMonitor.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/VMStatsMonitor.java
@@ -17,7 +17,6 @@ package org.apache.geode.management.internal.beans.stats;
 import java.lang.management.ManagementFactory;
 
 import org.apache.geode.StatisticDescriptor;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.internal.statistics.StatisticId;
 import org.apache.geode.internal.statistics.StatisticNotFoundException;
 import org.apache.geode.internal.statistics.StatisticsNotification;
@@ -30,9 +29,9 @@ import org.apache.geode.management.internal.MBeanJMXAdapter;
  */
 public class VMStatsMonitor extends MBeanStatsMonitor {
 
-  private volatile float cpuUsage = 0;
-
+  private static final int VALUE_NOT_AVAILABLE = -1;
 
+  private volatile float cpuUsage = 0;
 
   private static String processCPUTimeAttr = "ProcessCpuTime";
 
@@ -47,7 +46,7 @@ public class VMStatsMonitor extends MBeanStatsMonitor {
     processCPUTimeAvailable = MBeanJMXAdapter.isAttributeAvailable(processCPUTimeAttr,
         ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME);
     if (!processCPUTimeAvailable) {
-      cpuUsage = MBeanJMXAdapter.VALUE_NOT_AVAILABLE;
+      cpuUsage = VALUE_NOT_AVAILABLE;
     }
 
   }
@@ -89,7 +88,7 @@ public class VMStatsMonitor extends MBeanStatsMonitor {
       // Some JVM like IBM is not handled by Stats layer properly. Ignoring the attribute for such
       // cases
       if (processCpuTime == null) {
-        cpuUsage = MBeanJMXAdapter.VALUE_NOT_AVAILABLE;
+        cpuUsage = VALUE_NOT_AVAILABLE;
         return;
       }
 
@@ -106,9 +105,8 @@ public class VMStatsMonitor extends MBeanStatsMonitor {
       }
       long systemTime = System.currentTimeMillis();
 
-      long denom = (systemTime - lastSystemTime) * 10000; // 10000 = (Nano
-      // conversion factor /
-      // 100 for percentage)
+      // 10000 = (Nano conversion factor / 100 for percentage)
+      long denom = (systemTime - lastSystemTime) * 10000;
 
       float processCpuUsage = (float) (cpuTime - lastProcessCpuTime) / denom;
 

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/CliUtil.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/CliUtil.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/CliUtil.java
index 8e9b54e..67f1b2b 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/CliUtil.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/CliUtil.java
@@ -75,7 +75,7 @@ public class CliUtil {
   public static final FileFilter JAR_FILE_FILTER = new CustomFileFilter(".jar");
 
   public static String cliDependenciesExist(boolean includeGfshDependencies) {
-    String jarProductName = null;
+    String jarProductName;
 
     // Parser & CliCommand from Spring Shell
     jarProductName =
@@ -127,23 +127,22 @@ public class CliUtil {
   }
 
   public static byte[][] filesToBytes(String[] fileNames) throws IOException {
-    List<byte[]> filesDataList = new ArrayList<byte[]>();
+    List<byte[]> filesDataList = new ArrayList<>();
 
-    for (int i = 0; i < fileNames.length; i++) {
-      File file = new File(fileNames[i]);
+    for (String fileName : fileNames) {
+      File file = new File(fileName);
 
       if (!file.exists()) {
         throw new FileNotFoundException("Could not find " + file.getCanonicalPath());
       }
 
       if (file.isDirectory()) {
-        // TODO: (1) No recursive search yet. (2) Do we need to check/limit size of the files too?
         File[] childrenFiles = file.listFiles(JAR_FILE_FILTER);
-        for (int j = 0; j < childrenFiles.length; j++) {
+        for (File childrenFile : childrenFiles) {
           // 1. add name of the file as bytes at even index
-          filesDataList.add(childrenFiles[j].getName().getBytes());
+          filesDataList.add(childrenFile.getName().getBytes());
           // 2. add file contents as bytes at odd index
-          filesDataList.add(toByteArray(new FileInputStream(childrenFiles[j])));
+          filesDataList.add(toByteArray(new FileInputStream(childrenFile)));
         }
       } else {
         filesDataList.add(file.getName().getBytes());
@@ -211,31 +210,21 @@ public class CliUtil {
     }
   }
 
-  public static boolean isValidFileName(String filePath, String extension) {
-    boolean isValid = true;
-    return isValid;
-  }
-
   private static InternalCache getInternalCache() {
     return (InternalCache) CacheFactory.getAnyInstance();
   }
 
   public static Set<String> getAllRegionNames() {
     InternalCache cache = getInternalCache();
-    Set<String> regionNames = new HashSet<String>();
+    Set<String> regionNames = new HashSet<>();
     Set<Region<?, ?>> rootRegions = cache.rootRegions();
 
-    Iterator<Region<?, ?>> rootRegionIters = rootRegions.iterator();
-
-    while (rootRegionIters.hasNext()) {
-      Region<?, ?> rootRegion = rootRegionIters.next();
+    for (Region<?, ?> rootRegion : rootRegions) {
       regionNames.add(rootRegion.getFullPath().substring(1));
 
       Set<Region<?, ?>> subRegions = rootRegion.subregions(true);
-      Iterator<Region<?, ?>> subRegionIters = subRegions.iterator();
 
-      while (subRegionIters.hasNext()) {
-        Region<?, ?> subRegion = subRegionIters.next();
+      for (Region<?, ?> subRegion : subRegions) {
         regionNames.add(subRegion.getFullPath().substring(1));
       }
     }
@@ -245,10 +234,8 @@ public class CliUtil {
   public static String convertStringSetToString(Set<String> stringSet, char delimiter) {
     StringBuilder sb = new StringBuilder();
     if (stringSet != null) {
-      Iterator<String> iters = stringSet.iterator();
 
-      while (iters.hasNext()) {
-        String stringValue = iters.next();
+      for (String stringValue : stringSet) {
         sb.append(stringValue);
         sb.append(delimiter);
       }
@@ -259,10 +246,8 @@ public class CliUtil {
   public static String convertStringListToString(List<String> stringList, char delimiter) {
     StringBuilder sb = new StringBuilder();
     if (stringList != null) {
-      Iterator<String> iters = stringList.iterator();
 
-      while (iters.hasNext()) {
-        String stringValue = iters.next();
+      for (String stringValue : stringList) {
         sb.append(stringValue);
         sb.append(delimiter);
       }
@@ -311,7 +296,7 @@ public class CliUtil {
       return membersToConsider;
     }
 
-    Set<DistributedMember> matchingMembers = new HashSet<DistributedMember>();
+    Set<DistributedMember> matchingMembers = new HashSet<>();
     // it will either go into this loop or the following loop, not both.
     for (String memberNameOrId : members) {
       for (DistributedMember member : membersToConsider) {
@@ -384,7 +369,7 @@ public class CliUtil {
   }
 
   public static <K> K newInstance(Class<K> klass, String neededFor) {
-    K instance = null;
+    K instance;
     try {
       instance = klass.newInstance();
     } catch (InstantiationException e) {
@@ -449,7 +434,6 @@ public class CliUtil {
       System.arraycopy(buffer, 0, newResult, result.length, bytesRead);
       result = newResult;
     }
-    // System.out.println(new String(result));
     decompresser.end();
 
     return new DeflaterInflaterData(result.length, result);
@@ -480,43 +464,6 @@ public class CliUtil {
     }
   }
 
-  public static void main(String[] args) {
-    try {
-      byte[][] filesToBytes =
-          filesToBytes(new String[] {"/export/abhishek1/work/aspenmm/GFTryouts/test.json"});
-
-      System.out.println(filesToBytes[1].length);
-
-      DeflaterInflaterData compressBytes = compressBytes(filesToBytes[1]);
-      System.out.println(compressBytes);
-
-      DeflaterInflaterData uncompressBytes =
-          uncompressBytes(compressBytes.data, compressBytes.dataLength);
-      System.out.println(uncompressBytes);
-
-      System.out.println(new String(uncompressBytes.getData()));
-    } catch (FileNotFoundException e) {
-      e.printStackTrace();
-    } catch (IOException e) {
-      e.printStackTrace();
-    } catch (DataFormatException e) {
-      e.printStackTrace();
-    }
-  }
-
-  public static void main1(String[] args) {
-    try {
-      byte[][] fileToBytes = filesToBytes(new String[] {"../dumped/source/lib"});
-
-      bytesToFiles(fileToBytes, "../dumped/dest/lib/", true);
-
-    } catch (FileNotFoundException e) {
-      e.printStackTrace();
-    } catch (IOException e) {
-      e.printStackTrace();
-    }
-  }
-
   public static boolean contains(Object[] array, Object object) {
     boolean contains = false;
 
@@ -560,7 +507,7 @@ public class CliUtil {
    */
   public static Set<DistributedMember> getDistributedMembersByGroup(InternalCache cache,
       String[] groups) {
-    Set<DistributedMember> groupMembers = new HashSet<DistributedMember>();
+    Set<DistributedMember> groupMembers = new HashSet<>();
     for (String group : groups) {
       groupMembers.addAll(
           cache.getInternalDistributedSystem().getDistributionManager().getGroupMembers(group));
@@ -580,7 +527,7 @@ public class CliUtil {
    */
   public static ResultCollector<?, ?> executeFunction(final Function function, Object args,
       final Set<DistributedMember> targetMembers) {
-    Execution execution = null;
+    Execution execution;
 
     if (args != null) {
       execution = FunctionService.onMembers(targetMembers).setArguments(args);
@@ -603,7 +550,7 @@ public class CliUtil {
    */
   public static ResultCollector<?, ?> executeFunction(final Function function, Object args,
       final DistributedMember targetMember) {
-    Execution execution = null;
+    Execution execution;
 
     if (args != null) {
       execution = FunctionService.onMember(targetMember).setArguments(args);
@@ -635,9 +582,9 @@ public class CliUtil {
     ManagementService managementService = ManagementService.getExistingManagementService(cache);
     DistributedSystemMXBean distributedSystemMXBean =
         managementService.getDistributedSystemMXBean();
-    Set<DistributedMember> matchedMembers = new HashSet<DistributedMember>();
+    Set<DistributedMember> matchedMembers = new HashSet<>();
 
-    Set<DistributedMember> allClusterMembers = new HashSet<DistributedMember>();
+    Set<DistributedMember> allClusterMembers = new HashSet<>();
     allClusterMembers.addAll(cache.getMembers());
     allClusterMembers.add(cache.getDistributedSystem().getDistributedMember());
 
@@ -647,8 +594,7 @@ public class CliUtil {
             region) != null) {
           matchedMembers.add(member);
         }
-      } catch (Exception e) {
-        // ignore for now
+      } catch (Exception ignored) {
       }
     }
     return matchedMembers;
@@ -729,7 +675,7 @@ public class CliUtil {
     }
 
     File file = null;
-    FileWriter fw = null;
+    FileWriter fw;
     try {
       file = File.createTempFile("gfsh_output", "less");
       fw = new FileWriter(file);
@@ -741,9 +687,7 @@ public class CliUtil {
               "LESSOPEN=\"|color %s\" less -SR " + file.getName() + " < /dev/tty > /dev/tty "},
           null, workingDir);
       p.waitFor();
-    } catch (IOException e) {
-      Gfsh.printlnErr(e.getMessage());
-    } catch (InterruptedException e) {
+    } catch (IOException | InterruptedException e) {
       Gfsh.printlnErr(e.getMessage());
     } finally {
       if (file != null)
@@ -764,7 +708,7 @@ public class CliUtil {
   public static Set<DistributedMember> getMembersForeRegionViaFunction(InternalCache cache,
       String regionPath, boolean returnAll) {
     try {
-      Set<DistributedMember> regionMembers = new HashSet<DistributedMember>();
+      Set<DistributedMember> regionMembers = new HashSet<>();
       MembersForRegionFunction membersForRegionFunction = new MembersForRegionFunction();
       FunctionService.registerFunction(membersForRegionFunction);
       Set<DistributedMember> targetMembers = CliUtil.getAllMembers(cache);
@@ -786,9 +730,7 @@ public class CliUtil {
           }
           if (object != null) {
             Map<String, String> memberDetails = (Map<String, String>) object;
-            Iterator<Entry<String, String>> it = memberDetails.entrySet().iterator();
-            while (it.hasNext()) {
-              Entry<String, String> entry = it.next();
+            for (Entry<String, String> entry : memberDetails.entrySet()) {
               Set<DistributedMember> dsMems = CliUtil.getAllMembers(cache);
               for (DistributedMember mem : dsMems) {
                 if (mem.getId().equals(entry.getKey())) {
@@ -802,7 +744,6 @@ public class CliUtil {
           }
         } catch (Exception ex) {
           LogWrapper.getInstance().warning("getMembersForeRegionViaFunction exception " + ex);
-          continue;
         }
       }
       return regionMembers;

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/CommandResponseBuilder.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/CommandResponseBuilder.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/CommandResponseBuilder.java
index 3f8f20d..790e54b 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/CommandResponseBuilder.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/CommandResponseBuilder.java
@@ -27,31 +27,16 @@ import org.apache.geode.management.internal.cli.result.CommandResult;
 public class CommandResponseBuilder {
 
   public static CommandResponse prepareCommandResponse(String memberName, CommandResult result) {
-    GfJsonObject content = null;
-    try {
-      content = result.getContent();
-    } catch (GfJsonException e) {
-      try {
-        content = new GfJsonObject(e.getMessage());
-      } catch (GfJsonException e1) {
-        content = new GfJsonObject();
-      }
-    }
-    return new CommandResponse(memberName, // sender
-        getType(result), // contentType
-        result.getStatus().getCode(), // status code
-        "1/1", // page --- TODO - Abhishek - define a scrollable ResultData
-        CliMetaData.ANNOTATION_NULL_VALUE, // tokenAccessor for next results
-        getDebugInfo(result), // debugData
-        result.getHeader(), // header
-        content, // content
-        result.getFooter(), // footer
-        result.failedToPersist()); // failed to persist
+    GfJsonObject content;
+    content = result.getContent();
+    return new CommandResponse(memberName, getType(result), result.getStatus().getCode(), "1/1",
+        CliMetaData.ANNOTATION_NULL_VALUE, getDebugInfo(result), result.getHeader(), content,
+        result.getFooter(), result.failedToPersist());
   }
 
   // De-serializing to CommandResponse
   public static CommandResponse prepareCommandResponseFromJson(String jsonString) {
-    GfJsonObject jsonObject = null;
+    GfJsonObject jsonObject;
     try {
       jsonObject = new GfJsonObject(jsonString);
     } catch (GfJsonException e) {

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java
index 157bb91..a22f615 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java
@@ -14,7 +14,6 @@
  */
 package org.apache.geode.management.internal.cli;
 
-import java.io.IOException;
 import java.io.PrintStream;
 import java.util.HashSet;
 import java.util.List;
@@ -94,7 +93,7 @@ public class Launcher {
 
   protected Launcher() {
     this.startupTimeLogHelper = new StartupTimeLogHelper();
-    this.allowedCommandLineCommands = new HashSet<String>();
+    this.allowedCommandLineCommands = new HashSet<>();
     this.allowedCommandLineCommands.add(CliStrings.RUN);
     this.allowedCommandLineCommands.add(CliStrings.START_PULSE);
     this.allowedCommandLineCommands.add(CliStrings.START_JCONSOLE);
@@ -141,10 +140,6 @@ public class Launcher {
     try {
       gfsh = Gfsh.getInstance(false, args, new GfshConfig());
       this.startupTimeLogHelper.logStartupTime();
-    } catch (ClassNotFoundException cnfex) {
-      log(cnfex, gfsh);
-    } catch (IOException ioex) {
-      log(ioex, gfsh);
     } catch (IllegalStateException isex) {
       System.err.println("ERROR : " + isex.getMessage());
     }
@@ -208,10 +203,6 @@ public class Launcher {
     try {
       gfsh = Gfsh.getInstance(launchShell, args, new GfshConfig());
       this.startupTimeLogHelper.logStartupTime();
-    } catch (ClassNotFoundException cnfex) {
-      log(cnfex, gfsh);
-    } catch (IOException ioex) {
-      log(ioex, gfsh);
     } catch (IllegalStateException isex) {
       System.err.println("ERROR : " + isex.getMessage());
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/LogWrapper.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/LogWrapper.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/LogWrapper.java
index 6aa4f74..2cd15f4 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/LogWrapper.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/LogWrapper.java
@@ -16,12 +16,12 @@ package org.apache.geode.management.internal.cli;
 
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.io.StringWriter;
 import java.text.BreakIterator;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.logging.ConsoleHandler;
 import java.util.logging.FileHandler;
-import java.util.logging.Filter;
 import java.util.logging.Formatter;
 import java.util.logging.Handler;
 import java.util.logging.Level;
@@ -41,7 +41,7 @@ import org.apache.geode.management.internal.cli.shell.GfshConfig;
  */
 public class LogWrapper {
   private static Object INSTANCE_LOCK = new Object();
-  private volatile static LogWrapper INSTANCE = null;
+  private static volatile LogWrapper INSTANCE = null;
 
   private Logger logger;
 
@@ -50,15 +50,9 @@ public class LogWrapper {
 
     Cache cache = CliUtil.getCacheIfExists();
     if (cache != null && !cache.isClosed()) {
-      // TODO - Abhishek how to set different log levels for different handlers???
       logger.addHandler(cache.getLogger().getHandler());
       CommandResponseWriterHandler handler = new CommandResponseWriterHandler();
-      handler.setFilter(new Filter() {
-        @Override
-        public boolean isLoggable(LogRecord record) {
-          return record.getLevel().intValue() >= Level.FINE.intValue();
-        }
-      });
+      handler.setFilter(record -> record.getLevel().intValue() >= Level.FINE.intValue());
       handler.setLevel(Level.FINE);
       logger.addHandler(handler);
     }
@@ -81,14 +75,12 @@ public class LogWrapper {
     if (config.isLoggingEnabled()) {
       try {
         FileHandler fileHandler = new FileHandler(config.getLogFilePath(),
-            config.getLogFileSizeLimit(), config.getLogFileCount(), true /* append */);
+            config.getLogFileSizeLimit(), config.getLogFileCount(), true);
         fileHandler.setFormatter(new GemFireFormatter());
         fileHandler.setLevel(config.getLogLevel());
         logger.addHandler(fileHandler);
         logger.setLevel(config.getLogLevel());
-      } catch (SecurityException e) {
-        addDefaultConsoleHandler(logger, e.getMessage(), config.getLogFilePath());
-      } catch (IOException e) {
+      } catch (SecurityException | IOException e) {
         addDefaultConsoleHandler(logger, e.getMessage(), config.getLogFilePath());
       }
     }
@@ -164,8 +156,7 @@ public class LogWrapper {
     return logger.getLevel();
   }
 
-  // TODO - Abhishek - ideally shouldn't be exposed outside.
-  /* package */ Logger getLogger() {
+  Logger getLogger() {
     return logger;
   }
 
@@ -185,19 +176,6 @@ public class LogWrapper {
     }
   }
 
-  // TODO - Abhishek - Check whether we can use GemFireLevel.ERROR
-  // public boolean errorEnabled() {
-  // return severeEnabled();
-  // }
-  //
-  // public void error(String message) {
-  // logger.severe(message);
-  // }
-  //
-  // public void error(String message, Throwable t) {
-  // logger.log(Level.SEVERE, message, t);
-  // }
-
   public boolean warningEnabled() {
     return logger.isLoggable(Level.WARNING);
   }
@@ -298,15 +276,14 @@ public class LogWrapper {
    *
    * @since GemFire 7.0
    */
-  // Formatter code "copied" from LogWriterImpl
   static class GemFireFormatter extends Formatter {
-    private final static String FORMAT = "yyyy/MM/dd HH:mm:ss.SSS z";
+    private static final String FORMAT = "yyyy/MM/dd HH:mm:ss.SSS z";
 
     private SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
 
     @Override
     public synchronized String format(LogRecord record) {
-      java.io.StringWriter sw = new java.io.StringWriter();
+      StringWriter sw = new StringWriter();
       PrintWriter pw = new PrintWriter(sw);
 
       pw.println();
@@ -348,10 +325,9 @@ public class LogWrapper {
       pw.close();
       try {
         sw.close();
-      } catch (java.io.IOException ignore) {
+      } catch (IOException ignore) {
       }
-      String result = sw.toString();
-      return result;
+      return sw.toString();
     }
 
     private void formatText(PrintWriter writer, String target, int initialLength) {

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConnectCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConnectCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConnectCommand.java
index d0f2e5a..a75eeb0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConnectCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConnectCommand.java
@@ -22,14 +22,13 @@ import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_S
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
-import java.net.MalformedURLException;
 import java.security.KeyStore;
+import java.security.SecureRandom;
 import java.util.Arrays;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Properties;
 
-import javax.net.ssl.HostnameVerifier;
 import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.KeyManagerFactory;
 import javax.net.ssl.SSLContext;
@@ -69,9 +68,9 @@ import org.apache.geode.security.AuthenticationFailedException;
 
 public class ConnectCommand implements GfshCommand {
   // millis that connect --locator will wait for a response from the locator.
-  public final static int CONNECT_LOCATOR_TIMEOUT_MS = 60000; // see bug 45971
+  static final int CONNECT_LOCATOR_TIMEOUT_MS = 60000; // see bug 45971
 
-  static UserInputProperty[] USERINPUTPROPERTIES =
+  private static UserInputProperty[] USERINPUTPROPERTIES =
       {UserInputProperty.KEYSTORE, UserInputProperty.KEYSTORE_PASSWORD,
           UserInputProperty.KEYSTORE_TYPE, UserInputProperty.TRUSTSTORE,
           UserInputProperty.TRUSTSTORE_PASSWORD, UserInputProperty.TRUSTSTORE_TYPE,
@@ -117,8 +116,7 @@ public class ConnectCommand implements GfshCommand {
           help = CliStrings.CONNECT__USE_SSL__HELP) boolean useSsl,
       @CliOption(key = {"skip-ssl-validation"}, specifiedDefaultValue = "true",
           unspecifiedDefaultValue = "false",
-          help = "When connecting via HTTP, connects using 1-way SSL validation rather than 2-way SSL validation.") boolean skipSslValidation)
-      throws MalformedURLException {
+          help = "When connecting via HTTP, connects using 1-way SSL validation rather than 2-way SSL validation.") boolean skipSslValidation) {
 
     Result result;
     Gfsh gfsh = getGfsh();
@@ -213,10 +211,7 @@ public class ConnectCommand implements GfshCommand {
   }
 
   boolean isSslImpliedBySslOptions(String... sslOptions) {
-    if (sslOptions == null) {
-      return false;
-    }
-    return Arrays.stream(sslOptions).anyMatch(Objects::nonNull);
+    return sslOptions != null && Arrays.stream(sslOptions).anyMatch(Objects::nonNull);
   }
 
   Properties loadProperties(File... files) {
@@ -279,25 +274,22 @@ public class ConnectCommand implements GfshCommand {
       return ResultBuilder.createInfoResult(
           CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, operationInvoker.toString()));
 
-    } catch (Exception e) {
-      // all other exceptions, just logs it and returns a connection error
-      if (!(e instanceof SecurityException) && !(e instanceof AuthenticationFailedException)) {
-        return handleExcpetion(e, null);
-      }
-
-      // if it's security exception, and we already sent in username and password, still retuns the
+    } catch (SecurityException | AuthenticationFailedException e) {
+      // if it's security exception, and we already sent in username and password, still returns the
       // connection error
       if (gfProperties.containsKey(ResourceConstants.USER_NAME)) {
-        return handleExcpetion(e, null);
+        return handleException(e);
       }
 
-      // otherwise, prompt for username and password and retry the conenction
+      // otherwise, prompt for username and password and retry the connection
       gfProperties.setProperty(UserInputProperty.USERNAME.getKey(),
           UserInputProperty.USERNAME.promptForAcceptableValue(gfsh));
       gfProperties.setProperty(UserInputProperty.PASSWORD.getKey(),
           UserInputProperty.PASSWORD.promptForAcceptableValue(gfsh));
       return httpConnect(gfProperties, url);
-
+    } catch (Exception e) {
+      // all other exceptions, just logs it and returns a connection error
+      return handleException(e);
     } finally {
       Gfsh.redirectInternalJavaLoggers();
     }
@@ -358,25 +350,22 @@ public class ConnectCommand implements GfshCommand {
       LogWrapper.getInstance().info(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS,
           jmxHostPortToConnect.toString(false)));
       return ResultBuilder.buildResult(infoResultData);
-    } catch (Exception e) {
-      // all other exceptions, just logs it and returns a connection error
-      if (!(e instanceof SecurityException) && !(e instanceof AuthenticationFailedException)) {
-        return handleExcpetion(e, jmxHostPortToConnect);
-      }
-
+    } catch (SecurityException | AuthenticationFailedException e) {
       // if it's security exception, and we already sent in username and password, still returns the
       // connection error
       if (gfProperties.containsKey(ResourceConstants.USER_NAME)) {
-        return handleExcpetion(e, jmxHostPortToConnect);
+        return handleException(e, jmxHostPortToConnect);
       }
 
-      // otherwise, prompt for username and password and retry the conenction
+      // otherwise, prompt for username and password and retry the connection
       gfProperties.setProperty(UserInputProperty.USERNAME.getKey(),
           UserInputProperty.USERNAME.promptForAcceptableValue(gfsh));
       gfProperties.setProperty(UserInputProperty.PASSWORD.getKey(),
           UserInputProperty.PASSWORD.promptForAcceptableValue(gfsh));
       return jmxConnect(gfProperties, useSsl, jmxHostPortToConnect, null, true);
-
+    } catch (Exception e) {
+      // all other exceptions, just logs it and returns a connection error
+      return handleException(e, jmxHostPortToConnect);
     } finally {
       Gfsh.redirectInternalJavaLoggers();
     }
@@ -448,7 +437,7 @@ public class ConnectCommand implements GfshCommand {
 
       ssl.init(keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null,
           trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null,
-          new java.security.SecureRandom());
+          new SecureRandom());
 
       HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
     } finally {
@@ -461,13 +450,20 @@ public class ConnectCommand implements GfshCommand {
     }
   }
 
-  private Result handleExcpetion(Exception e, ConnectionEndpoint hostPortToConnect) {
-    String errorMessage = e.getMessage();
-    if (hostPortToConnect != null) {
-      errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__ERROR,
-          hostPortToConnect.toString(false), e.getMessage());
-    }
+  private Result handleException(Exception e) {
+    return handleException(e, e.getMessage());
+  }
+
+  private Result handleException(Exception e, String errorMessage) {
     LogWrapper.getInstance().severe(errorMessage, e);
     return ResultBuilder.createConnectionErrorResult(errorMessage);
   }
+
+  private Result handleException(Exception e, ConnectionEndpoint hostPortToConnect) {
+    if (hostPortToConnect == null) {
+      return handleException(e);
+    }
+    return handleException(e, CliStrings.format(CliStrings.CONNECT__MSG__ERROR,
+        hostPortToConnect.toString(false), e.getMessage()));
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java
index d2f9371..fca84a7 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java
@@ -44,6 +44,7 @@ import org.apache.geode.management.cli.Result;
 import org.apache.geode.management.internal.cli.CliUtil;
 import org.apache.geode.management.internal.cli.GfshParser;
 import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.converters.RegionPathConverter;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.result.ErrorResultData;
 import org.apache.geode.management.internal.cli.result.InfoResultData;
@@ -159,7 +160,7 @@ public class ShellCommands implements GfshCommand {
 
   @CliCommand(value = {CliStrings.EXIT, "quit"}, help = CliStrings.EXIT__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
-  public ExitShellRequest exit() throws IOException {
+  public ExitShellRequest exit() {
     Gfsh gfshInstance = getGfsh();
 
     gfshInstance.stop();
@@ -179,7 +180,7 @@ public class ShellCommands implements GfshCommand {
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEODE_JMX,
       CliStrings.TOPIC_GEODE_MANAGER})
   public Result disconnect() {
-    Result result = null;
+    Result result;
 
     if (getGfsh() != null && !getGfsh().isConnectedAndReady()) {
       result = ResultBuilder.createInfoResult("Not connected.");
@@ -195,8 +196,7 @@ public class ShellCommands implements GfshCommand {
               operationInvoker.toString()));
           LogWrapper.getInstance().info(CliStrings.format(CliStrings.DISCONNECT__MSG__DISCONNECTED,
               operationInvoker.toString()));
-          gfshInstance.setPromptPath(
-              org.apache.geode.management.internal.cli.converters.RegionPathConverter.DEFAULT_APP_CONTEXT_PATH);
+          gfshInstance.setPromptPath(RegionPathConverter.DEFAULT_APP_CONTEXT_PATH);
         } else {
           infoResultData.addLine(CliStrings.DISCONNECT__MSG__NOTCONNECTED);
         }
@@ -213,13 +213,12 @@ public class ShellCommands implements GfshCommand {
   @CliCommand(value = {CliStrings.DESCRIBE_CONNECTION}, help = CliStrings.DESCRIBE_CONNECTION__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEODE_JMX})
   public Result describeConnection() {
-    Result result = null;
+    Result result;
     try {
       TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
       Gfsh gfshInstance = getGfsh();
       if (gfshInstance.isConnectedAndReady()) {
         OperationInvoker operationInvoker = gfshInstance.getOperationInvoker();
-        // tabularResultData.accumulate("Monitored GemFire DS", operationInvoker.toString());
         tabularResultData.accumulate("Connection Endpoints", operationInvoker.toString());
       } else {
         tabularResultData.accumulate("Connection Endpoints", "Not connected");
@@ -238,7 +237,7 @@ public class ShellCommands implements GfshCommand {
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
   public Result echo(@CliOption(key = {CliStrings.ECHO__STR, ""}, specifiedDefaultValue = "",
       mandatory = true, help = CliStrings.ECHO__STR__HELP) String stringToEcho) {
-    Result result = null;
+    Result result;
 
     if (stringToEcho.equals("$*")) {
       Gfsh gfshInstance = getGfsh();
@@ -256,10 +255,8 @@ public class ShellCommands implements GfshCommand {
 
   TabularResultData buildResultForEcho(Set<Entry<String, String>> propertyMap) {
     TabularResultData resultData = ResultBuilder.createTabularResultData();
-    Iterator<Entry<String, String>> it = propertyMap.iterator();
 
-    while (it.hasNext()) {
-      Entry<String, String> setEntry = it.next();
+    for (Entry<String, String> setEntry : propertyMap) {
       resultData.accumulate("Property", setEntry.getKey());
       resultData.accumulate("Value", String.valueOf(setEntry.getValue()));
     }
@@ -273,7 +270,7 @@ public class ShellCommands implements GfshCommand {
           help = CliStrings.SET_VARIABLE__VAR__HELP) String var,
       @CliOption(key = CliStrings.SET_VARIABLE__VALUE, mandatory = true,
           help = CliStrings.SET_VARIABLE__VALUE__HELP) String value) {
-    Result result = null;
+    Result result;
     try {
       getGfsh().setEnvProperty(var, String.valueOf(value));
       result =
@@ -329,7 +326,7 @@ public class ShellCommands implements GfshCommand {
     } else {
       // Process file option
       Gfsh gfsh = Gfsh.getCurrentInstance();
-      ErrorResultData errorResultData = null;
+      ErrorResultData errorResultData;
       StringBuilder contents = new StringBuilder();
       Writer output = null;
 
@@ -344,7 +341,7 @@ public class ShellCommands implements GfshCommand {
 
       while (it.hasNext()) {
         String line = it.next().toString();
-        if (line.isEmpty() == false) {
+        if (!line.isEmpty()) {
           if (flagForLineNumbers) {
             lineNumber++;
             contents.append(String.format("%" + historySizeWordLength + "s  ", lineNumber));
@@ -429,7 +426,7 @@ public class ShellCommands implements GfshCommand {
       @CliOption(key = {CliStrings.RUN__CONTINUEONERROR}, specifiedDefaultValue = "true",
           unspecifiedDefaultValue = "false",
           help = CliStrings.RUN__CONTINUEONERROR__HELP) boolean continueOnError) {
-    Result result = null;
+    Result result;
 
     Gfsh gfsh = Gfsh.getCurrentInstance();
     try {
@@ -457,7 +454,7 @@ public class ShellCommands implements GfshCommand {
     try {
       LogWrapper.getInstance().fine("Sleeping for " + time + "seconds.");
       Thread.sleep(Math.round(time * 1000));
-    } catch (InterruptedException ignorable) {
+    } catch (InterruptedException ignored) {
     }
     return ResultBuilder.createInfoResult("");
   }
@@ -470,15 +467,11 @@ public class ShellCommands implements GfshCommand {
       @CliOption(key = CliStrings.SH__USE_CONSOLE, specifiedDefaultValue = "true",
           unspecifiedDefaultValue = "false",
           help = CliStrings.SH__USE_CONSOLE__HELP) boolean useConsole) {
-    Result result = null;
+    Result result;
     try {
       result =
           ResultBuilder.buildResult(executeCommand(Gfsh.getCurrentInstance(), command, useConsole));
-    } catch (IllegalStateException e) {
-      result = ResultBuilder.createUserErrorResult(e.getMessage());
-      LogWrapper.getInstance()
-          .warning("Unable to execute command \"" + command + "\". Reason:" + e.getMessage() + ".");
-    } catch (IOException e) {
+    } catch (IllegalStateException | IOException e) {
       result = ResultBuilder.createUserErrorResult(e.getMessage());
       LogWrapper.getInstance()
           .warning("Unable to execute command \"" + command + "\". Reason:" + e.getMessage() + ".");

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
index 6236b38..7db3155 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
@@ -396,9 +396,6 @@ public class ShowMetricsCommand implements GfshCommand {
             csvBuilder);
         writeToTableAndCsv(metricsTable, "", "putAllAvgLatency", memberMxBean.getPutAllAvgLatency(),
             csvBuilder);
-        // Not available from stats. After Stats re-org it will be available
-        // writeToTableAndCsv(metricsTable, "", "getAllAvgLatency",
-        // memberMxBean.getGetAllAvgLatency(), csvBuilder);
         writeToTableAndCsv(metricsTable, "", "totalMissCount", memberMxBean.getTotalMissCount(),
             csvBuilder);
         writeToTableAndCsv(metricsTable, "", "totalHitCount", memberMxBean.getTotalHitCount(),

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java
index 3e1053a..44d32a4 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java
@@ -29,6 +29,7 @@ import java.util.Properties;
 import javax.management.MalformedObjectNameException;
 
 import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.lang.StringUtils;
 
 import org.apache.geode.distributed.internal.DistributionConfig;
 import org.apache.geode.internal.GemFireVersion;
@@ -102,7 +103,7 @@ public class StartMemberUtils {
     for (final Object property : gemfireProperties.keySet()) {
       final String propertyName = property.toString();
       final String propertyValue = gemfireProperties.getProperty(propertyName);
-      if (org.apache.geode.internal.lang.StringUtils.isNotBlank(propertyValue)) {
+      if (StringUtils.isNotBlank(propertyValue)) {
         commandLine.add(
             "-D" + DistributionConfig.GEMFIRE_PREFIX + "" + propertyName + "=" + propertyValue);
       }
@@ -117,26 +118,24 @@ public class StartMemberUtils {
   }
 
   static void addInitialHeap(final List<String> commandLine, final String initialHeap) {
-    if (org.apache.geode.internal.lang.StringUtils.isNotBlank(initialHeap)) {
+    if (StringUtils.isNotBlank(initialHeap)) {
       commandLine.add("-Xms" + initialHeap);
     }
   }
 
   static void addMaxHeap(final List<String> commandLine, final String maxHeap) {
-    if (org.apache.geode.internal.lang.StringUtils.isNotBlank(maxHeap)) {
+    if (StringUtils.isNotBlank(maxHeap)) {
       commandLine.add("-Xmx" + maxHeap);
       commandLine.add("-XX:+UseConcMarkSweepGC");
       commandLine.add("-XX:CMSInitiatingOccupancyFraction=" + CMS_INITIAL_OCCUPANCY_FRACTION);
-      // commandLine.add("-XX:MinHeapFreeRatio=" + MINIMUM_HEAP_FREE_RATIO);
     }
   }
 
   static void addCurrentLocators(GfshCommand gfshCommand, final List<String> commandLine,
       final Properties gemfireProperties) throws MalformedObjectNameException {
-    if (org.apache.geode.internal.lang.StringUtils
-        .isBlank(gemfireProperties.getProperty(LOCATORS))) {
+    if (StringUtils.isBlank(gemfireProperties.getProperty(LOCATORS))) {
       String currentLocators = getCurrentLocators(gfshCommand);
-      if (org.apache.geode.internal.lang.StringUtils.isNotBlank(currentLocators)) {
+      if (StringUtils.isNotBlank(currentLocators)) {
         commandLine.add("-D".concat(ProcessLauncherContext.OVERRIDDEN_DEFAULTS_PREFIX)
             .concat(LOCATORS).concat("=").concat(currentLocators));
       }
@@ -209,9 +208,8 @@ public class StartMemberUtils {
     // System CLASSPATH environment variable setting, which is consistent with the Java platform
     // behavior...
     for (String userClasspath : userClasspaths) {
-      if (org.apache.geode.internal.lang.StringUtils.isNotBlank(userClasspath)) {
-        classpath.append((classpath.length() == 0)
-            ? org.apache.geode.internal.lang.StringUtils.EMPTY : File.pathSeparator);
+      if (StringUtils.isNotBlank(userClasspath)) {
+        classpath.append((classpath.length() == 0) ? StringUtils.EMPTY : File.pathSeparator);
         classpath.append(userClasspath);
       }
     }
@@ -227,9 +225,8 @@ public class StartMemberUtils {
 
     // And finally, include all GemFire dependencies on the CLASSPATH...
     for (String jarFilePathname : jarFilePathnames) {
-      if (org.apache.geode.internal.lang.StringUtils.isNotBlank(jarFilePathname)) {
-        classpath.append((classpath.length() == 0)
-            ? org.apache.geode.internal.lang.StringUtils.EMPTY : File.pathSeparator);
+      if (StringUtils.isNotBlank(jarFilePathname)) {
+        classpath.append((classpath.length() == 0) ? StringUtils.EMPTY : File.pathSeparator);
         classpath.append(jarFilePathname);
       }
     }
@@ -240,7 +237,6 @@ public class StartMemberUtils {
     String classpath = getSystemClasspath();
     String gemfireJarPath = GEODE_JAR_PATHNAME;
     for (String classpathElement : classpath.split(File.pathSeparator)) {
-      // MUST CHANGE THIS TO REGEX SINCE VERSION CHANGES IN JAR NAME
       if (classpathElement.endsWith("gemfire-core-8.2.0.0-SNAPSHOT.jar")) {
         gemfireJarPath = classpathElement;
         break;


[15/47] geode git commit: GEODE-3436: Restore refactoring of IndexCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
index 5ff0a67..6dc23ce 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
@@ -23,7 +23,22 @@ import static org.apache.geode.test.dunit.Assert.assertTrue;
 import static org.apache.geode.test.dunit.LogWriterUtils.getDUnitLogLevel;
 import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
 
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
+
 import org.apache.commons.lang.StringUtils;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.Region;
@@ -43,27 +58,18 @@ import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.SerializableRunnableIF;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicLong;
 
 /**
  * The ListIndexCommandDUnitTest class is distributed test suite of test cases for testing the
  * index-based GemFire shell (Gfsh) commands.
  *
  * @see org.apache.geode.management.internal.cli.commands.CliCommandTestBase
- * @see org.apache.geode.management.internal.cli.commands.IndexCommands
+ * @see org.apache.geode.management.internal.cli.commands.ClearDefinedIndexesCommand
+ * @see org.apache.geode.management.internal.cli.commands.CreateDefinedIndexesCommand
+ * @see org.apache.geode.management.internal.cli.commands.CreateIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.DefineIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.DestroyIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.ListIndexCommand
  * @since GemFire 7.0
  */
 @SuppressWarnings("unused")
@@ -690,7 +696,7 @@ public class ListIndexCommandDUnitTest extends CliCommandTestBase {
     }
   }
 
-  private static enum CrudOperation {
+  private enum CrudOperation {
     CREATE, RETRIEVE, UPDATE, DELETE
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
new file mode 100644
index 0000000..8deb4ae
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
@@ -0,0 +1,223 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import org.jmock.Expectations;
+import org.jmock.Mockery;
+import org.jmock.lib.concurrent.Synchroniser;
+import org.jmock.lib.legacy.ClassImposteriser;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.cache.execute.AbstractExecution;
+import org.apache.geode.internal.util.CollectionUtils;
+import org.apache.geode.management.internal.cli.domain.IndexDetails;
+import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
+import org.apache.geode.test.junit.categories.UnitTest;
+
+/**
+ * The ListIndexCommandJUnitTest class is a test suite of test cases testing the contract and
+ * functionality of the ListIndexCommand class.
+ * </p>
+ * 
+ * @see org.apache.geode.management.internal.cli.commands.ClearDefinedIndexesCommand
+ * @see org.apache.geode.management.internal.cli.commands.CreateDefinedIndexesCommand
+ * @see org.apache.geode.management.internal.cli.commands.CreateIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.DefineIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.DestroyIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.ListIndexCommand
+ * @see org.apache.geode.management.internal.cli.domain.IndexDetails
+ * @see org.apache.geode.management.internal.cli.functions.ListIndexFunction
+ * @see org.jmock.Expectations
+ * @see org.jmock.Mockery
+ * @see org.jmock.lib.legacy.ClassImposteriser
+ * @see org.junit.Assert
+ * @see org.junit.Test
+ * @since GemFire 7.0
+ */
+@Category(UnitTest.class)
+public class ListIndexCommandJUnitTest {
+  private Mockery mockContext;
+
+  @Before
+  public void setup() {
+    mockContext = new Mockery() {
+      {
+        setImposteriser(ClassImposteriser.INSTANCE);
+        setThreadingPolicy(new Synchroniser());
+      }
+    };
+  }
+
+  @After
+  public void tearDown() {
+    mockContext.assertIsSatisfied();
+    mockContext = null;
+  }
+
+  private ListIndexCommand createListIndexCommand(final InternalCache cache,
+      final Execution functionExecutor) {
+    return new TestListIndexCommands(cache, functionExecutor);
+  }
+
+  private IndexDetails createIndexDetails(final String memberId, final String indexName) {
+    return new IndexDetails(memberId, "/Employees", indexName);
+  }
+
+  @Test
+  public void testGetIndexListing() {
+    final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
+
+    final AbstractExecution mockFunctionExecutor =
+        mockContext.mock(AbstractExecution.class, "Function Executor");
+
+    final ResultCollector mockResultCollector =
+        mockContext.mock(ResultCollector.class, "ResultCollector");
+
+    final IndexDetails indexDetails1 = createIndexDetails("memberOne", "empIdIdx");
+    final IndexDetails indexDetails2 = createIndexDetails("memberOne", "empLastNameIdx");
+    final IndexDetails indexDetails3 = createIndexDetails("memberTwo", "empDobIdx");
+
+    final List<IndexDetails> expectedIndexDetails =
+        Arrays.asList(indexDetails1, indexDetails2, indexDetails3);
+
+    final List<Set<IndexDetails>> results = new ArrayList<Set<IndexDetails>>(2);
+
+    results.add(CollectionUtils.asSet(indexDetails2, indexDetails1));
+    results.add(CollectionUtils.asSet(indexDetails3));
+
+    mockContext.checking(new Expectations() {
+      {
+        oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
+        oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
+        will(returnValue(mockResultCollector));
+        oneOf(mockResultCollector).getResult();
+        will(returnValue(results));
+      }
+    });
+
+    final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
+    final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
+
+    assertNotNull(actualIndexDetails);
+    assertEquals(expectedIndexDetails, actualIndexDetails);
+  }
+
+  @Test(expected = RuntimeException.class)
+  public void testGetIndexListingThrowsRuntimeException() {
+    final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
+    final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
+
+    mockContext.checking(new Expectations() {
+      {
+        oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
+        will(throwException(new RuntimeException("expected")));
+      }
+    });
+
+    final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
+
+    try {
+      commands.getIndexListing();
+    } catch (RuntimeException expected) {
+      assertEquals("expected", expected.getMessage());
+      throw expected;
+    }
+  }
+
+  @Test
+  public void testGetIndexListingReturnsFunctionInvocationTargetExceptionInResults() {
+    final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
+
+    final AbstractExecution mockFunctionExecutor =
+        mockContext.mock(AbstractExecution.class, "Function Executor");
+
+    final ResultCollector mockResultCollector =
+        mockContext.mock(ResultCollector.class, "ResultCollector");
+
+    final IndexDetails indexDetails = createIndexDetails("memberOne", "empIdIdx");
+
+    final List<IndexDetails> expectedIndexDetails = Collections.singletonList(indexDetails);
+
+    final List<Object> results = new ArrayList<Object>(2);
+
+    results.add(CollectionUtils.asSet(indexDetails));
+    results.add(new FunctionInvocationTargetException("expected"));
+
+    mockContext.checking(new Expectations() {
+      {
+        oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
+        oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
+        will(returnValue(mockResultCollector));
+        oneOf(mockResultCollector).getResult();
+        will(returnValue(results));
+      }
+    });
+
+    final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
+
+    final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
+
+    assertNotNull(actualIndexDetails);
+    assertEquals(expectedIndexDetails, actualIndexDetails);
+  }
+
+  private static class TestListIndexCommands extends ListIndexCommand {
+    private final InternalCache cache;
+    private final Execution functionExecutor;
+
+    TestListIndexCommands(final InternalCache cache, final Execution functionExecutor) {
+      assert cache != null : "The InternalCache cannot be null!";
+      assert functionExecutor != null : "The function executor cannot be null!";
+      this.cache = cache;
+      this.functionExecutor = functionExecutor;
+    }
+
+    @Override
+    public InternalCache getCache() {
+      return this.cache;
+    }
+
+    @Override
+    public Set<DistributedMember> getMembers(final InternalCache cache) {
+      assertSame(getCache(), cache);
+      return Collections.emptySet();
+    }
+
+    @Override
+    public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
+      Assert.assertNotNull(members);
+      return functionExecutor;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0dc67f0e/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index 853853b..4efa93f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -200,7 +200,8 @@ public class TestCommand {
     createTestCommand("hint");
     createTestCommand("help");
 
-    // IndexCommands
+    // ClearDefinedIndexesCommand, CreateDefinedIndexesCommand, CreateIndexCommand,
+    // DefineIndexCommand, DestroyIndexCommand, ListIndexCommand
     createTestCommand("clear defined indexes", clusterManageQuery);
     createTestCommand("create defined indexes", clusterManageQuery);
     createTestCommand(


[20/47] geode git commit: GEODE-3436: Restore refactoring of Refactoring MiscellaneousCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of Refactoring MiscellaneousCommands

* See initial commit GEODE-3265 (63169699e933f6e0fdd90b95ed039e4e3c92c32c)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 611095f0a196ee58a51da6a75367791eff18ca19
Parents: 39fff45
Author: YehEmily <em...@gmail.com>
Authored: Mon Aug 7 15:37:23 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:26 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/ChangeLogLevelCommand.java     |  163 ++
 .../cli/commands/ExportStackTraceCommand.java   |  182 ++
 .../internal/cli/commands/GCCommand.java        |  131 ++
 .../cli/commands/MiscellaneousCommands.java     | 1926 ------------------
 .../internal/cli/commands/NetstatCommand.java   |  212 ++
 .../cli/commands/ShowDeadlockCommand.java       |   92 +
 .../internal/cli/commands/ShowLogCommand.java   |  102 +
 .../cli/commands/ShowMetricsCommand.java        | 1085 ++++++++++
 .../internal/cli/commands/ShutdownCommand.java  |  209 ++
 .../MiscellaneousCommandsController.java        |    9 +-
 .../cli/commands/LogLevelInterceptorTest.java   |   19 +-
 .../MiscellaneousCommandsDUnitTest.java         |  136 +-
 .../security/GfshCommandsSecurityTest.java      |    4 +-
 .../internal/security/TestCommand.java          |    9 +-
 14 files changed, 2275 insertions(+), 2004 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ChangeLogLevelCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ChangeLogLevelCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ChangeLogLevelCommand.java
new file mode 100644
index 0000000..823c113
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ChangeLogLevelCommand.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.LogWriter;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.logging.log4j.LogLevel;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.ChangeLogLevelFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ChangeLogLevelCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.CHANGE_LOGLEVEL, help = CliStrings.CHANGE_LOGLEVEL__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_LOGS},
+      interceptor = "org.apache.geode.management.internal.cli.commands.ChangeLogLevelCommand$ChangeLogLevelCommandInterceptor")
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.WRITE)
+  public Result changeLogLevel(
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          help = CliStrings.CHANGE_LOGLEVEL__MEMBER__HELP) String[] memberIds,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, unspecifiedDefaultValue = "",
+          help = CliStrings.CHANGE_LOGLEVEL__GROUPS__HELP) String[] grps,
+      @CliOption(key = CliStrings.CHANGE_LOGLEVEL__LOGLEVEL,
+          optionContext = ConverterHint.LOG_LEVEL, mandatory = true, unspecifiedDefaultValue = "",
+          help = CliStrings.CHANGE_LOGLEVEL__LOGLEVEL__HELP) String logLevel) {
+    try {
+      if ((memberIds == null || memberIds.length == 0) && (grps == null || grps.length == 0)) {
+        return ResultBuilder
+            .createUserErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG__SPECIFY_GRP_OR_MEMBER);
+      }
+
+      InternalCache cache = GemFireCacheImpl.getInstance();
+      LogWriter logger = cache.getLogger();
+
+      Set<DistributedMember> dsMembers = new HashSet<>();
+      Set<DistributedMember> ds = CliUtil.getAllMembers(cache);
+
+      if (grps != null && grps.length > 0) {
+        for (String grp : grps) {
+          dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
+        }
+      }
+
+      if (memberIds != null && memberIds.length > 0) {
+        for (String member : memberIds) {
+          for (DistributedMember mem : ds) {
+            if (mem.getName() != null
+                && (mem.getName().equals(member) || mem.getId().equals(member))) {
+              dsMembers.add(mem);
+              break;
+            }
+          }
+        }
+      }
+
+      if (dsMembers.size() == 0) {
+        return ResultBuilder.createGemFireErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG_NO_MEMBERS);
+      }
+
+      Function logFunction = new ChangeLogLevelFunction();
+      FunctionService.registerFunction(logFunction);
+      Object[] functionArgs = new Object[1];
+      functionArgs[0] = logLevel;
+
+      CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
+      CompositeResultData.SectionResultData section = compositeResultData.addSection("section");
+      TabularResultData resultTable = section.addTable("ChangeLogLevel");
+      resultTable = resultTable.setHeader("Summary");
+
+      Execution execution = FunctionService.onMembers(dsMembers).setArguments(functionArgs);
+      if (execution == null) {
+        return ResultBuilder.createUserErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG__CANNOT_EXECUTE);
+      }
+      List<?> resultList = (List<?>) execution.execute(logFunction).getResult();
+
+      for (Object object : resultList) {
+        try {
+          if (object instanceof Throwable) {
+            logger.warning(
+                "Exception in ChangeLogLevelFunction " + ((Throwable) object).getMessage(),
+                ((Throwable) object));
+            continue;
+          }
+
+          if (object != null) {
+            Map<String, String> resultMap = (Map<String, String>) object;
+            Map.Entry<String, String> entry = resultMap.entrySet().iterator().next();
+
+            if (entry.getValue().contains("ChangeLogLevelFunction exception")) {
+              resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_MEMBER, entry.getKey());
+              resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_STATUS, "false");
+            } else {
+              resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_MEMBER, entry.getKey());
+              resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_STATUS, "true");
+            }
+
+          }
+        } catch (Exception ex) {
+          LogWrapper.getInstance().warning("change log level command exception " + ex);
+        }
+      }
+
+      Result result = ResultBuilder.buildResult(compositeResultData);
+      logger.info("change log-level command result=" + result);
+      return result;
+    } catch (Exception ex) {
+      GemFireCacheImpl.getInstance().getLogger().error("GFSH Changeloglevel exception: " + ex);
+      return ResultBuilder.createUserErrorResult(ex.getMessage());
+    }
+  }
+
+  public static class ChangeLogLevelCommandInterceptor extends AbstractCliAroundInterceptor {
+    @Override
+    public Result preExecution(GfshParseResult parseResult) {
+      Map<String, String> arguments = parseResult.getParamValueStrings();
+      // validate log level
+      String logLevel = arguments.get("loglevel");
+      if (StringUtils.isBlank(logLevel) || LogLevel.getLevel(logLevel) == null) {
+        return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
+      }
+
+      return ResultBuilder.createInfoResult("");
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
new file mode 100644
index 0000000..a5749ca
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.zip.GZIPInputStream;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.domain.StackTracesPerMember;
+import org.apache.geode.management.internal.cli.functions.GetStackTracesFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ExportStackTraceCommand implements GfshCommand {
+  private final GetStackTracesFunction getStackTracesFunction = new GetStackTracesFunction();
+
+  /**
+   * Current implementation supports writing it to a file and returning the location of the file
+   */
+  @CliCommand(value = CliStrings.EXPORT_STACKTRACE, help = CliStrings.EXPORT_STACKTRACE__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result exportStackTrace(@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+      optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+      help = CliStrings.EXPORT_STACKTRACE__HELP) String[] memberNameOrId,
+
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.GROUP) String[] group,
+
+      @CliOption(key = CliStrings.EXPORT_STACKTRACE__FILE,
+          help = CliStrings.EXPORT_STACKTRACE__FILE__HELP) String fileName,
+
+      @CliOption(key = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT,
+          unspecifiedDefaultValue = "false",
+          help = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT__HELP) boolean failIfFilePresent) {
+
+    Result result;
+    StringBuilder filePrefix = new StringBuilder("stacktrace");
+
+    if (fileName == null) {
+      fileName = filePrefix.append("_").append(System.currentTimeMillis()).toString();
+    }
+    final File outFile = new File(fileName);
+    try {
+      if (outFile.exists() && failIfFilePresent) {
+        return ResultBuilder.createShellClientErrorResult(CliStrings.format(
+            CliStrings.EXPORT_STACKTRACE__ERROR__FILE__PRESENT, outFile.getCanonicalPath()));
+      }
+
+
+      InternalCache cache = getCache();
+      InternalDistributedSystem ads = cache.getInternalDistributedSystem();
+
+      InfoResultData resultData = ResultBuilder.createInfoResultData();
+
+      Map<String, byte[]> dumps = new HashMap<>();
+      Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+      if (targetMembers.isEmpty()) {
+        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+      }
+
+      ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(getStackTracesFunction, null, targetMembers);
+      ArrayList<Object> resultList = (ArrayList<Object>) rc.getResult();
+
+      for (Object resultObj : resultList) {
+        if (resultObj instanceof StackTracesPerMember) {
+          StackTracesPerMember stackTracePerMember = (StackTracesPerMember) resultObj;
+          dumps.put(stackTracePerMember.getMemberNameOrId(), stackTracePerMember.getStackTraces());
+        }
+      }
+
+      String filePath = writeStacksToFile(dumps, fileName);
+      resultData.addLine(CliStrings.format(CliStrings.EXPORT_STACKTRACE__SUCCESS, filePath));
+      resultData.addLine(CliStrings.EXPORT_STACKTRACE__HOST + ads.getDistributedMember().getHost());
+
+      result = ResultBuilder.buildResult(resultData);
+    } catch (IOException ex) {
+      result = ResultBuilder
+          .createGemFireErrorResult(CliStrings.EXPORT_STACKTRACE__ERROR + ex.getMessage());
+    }
+    return result;
+  }
+
+  // TODO PSR: ExportStackTrace Interceptor appeared to exist, but was not hooked to command and has
+  // a clearly incorrect javadoc.
+  // TODO PSR: It appears it was introduced in 2016-11-26: 903135115a0466d86fa663e965ace3ff47eba6b4,
+  // but never correctly linked to the command.
+  public static class ExportStackTraceInterceptor extends AbstractCliAroundInterceptor {
+    @Override
+    public Result preExecution(GfshParseResult parseResult) {
+
+      Map<String, String> paramValueMap = parseResult.getParamValueStrings();
+      String fileName = paramValueMap.get(CliStrings.EXPORT_STACKTRACE__FILE);
+
+      Response response = readYesNo(
+          CliStrings.format(CliStrings.EXPORT_STACKTRACE_WARN_USER, fileName), Response.YES);
+      if (response == Response.NO) {
+        return ResultBuilder
+            .createShellClientAbortOperationResult(CliStrings.EXPORT_STACKTRACE_MSG_ABORTING);
+      } else {
+        // we don't to show any info result
+        return ResultBuilder.createInfoResult("");
+      }
+    }
+  }
+
+  /***
+   * Writes the Stack traces member-wise to a text file
+   *
+   * @param dumps - Map containing key : member , value : zipped stack traces
+   * @param fileName - Name of the file to which the stack-traces are written to
+   * @return Canonical path of the file which contains the stack-traces
+   * @throws IOException
+   */
+  private String writeStacksToFile(Map<String, byte[]> dumps, String fileName) throws IOException {
+    String filePath;
+    PrintWriter ps;
+    File outputFile;
+
+    outputFile = new File(fileName);
+    try (OutputStream os = new FileOutputStream(outputFile)) {
+      ps = new PrintWriter(os);
+
+      for (Map.Entry<String, byte[]> entry : dumps.entrySet()) {
+        ps.append("*** Stack-trace for member ").append(entry.getKey()).append(" ***");
+        ps.flush();
+        GZIPInputStream zipIn = new GZIPInputStream(new ByteArrayInputStream(entry.getValue()));
+        BufferedInputStream bin = new BufferedInputStream(zipIn);
+        byte[] buffer = new byte[10000];
+        int count;
+        while ((count = bin.read(buffer)) != -1) {
+          os.write(buffer, 0, count);
+        }
+        ps.append('\n');
+      }
+      ps.flush();
+      filePath = outputFile.getCanonicalPath();
+    }
+
+    return filePath;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GCCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GCCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GCCommand.java
new file mode 100644
index 0000000..4884d6d
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GCCommand.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.GarbageCollectionFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class GCCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.GC, help = CliStrings.GC__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE)
+  public Result gc(
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          help = CliStrings.GC__GROUP__HELP) String[] groups,
+      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+          help = CliStrings.GC__MEMBER__HELP) String memberId) {
+    InternalCache cache = getCache();
+    Result result;
+    CompositeResultData gcResultTable = ResultBuilder.createCompositeResultData();
+    TabularResultData resultTable = gcResultTable.addSection().addTable("Table1");
+    String headerText = "GC Summary";
+    resultTable.setHeader(headerText);
+    Set<DistributedMember> dsMembers = new HashSet<>();
+    if (memberId != null && memberId.length() > 0) {
+      DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberId);
+      if (member == null) {
+        return ResultBuilder
+            .createGemFireErrorResult(memberId + CliStrings.GC__MSG__MEMBER_NOT_FOUND);
+      }
+      dsMembers.add(member);
+      result = executeAndBuildResult(resultTable, dsMembers);
+    } else if (groups != null && groups.length > 0) {
+      for (String group : groups) {
+        dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(group));
+      }
+      result = executeAndBuildResult(resultTable, dsMembers);
+
+    } else {
+      // gc on entire cluster
+      // exclude locators
+      dsMembers = CliUtil.getAllNormalMembers(cache);
+      result = executeAndBuildResult(resultTable, dsMembers);
+
+    }
+    return result;
+  }
+
+  private Result executeAndBuildResult(TabularResultData resultTable,
+      Set<DistributedMember> dsMembers) {
+    try {
+      List<?> resultList;
+      Function garbageCollectionFunction = new GarbageCollectionFunction();
+      resultList =
+          (List<?>) CliUtil.executeFunction(garbageCollectionFunction, null, dsMembers).getResult();
+
+      for (Object object : resultList) {
+        if (object instanceof Exception) {
+          LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
+              ((Throwable) object));
+          continue;
+        } else if (object instanceof Throwable) {
+          LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
+              ((Throwable) object));
+          continue;
+        }
+
+        if (object != null) {
+          if (object instanceof String) {
+            // unexpected exception string - cache may be closed or something
+            return ResultBuilder.createUserErrorResult((String) object);
+          } else {
+            Map<String, String> resultMap = (Map<String, String>) object;
+            toTabularResultData(resultTable, resultMap.get("MemberId"),
+                resultMap.get("HeapSizeBeforeGC"), resultMap.get("HeapSizeAfterGC"),
+                resultMap.get("TimeSpentInGC"));
+          }
+        } else {
+          LogWrapper.getInstance().fine("ResultMap was null ");
+        }
+      }
+    } catch (Exception e) {
+      String stack = CliUtil.stackTraceAsString(e);
+      LogWrapper.getInstance().info("GC exception is " + stack);
+      return ResultBuilder.createGemFireErrorResult(e.getMessage() + ": " + stack);
+    }
+    return ResultBuilder.buildResult(resultTable);
+  }
+
+  private void toTabularResultData(TabularResultData table, String memberId, String heapSizeBefore,
+      String heapSizeAfter, String timeTaken) {
+    table.accumulate(CliStrings.GC__MSG__MEMBER_NAME, memberId);
+    table.accumulate(CliStrings.GC__MSG__HEAP_SIZE_BEFORE_GC, heapSizeBefore);
+    table.accumulate(CliStrings.GC__MSG__HEAP_SIZE_AFTER_GC, heapSizeAfter);
+    table.accumulate(CliStrings.GC__MSG__TOTAL_TIME_IN_GC, timeTaken);
+  }
+}


[05/47] geode git commit: GEODE-3436: Restore refactoring of PDXCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of PDXCommands

* See initial commit GEODE-3266 (67185abcdd68b908dea6888cb94286b8aa9ea49f)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 50dd10b76bf1264aa3e89bdfff2d9feda3facf44
Parents: 7ff9539
Author: YehEmily <em...@gmail.com>
Authored: Fri Aug 4 10:47:48 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:23 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/ConfigurePDXCommand.java       | 138 +++++++++++++
 .../internal/cli/commands/PDXCommands.java      | 195 -------------------
 .../internal/cli/commands/PDXRenameCommand.java |  81 ++++++++
 .../web/controllers/PdxCommandsController.java  |   3 +-
 4 files changed, 221 insertions(+), 196 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/50dd10b7/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigurePDXCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigurePDXCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigurePDXCommand.java
new file mode 100644
index 0000000..8c490f4
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigurePDXCommand.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Arrays;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.internal.cache.CacheConfig;
+import org.apache.geode.internal.cache.xmlcache.CacheCreation;
+import org.apache.geode.internal.cache.xmlcache.CacheXml;
+import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.pdx.ReflectionBasedAutoSerializer;
+import org.apache.geode.security.ResourcePermission;
+
+public class ConfigurePDXCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.CONFIGURE_PDX, help = CliStrings.CONFIGURE_PDX__HELP)
+  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE)
+  public Result configurePDX(
+      @CliOption(key = CliStrings.CONFIGURE_PDX__READ__SERIALIZED,
+          help = CliStrings.CONFIGURE_PDX__READ__SERIALIZED__HELP) Boolean readSerialized,
+      @CliOption(key = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS,
+          help = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS__HELP) Boolean ignoreUnreadFields,
+      @CliOption(key = CliStrings.CONFIGURE_PDX__DISKSTORE, specifiedDefaultValue = "",
+          help = CliStrings.CONFIGURE_PDX__DISKSTORE__HELP) String diskStore,
+      @CliOption(key = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES,
+          help = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES__HELP) String[] patterns,
+      @CliOption(key = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES,
+          help = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES__HELP) String[] portablePatterns) {
+    Result result;
+
+    try {
+      InfoResultData ird = ResultBuilder.createInfoResultData();
+      CacheCreation cache = new CacheCreation(true);
+
+      if ((portablePatterns != null && portablePatterns.length > 0)
+          && (patterns != null && patterns.length > 0)) {
+        return ResultBuilder.createUserErrorResult(CliStrings.CONFIGURE_PDX__ERROR__MESSAGE);
+      }
+      if (!CliUtil.getAllNormalMembers(CliUtil.getCacheIfExists()).isEmpty()) {
+        ird.addLine(CliStrings.CONFIGURE_PDX__NORMAL__MEMBERS__WARNING);
+      }
+      // Set persistent and the disk-store
+      if (diskStore != null) {
+        cache.setPdxPersistent(true);
+        ird.addLine(CliStrings.CONFIGURE_PDX__PERSISTENT + " = " + cache.getPdxPersistent());
+        if (!diskStore.equals("")) {
+          cache.setPdxDiskStore(diskStore);
+          ird.addLine(CliStrings.CONFIGURE_PDX__DISKSTORE + " = " + cache.getPdxDiskStore());
+        } else {
+          ird.addLine(CliStrings.CONFIGURE_PDX__DISKSTORE + " = " + "DEFAULT");
+        }
+      } else {
+        cache.setPdxPersistent(CacheConfig.DEFAULT_PDX_PERSISTENT);
+        ird.addLine(CliStrings.CONFIGURE_PDX__PERSISTENT + " = " + cache.getPdxPersistent());
+      }
+
+      // Set read-serialized
+      if (readSerialized != null) {
+        cache.setPdxReadSerialized(readSerialized);
+      } else {
+        cache.setPdxReadSerialized(CacheConfig.DEFAULT_PDX_READ_SERIALIZED);
+      }
+      ird.addLine(
+          CliStrings.CONFIGURE_PDX__READ__SERIALIZED + " = " + cache.getPdxReadSerialized());
+
+
+      // Set ignoreUnreadFields
+      if (ignoreUnreadFields != null) {
+        cache.setPdxIgnoreUnreadFields(ignoreUnreadFields);
+      } else {
+        cache.setPdxIgnoreUnreadFields(CacheConfig.DEFAULT_PDX_IGNORE_UNREAD_FIELDS);
+      }
+      ird.addLine(CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS + " = "
+          + cache.getPdxIgnoreUnreadFields());
+
+
+      if (portablePatterns != null) {
+        ReflectionBasedAutoSerializer autoSerializer =
+            new ReflectionBasedAutoSerializer(portablePatterns);
+        cache.setPdxSerializer(autoSerializer);
+        ird.addLine("PDX Serializer " + cache.getPdxSerializer().getClass().getName());
+        ird.addLine("Portable classes " + Arrays.toString(portablePatterns));
+      }
+
+      if (patterns != null) {
+        ReflectionBasedAutoSerializer nonPortableAutoSerializer =
+            new ReflectionBasedAutoSerializer(true, patterns);
+        cache.setPdxSerializer(nonPortableAutoSerializer);
+        ird.addLine("PDX Serializer : " + cache.getPdxSerializer().getClass().getName());
+        ird.addLine("Non portable classes :" + Arrays.toString(patterns));
+      }
+
+      final StringWriter stringWriter = new StringWriter();
+      final PrintWriter printWriter = new PrintWriter(stringWriter);
+      CacheXmlGenerator.generate(cache, printWriter, true, false, false);
+      printWriter.close();
+      String xmlDefinition = stringWriter.toString();
+      // TODO jbarrett - shouldn't this use the same loadXmlDefinition that other constructors use?
+      XmlEntity xmlEntity =
+          XmlEntity.builder().withType(CacheXml.PDX).withConfig(xmlDefinition).build();
+
+      result = ResultBuilder.buildResult(ird);
+      persistClusterConfiguration(result,
+          () -> getSharedConfiguration().addXmlEntity(xmlEntity, null));
+
+    } catch (Exception e) {
+      return ResultBuilder.createGemFireErrorResult(e.getMessage());
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/50dd10b7/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
deleted file mode 100644
index e0bad15..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Arrays;
-import java.util.Collection;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.internal.cache.CacheConfig;
-import org.apache.geode.internal.cache.DiskStoreImpl;
-import org.apache.geode.internal.cache.xmlcache.CacheCreation;
-import org.apache.geode.internal.cache.xmlcache.CacheXml;
-import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.pdx.ReflectionBasedAutoSerializer;
-import org.apache.geode.pdx.internal.EnumInfo;
-import org.apache.geode.pdx.internal.PdxType;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-
-public class PDXCommands implements GfshCommand {
-
-
-  @CliCommand(value = CliStrings.CONFIGURE_PDX, help = CliStrings.CONFIGURE_PDX__HELP)
-  @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
-  public Result configurePDX(
-      @CliOption(key = CliStrings.CONFIGURE_PDX__READ__SERIALIZED,
-          help = CliStrings.CONFIGURE_PDX__READ__SERIALIZED__HELP) Boolean readSerialized,
-      @CliOption(key = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS,
-          help = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS__HELP) Boolean ignoreUnreadFields,
-      @CliOption(key = CliStrings.CONFIGURE_PDX__DISKSTORE, specifiedDefaultValue = "",
-          help = CliStrings.CONFIGURE_PDX__DISKSTORE__HELP) String diskStore,
-      @CliOption(key = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES,
-          help = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES__HELP) String[] patterns,
-      @CliOption(key = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES,
-          help = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES__HELP) String[] portablePatterns) {
-    Result result;
-
-    try {
-      InfoResultData ird = ResultBuilder.createInfoResultData();
-      CacheCreation cache = new CacheCreation(true);
-
-      if ((portablePatterns != null && portablePatterns.length > 0)
-          && (patterns != null && patterns.length > 0)) {
-        return ResultBuilder.createUserErrorResult(CliStrings.CONFIGURE_PDX__ERROR__MESSAGE);
-      }
-      if (!CliUtil.getAllNormalMembers(CliUtil.getCacheIfExists()).isEmpty()) {
-        ird.addLine(CliStrings.CONFIGURE_PDX__NORMAL__MEMBERS__WARNING);
-      }
-      // Set persistent and the disk-store
-      if (diskStore != null) {
-        cache.setPdxPersistent(true);
-        ird.addLine(CliStrings.CONFIGURE_PDX__PERSISTENT + " = " + cache.getPdxPersistent());
-        if (!diskStore.equals("")) {
-          cache.setPdxDiskStore(diskStore);
-          ird.addLine(CliStrings.CONFIGURE_PDX__DISKSTORE + " = " + cache.getPdxDiskStore());
-        } else {
-          ird.addLine(CliStrings.CONFIGURE_PDX__DISKSTORE + " = " + "DEFAULT");
-        }
-      } else {
-        cache.setPdxPersistent(CacheConfig.DEFAULT_PDX_PERSISTENT);
-        ird.addLine(CliStrings.CONFIGURE_PDX__PERSISTENT + " = " + cache.getPdxPersistent());
-      }
-
-      // Set read-serialized
-      if (readSerialized != null) {
-        cache.setPdxReadSerialized(readSerialized);
-      } else {
-        cache.setPdxReadSerialized(CacheConfig.DEFAULT_PDX_READ_SERIALIZED);
-      }
-      ird.addLine(
-          CliStrings.CONFIGURE_PDX__READ__SERIALIZED + " = " + cache.getPdxReadSerialized());
-
-
-      // Set ignoreUnreadFields
-      if (ignoreUnreadFields != null) {
-        cache.setPdxIgnoreUnreadFields(ignoreUnreadFields);
-      } else {
-        cache.setPdxIgnoreUnreadFields(CacheConfig.DEFAULT_PDX_IGNORE_UNREAD_FIELDS);
-      }
-      ird.addLine(CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS + " = "
-          + cache.getPdxIgnoreUnreadFields());
-
-
-      if (portablePatterns != null) {
-        ReflectionBasedAutoSerializer autoSerializer =
-            new ReflectionBasedAutoSerializer(portablePatterns);
-        cache.setPdxSerializer(autoSerializer);
-        ird.addLine("PDX Serializer " + cache.getPdxSerializer().getClass().getName());
-        ird.addLine("Portable classes " + Arrays.toString(portablePatterns));
-      }
-
-      if (patterns != null) {
-        ReflectionBasedAutoSerializer nonPortableAutoSerializer =
-            new ReflectionBasedAutoSerializer(true, patterns);
-        cache.setPdxSerializer(nonPortableAutoSerializer);
-        ird.addLine("PDX Serializer : " + cache.getPdxSerializer().getClass().getName());
-        ird.addLine("Non portable classes :" + Arrays.toString(patterns));
-      }
-
-      final StringWriter stringWriter = new StringWriter();
-      final PrintWriter printWriter = new PrintWriter(stringWriter);
-      CacheXmlGenerator.generate(cache, printWriter, true, false, false);
-      printWriter.close();
-      String xmlDefinition = stringWriter.toString();
-      // TODO jbarrett - shouldn't this use the same loadXmlDefinition that other constructors use?
-      XmlEntity xmlEntity =
-          XmlEntity.builder().withType(CacheXml.PDX).withConfig(xmlDefinition).build();
-
-      result = ResultBuilder.buildResult(ird);
-      persistClusterConfiguration(result,
-          () -> getSharedConfiguration().addXmlEntity(xmlEntity, null));
-
-    } catch (Exception e) {
-      return ResultBuilder.createGemFireErrorResult(e.getMessage());
-    }
-
-    return result;
-  }
-
-  @CliCommand(value = CliStrings.PDX_RENAME, help = CliStrings.PDX_RENAME__HELP)
-  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
-  public Result pdxRename(@CliOption(key = CliStrings.PDX_RENAME_OLD, mandatory = true,
-      help = CliStrings.PDX_RENAME_OLD__HELP) String oldClassName,
-
-      @CliOption(key = CliStrings.PDX_RENAME_NEW, mandatory = true,
-          help = CliStrings.PDX_RENAME_NEW__HELP) String newClassName,
-
-      @CliOption(key = CliStrings.PDX_DISKSTORE, mandatory = true,
-          help = CliStrings.PDX_DISKSTORE__HELP) String diskStore,
-
-      @CliOption(key = CliStrings.PDX_DISKDIR, mandatory = true,
-          help = CliStrings.PDX_DISKDIR__HELP) String[] diskDirs) {
-
-    try {
-      final File[] dirs = new File[diskDirs.length];
-      for (int i = 0; i < diskDirs.length; i++) {
-        dirs[i] = new File((diskDirs[i]));
-      }
-
-      Collection<Object> results =
-          DiskStoreImpl.pdxRename(diskStore, dirs, oldClassName, newClassName);
-
-      if (results.isEmpty()) {
-        return ResultBuilder
-            .createGemFireErrorResult(CliStrings.format(CliStrings.PDX_RENAME__EMPTY));
-      }
-
-      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
-      PrintStream printStream = new PrintStream(outputStream);
-      for (Object p : results) {
-        if (p instanceof PdxType) {
-          ((PdxType) p).toStream(printStream, false);
-        } else {
-          ((EnumInfo) p).toStream(printStream);
-        }
-      }
-      String resultString =
-          CliStrings.format(CliStrings.PDX_RENAME__SUCCESS, outputStream.toString());
-      return ResultBuilder.createInfoResult(resultString);
-
-    } catch (Exception e) {
-      return ResultBuilder.createGemFireErrorResult(
-          CliStrings.format(CliStrings.PDX_RENAME__ERROR, e.getMessage()));
-    }
-
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/50dd10b7/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXRenameCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXRenameCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXRenameCommand.java
new file mode 100644
index 0000000..8831597
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXRenameCommand.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.PrintStream;
+import java.util.Collection;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.internal.cache.DiskStoreImpl;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.pdx.internal.EnumInfo;
+import org.apache.geode.pdx.internal.PdxType;
+
+public class PDXRenameCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.PDX_RENAME, help = CliStrings.PDX_RENAME__HELP)
+  @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+  public Result pdxRename(@CliOption(key = CliStrings.PDX_RENAME_OLD, mandatory = true,
+      help = CliStrings.PDX_RENAME_OLD__HELP) String oldClassName,
+
+      @CliOption(key = CliStrings.PDX_RENAME_NEW, mandatory = true,
+          help = CliStrings.PDX_RENAME_NEW__HELP) String newClassName,
+
+      @CliOption(key = CliStrings.PDX_DISKSTORE, mandatory = true,
+          help = CliStrings.PDX_DISKSTORE__HELP) String diskStore,
+
+      @CliOption(key = CliStrings.PDX_DISKDIR, mandatory = true,
+          help = CliStrings.PDX_DISKDIR__HELP) String[] diskDirs) {
+
+    try {
+      final File[] dirs = new File[diskDirs.length];
+      for (int i = 0; i < diskDirs.length; i++) {
+        dirs[i] = new File((diskDirs[i]));
+      }
+
+      Collection<Object> results =
+          DiskStoreImpl.pdxRename(diskStore, dirs, oldClassName, newClassName);
+
+      if (results.isEmpty()) {
+        return ResultBuilder
+            .createGemFireErrorResult(CliStrings.format(CliStrings.PDX_RENAME__EMPTY));
+      }
+
+      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+      PrintStream printStream = new PrintStream(outputStream);
+      for (Object p : results) {
+        if (p instanceof PdxType) {
+          ((PdxType) p).toStream(printStream, false);
+        } else {
+          ((EnumInfo) p).toStream(printStream);
+        }
+      }
+      String resultString =
+          CliStrings.format(CliStrings.PDX_RENAME__SUCCESS, outputStream.toString());
+      return ResultBuilder.createInfoResult(resultString);
+
+    } catch (Exception e) {
+      return ResultBuilder.createGemFireErrorResult(
+          CliStrings.format(CliStrings.PDX_RENAME__ERROR, e.getMessage()));
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/50dd10b7/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
index c757fd3..2722964 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
@@ -27,7 +27,8 @@ import org.springframework.web.bind.annotation.ResponseBody;
  * The PdxCommandsController class implements GemFire Management REST API web service endpoints for
  * Gfsh PDX Commands.
  *
- * @see org.apache.geode.management.internal.cli.commands.PDXCommands
+ * @see org.apache.geode.management.internal.cli.commands.PDXRenameCommand
+ * @see org.apache.geode.management.internal.cli.commands.ConfigurePDXCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.RequestMapping


[11/47] geode git commit: GEODE-3436: Restore refactoring of CreateAlterDestroyRegionCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
index e913746..a1b9ade 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
@@ -27,37 +27,39 @@ import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
 import static org.apache.geode.distributed.ConfigurationProperties.NAME;
 import static org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION;
 import static org.apache.geode.test.dunit.Assert.assertEquals;
-import static org.apache.geode.test.dunit.Assert.assertFalse;
 import static org.apache.geode.test.dunit.Assert.assertNotNull;
-import static org.apache.geode.test.dunit.Assert.assertNull;
 import static org.apache.geode.test.dunit.Assert.assertTrue;
 import static org.apache.geode.test.dunit.Assert.fail;
 import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
 import static org.awaitility.Awaitility.waitAtMost;
 
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.text.MessageFormat;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
 import org.apache.commons.io.FileUtils;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.PartitionAttributes;
-import org.apache.geode.cache.PartitionAttributesFactory;
-import org.apache.geode.cache.PartitionResolver;
 import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionAttributes;
-import org.apache.geode.cache.RegionFactory;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.Scope;
-import org.apache.geode.cache.asyncqueue.AsyncEvent;
-import org.apache.geode.cache.asyncqueue.AsyncEventListener;
-import org.apache.geode.cache.wan.GatewaySenderFactory;
-import org.apache.geode.compression.SnappyCompressor;
 import org.apache.geode.distributed.Locator;
 import org.apache.geode.distributed.internal.ClusterConfigurationService;
 import org.apache.geode.distributed.internal.InternalLocator;
 import org.apache.geode.internal.AvailablePort;
 import org.apache.geode.internal.AvailablePortHelper;
-import org.apache.geode.internal.ClassBuilder;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.PartitionedRegion;
-import org.apache.geode.internal.cache.RegionEntryContext;
 import org.apache.geode.management.ManagementService;
 import org.apache.geode.management.cli.Result;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
@@ -70,330 +72,26 @@ import org.apache.geode.test.dunit.SerializableCallable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.categories.FlakyTest;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.text.MessageFormat;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.TimeUnit;
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
 
 @Category(DistributedTest.class)
 public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBase {
-
   private static final long serialVersionUID = 1L;
+  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
 
-  final String alterRegionName = "testAlterRegionRegion";
-  final String alterAsyncEventQueueId1 = "testAlterRegionQueue1";
-  final String alterAsyncEventQueueId2 = "testAlterRegionQueue2";
-  final String alterAsyncEventQueueId3 = "testAlterRegionQueue3";
-  final String alterGatewaySenderId1 = "testAlterRegionSender1";
-  final String alterGatewaySenderId2 = "testAlterRegionSender2";
-  final String alterGatewaySenderId3 = "testAlterRegionSender3";
-  final String region46391 = "region46391";
-  VM alterVm1;
-  String alterVm1Name;
-  VM alterVm2;
-  String alterVm2Name;
-
-  final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
-
-  /**
-   * Asserts that the "compressor" option for the "create region" command succeeds for a recognized
-   * compressor.
-   */
-  @Test
-  public void testCreateRegionWithGoodCompressor() {
-    setUpJmxManagerOnVm0ThenConnect(null);
-    VM vm = Host.getHost(0).getVM(1);
-
-    // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
-
-    // Run create region command with compression
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "compressedRegion");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__COMPRESSOR,
-        RegionEntryContext.DEFAULT_COMPRESSION_PROVIDER);
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    // Make sure our region exists with compression enabled
-    vm.invoke(() -> {
-      Region region = getCache().getRegion("compressedRegion");
-      assertNotNull(region);
-      assertTrue(
-          SnappyCompressor.getDefaultInstance().equals(region.getAttributes().getCompressor()));
-    });
-
-    // cleanup
-    commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
-    commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, "compressedRegion");
-    cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-  }
-
-  /**
-   * Asserts that the "compressor" option for the "create region" command fails for an unrecognized
-   * compressorc.
-   */
-  @Test
-  public void testCreateRegionWithBadCompressor() {
-    setUpJmxManagerOnVm0ThenConnect(null);
-
-    VM vm = Host.getHost(0).getVM(1);
-
-    // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
-
-    // Create a region with an unrecognized compressor
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "compressedRegion");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__COMPRESSOR, "BAD_COMPRESSOR");
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
-    // Assert that our region was not created
-    vm.invoke(() -> {
-      Region region = getCache().getRegion("compressedRegion");
-      assertNull(region);
-    });
-  }
-
-  /**
-   * Asserts that a missing "compressor" option for the "create region" command results in a region
-   * with no compression.
-   */
-  @Test
-  public void testCreateRegionWithNoCompressor() {
-    setUpJmxManagerOnVm0ThenConnect(null);
-
-    VM vm = Host.getHost(0).getVM(1);
-
-    // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
-
-    // Create a region with no compression
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "testRegion");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    // Assert that our newly created region has no compression
-    vm.invoke(() -> {
-      Region region = getCache().getRegion("testRegion");
-      assertNotNull(region);
-      assertNull(region.getAttributes().getCompressor());
-    });
-
-    // Cleanup
-    commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
-    commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, "testRegion");
-    cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-  }
-
-  @Test
-  public void testDestroyDistributedRegion() {
-    setUpJmxManagerOnVm0ThenConnect(null);
-
-    for (int i = 1; i <= 2; i++) {
-      Host.getHost(0).getVM(i).invoke(() -> {
-        final Cache cache = getCache();
-
-        RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.PARTITION);
-        factory.create("Customer");
-
-        PartitionAttributesFactory paFactory = new PartitionAttributesFactory();
-        paFactory.setColocatedWith("Customer");
-        factory.setPartitionAttributes(paFactory.create());
-        factory.create("Order");
-      });
-    }
-
-    waitForRegionMBeanCreation("/Customer", 2);
-    waitForRegionMBeanCreation("/Order", 2);
-
-    // Test failure when region not found
-    String command = "destroy region --name=DOESNOTEXIST";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    CommandResult cmdResult = executeCommand(command);
-    String strr = commandResultToString(cmdResult);
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
-    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
-    // Test unable to destroy with co-location
-    command = "destroy region --name=/Customer";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    cmdResult = executeCommand(command);
-    strr = commandResultToString(cmdResult);
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
-    // Test success
-    command = "destroy region --name=/Order";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    cmdResult = executeCommand(command);
-    strr = commandResultToString(cmdResult);
-    assertTrue(stringContainsLine(strr, ".*Order.*destroyed successfully.*"));
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    command = "destroy region --name=/Customer";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    cmdResult = executeCommand(command);
-    strr = commandResultToString(cmdResult);
-    assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-  }
-
-  @Test
-  public void testDestroyLocalRegions() {
-    setUpJmxManagerOnVm0ThenConnect(null);
-
-    for (int i = 1; i <= 3; i++) {
-      Host.getHost(0).getVM(i).invoke(() -> {
-        final Cache cache = getCache();
-
-        RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.REPLICATE);
-        factory.setScope(Scope.LOCAL);
-        factory.create("Customer");
-      });
-    }
-
-    waitForRegionMBeanCreation("/Customer", 3);
-
-    // Test failure when region not found
-    String command = "destroy region --name=DOESNOTEXIST";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    CommandResult cmdResult = executeCommand(command);
-    String strr = commandResultToString(cmdResult);
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
-    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
-    command = "destroy region --name=/Customer";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    cmdResult = executeCommand(command);
-    strr = commandResultToString(cmdResult);
-    assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    for (int i = 1; i <= 3; i++) {
-      final int x = i;
-      Host.getHost(0).getVM(i).invoke(() -> {
-        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
-      });
-    }
-  }
-
-  @Test
-  public void testDestroyLocalAndDistributedRegions() {
-    setUpJmxManagerOnVm0ThenConnect(null);
-
-    for (int i = 1; i <= 2; i++) {
-      Host.getHost(0).getVM(i).invoke(() -> {
-        final Cache cache = getCache();
-        RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.PARTITION);
-        factory.create("Customer");
-        factory.create("Customer-2");
-        factory.create("Customer_3");
-      });
-    }
-
-    Host.getHost(0).getVM(3).invoke(() -> {
-      final Cache cache = getCache();
-      RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.REPLICATE);
-      factory.setScope(Scope.LOCAL);
-      factory.create("Customer");
-      factory.create("Customer-2");
-      factory.create("Customer_3");
-    });
-
-    waitForRegionMBeanCreation("/Customer", 3);
-
-    // Test failure when region not found
-    String command = "destroy region --name=DOESNOTEXIST";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    CommandResult cmdResult = executeCommand(command);
-    String strr = commandResultToString(cmdResult);
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
-    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
-    command = "destroy region --name=/Customer";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    cmdResult = executeCommand(command);
-    strr = commandResultToString(cmdResult);
-    assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    command = "destroy region --name=/Customer_3";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    cmdResult = executeCommand(command);
-    strr = commandResultToString(cmdResult);
-    assertTrue(stringContainsLine(strr, ".*Customer_3.*destroyed successfully.*"));
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    command = "destroy region --name=/Customer-2";
-    getLogWriter().info("testDestroyRegion command=" + command);
-    cmdResult = executeCommand(command);
-    strr = commandResultToString(cmdResult);
-    assertTrue(stringContainsLine(strr, ".*Customer-2.*destroyed successfully.*"));
-    getLogWriter().info("testDestroyRegion strr=" + strr);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    for (int i = 1; i <= 3; i++) {
-      final int x = i;
-      Host.getHost(0).getVM(i).invoke(() -> {
-        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
-        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer-2"));
-        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer_3"));
-      });
-    }
-  }
-
-  private void waitForRegionMBeanCreation(final String regionPath, final int mbeanCount) {
+  private void waitForRegionMBeanCreation(final String regionPath) {
     Host.getHost(0).getVM(0).invoke(() -> {
-      waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath, mbeanCount));
+      waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath));
     });
   }
 
-  private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath, final int mbeanCount) {
+  private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath) {
     return () -> {
       try {
         MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
         String queryExp =
             MessageFormat.format(ManagementConstants.OBJECTNAME__REGION_MXBEAN, regionPath, "*");
         ObjectName queryExpON = new ObjectName(queryExp);
-        return mbeanServer.queryNames(null, queryExpON).size() == mbeanCount;
+        return mbeanServer.queryNames(null, queryExpON).size() == 1;
       } catch (MalformedObjectNameException mone) {
         getLogWriter().error(mone);
         fail(mone.getMessage());
@@ -402,556 +100,6 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
     };
   }
 
-  @Category(FlakyTest.class) // GEODE-973: random ports, BindException,
-                             // java.rmi.server.ExportException: Port already in use
-  @Test
-  public void testCreateRegion46391() throws IOException {
-    setUpJmxManagerOnVm0ThenConnect(null); // GEODE-973: getRandomAvailablePort
-    String command = CliStrings.CREATE_REGION + " --" + CliStrings.CREATE_REGION__REGION + "="
-        + this.region46391 + " --" + CliStrings.CREATE_REGION__REGIONSHORTCUT + "=REPLICATE";
-
-    getLogWriter().info("testCreateRegion46391 create region command=" + command);
-
-    CommandResult cmdResult = executeCommand(command);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    command = CliStrings.PUT + " --" + CliStrings.PUT__KEY + "=k1" + " --" + CliStrings.PUT__VALUE
-        + "=k1" + " --" + CliStrings.PUT__REGIONNAME + "=" + this.region46391;
-
-    getLogWriter().info("testCreateRegion46391 put command=" + command);
-
-    CommandResult cmdResult2 = executeCommand(command);
-    assertEquals(Result.Status.OK, cmdResult2.getStatus());
-
-    getLogWriter().info("testCreateRegion46391  cmdResult2=" + commandResultToString(cmdResult2));
-    String str1 = "Result      : true";
-    String str2 = "Key         : k1";
-    String str3 = "Key Class   : java.lang.String";
-    String str4 = "Value Class : java.lang.String";
-    String str5 = "Old Value   : <NULL>";
-
-    assertTrue(commandResultToString(cmdResult)
-        .contains("Region \"/" + this.region46391 + "\" created on"));
-
-    assertTrue(commandResultToString(cmdResult2).contains(str1));
-    assertTrue(commandResultToString(cmdResult2).contains(str2));
-    assertTrue(commandResultToString(cmdResult2).contains(str3));
-    assertTrue(commandResultToString(cmdResult2).contains(str4));
-    assertTrue(commandResultToString(cmdResult2).contains(str5));
-  }
-
-  @Ignore("bug51924")
-  @Test
-  public void testAlterRegion() throws IOException {
-    setUpJmxManagerOnVm0ThenConnect(null);
-
-    CommandResult cmdResult = executeCommand(CliStrings.LIST_REGION);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    assertTrue(commandResultToString(cmdResult).contains("No Regions Found"));
-
-    Host.getHost(0).getVM(0).invoke(() -> {
-      Cache cache = getCache();
-      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
-          .create(alterRegionName);
-    });
-
-    this.alterVm1 = Host.getHost(0).getVM(1);
-    this.alterVm1Name = "VM" + this.alterVm1.getPid();
-    this.alterVm1.invoke(() -> {
-      Properties localProps = new Properties();
-      localProps.setProperty(NAME, alterVm1Name);
-      localProps.setProperty(GROUPS, "Group1");
-      getSystem(localProps);
-      Cache cache = getCache();
-
-      // Setup queues and gateway senders to be used by all tests
-      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
-          .create(alterRegionName);
-      AsyncEventListener listener = new AsyncEventListener() {
-        @Override
-        public void close() {
-          // Nothing to do
-        }
-
-        @Override
-        public boolean processEvents(List<AsyncEvent> events) {
-          return true;
-        }
-      };
-      cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId1, listener);
-      cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId2, listener);
-      cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId3, listener);
-
-      GatewaySenderFactory gatewaySenderFactory = cache.createGatewaySenderFactory();
-      gatewaySenderFactory.setManualStart(true);
-      gatewaySenderFactory.create(alterGatewaySenderId1, 2);
-      gatewaySenderFactory.create(alterGatewaySenderId2, 3);
-      gatewaySenderFactory.create(alterGatewaySenderId3, 4);
-    });
-
-    this.alterVm2 = Host.getHost(0).getVM(2);
-    this.alterVm2Name = "VM" + this.alterVm2.getPid();
-    this.alterVm2.invoke(() -> {
-      Properties localProps = new Properties();
-      localProps.setProperty(NAME, alterVm2Name);
-      localProps.setProperty(GROUPS, "Group1,Group2");
-      getSystem(localProps);
-      Cache cache = getCache();
-
-      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
-          .create(alterRegionName);
-    });
-
-    deployJarFilesForRegionAlter();
-    regionAlterGroupTest();
-    regionAlterSetAllTest();
-    regionAlterNoChangeTest();
-    regionAlterSetDefaultsTest();
-    regionAlterManipulatePlugInsTest();
-
-    this.alterVm1.invoke(() -> {
-      getCache().getRegion(alterRegionName).destroyRegion();
-    });
-  }
-
-  private void regionAlterGroupTest() {
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "5764");
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    String stringResult = commandResultToString(cmdResult);
-    assertEquals(4, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm1.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
-    });
-
-    this.alterVm2.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
-    });
-
-    commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.GROUP, "Group2");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "6963");
-    cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    stringResult = commandResultToString(cmdResult);
-    assertEquals(3, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertFalse(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm1.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
-    });
-
-    this.alterVm2.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(6963, attributes.getEvictionAttributes().getMaximum());
-    });
-  }
-
-  private void regionAlterSetAllTest() {
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "35464");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED, "true");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId1);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME, "3453");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
-        "DESTROY");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE, "7563");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION, "DESTROY");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerA");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELOADER,
-        "com.cadrdunit.RegionAlterCacheLoader");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHEWRITER,
-        "com.cadrdunit.RegionAlterCacheWriter");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId1);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME, "6234");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION,
-        "DESTROY");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, "4562");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION, "DESTROY");
-
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    String stringResult = commandResultToString(cmdResult);
-    assertEquals(5, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        "Manager.*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm1.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(35464, attributes.getEvictionAttributes().getMaximum());
-      assertEquals(3453, attributes.getEntryIdleTimeout().getTimeout());
-      assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
-      assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
-      assertTrue(attributes.getEntryTimeToLive().getAction().isDestroy());
-      assertEquals(6234, attributes.getRegionIdleTimeout().getTimeout());
-      assertTrue(attributes.getRegionIdleTimeout().getAction().isDestroy());
-      assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
-      assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
-      assertEquals(1, attributes.getAsyncEventQueueIds().size());
-      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
-      assertEquals(1, attributes.getGatewaySenderIds().size());
-      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
-      assertEquals(1, attributes.getCacheListeners().length);
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
-          attributes.getCacheListeners()[0].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheWriter",
-          attributes.getCacheWriter().getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheLoader",
-          attributes.getCacheLoader().getClass().getName());
-    });
-  }
-
-  private void regionAlterNoChangeTest() {
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED, "true");
-
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    String stringResult = commandResultToString(cmdResult);
-    assertEquals(4, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm2.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(35464, attributes.getEvictionAttributes().getMaximum());
-      assertEquals(3453, attributes.getEntryIdleTimeout().getTimeout());
-      assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
-      assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
-      assertTrue(attributes.getEntryTimeToLive().getAction().isDestroy());
-      assertEquals(6234, attributes.getRegionIdleTimeout().getTimeout());
-      assertTrue(attributes.getRegionIdleTimeout().getAction().isDestroy());
-      assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
-      assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
-      assertEquals(1, attributes.getAsyncEventQueueIds().size());
-      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
-      assertEquals(1, attributes.getGatewaySenderIds().size());
-      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
-      assertEquals(1, attributes.getCacheListeners().length);
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
-          attributes.getCacheListeners()[0].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheWriter",
-          attributes.getCacheWriter().getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheLoader",
-          attributes.getCacheLoader().getClass().getName());
-    });
-  }
-
-  private void regionAlterSetDefaultsTest() {
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELOADER);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHEWRITER);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION);
-
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    String stringResult = commandResultToString(cmdResult);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    assertEquals(4, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm1.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(0, attributes.getEvictionAttributes().getMaximum());
-      assertEquals(0, attributes.getEntryIdleTimeout().getTimeout());
-      assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
-      assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
-      assertTrue(attributes.getEntryTimeToLive().getAction().isInvalidate());
-      assertEquals(0, attributes.getRegionIdleTimeout().getTimeout());
-      assertTrue(attributes.getRegionIdleTimeout().getAction().isInvalidate());
-      assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
-      assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
-      assertEquals(0, attributes.getAsyncEventQueueIds().size());
-      assertEquals(0, attributes.getGatewaySenderIds().size());
-      assertEquals(0, attributes.getCacheListeners().length);
-    });
-  }
-
-  private void regionAlterManipulatePlugInsTest() {
-
-    // Start out by putting 3 entries into each of the plug-in sets
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId1);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId2);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId3);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId1);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId2);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId3);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerA");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerB");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerC");
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    String stringResult = commandResultToString(cmdResult);
-
-    assertEquals(4, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm1.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(3, attributes.getAsyncEventQueueIds().size());
-      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
-      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId2));
-      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId3));
-      assertEquals(3, attributes.getGatewaySenderIds().size());
-      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
-      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId2));
-      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId3));
-      assertEquals(3, attributes.getCacheListeners().length);
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
-          attributes.getCacheListeners()[0].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
-          attributes.getCacheListeners()[1].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
-          attributes.getCacheListeners()[2].getClass().getName());
-    });
-
-    // Now take 1 entry out of each of the sets
-    commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId1);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId2);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId1);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId3);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerB");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerC");
-    cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    stringResult = commandResultToString(cmdResult);
-    assertEquals(4, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm2.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(2, attributes.getAsyncEventQueueIds().size());
-      Iterator iterator = attributes.getAsyncEventQueueIds().iterator();
-      assertEquals(alterAsyncEventQueueId1, iterator.next());
-      assertEquals(alterAsyncEventQueueId2, iterator.next());
-      assertEquals(2, attributes.getGatewaySenderIds().size());
-      iterator = attributes.getGatewaySenderIds().iterator();
-      assertEquals(alterGatewaySenderId1, iterator.next());
-      assertEquals(alterGatewaySenderId3, iterator.next());
-      assertEquals(2, attributes.getCacheListeners().length);
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
-          attributes.getCacheListeners()[0].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
-          attributes.getCacheListeners()[1].getClass().getName());
-    });
-
-    // Add 1 back to each of the sets
-    commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId1);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId2);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
-        this.alterAsyncEventQueueId3);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId1);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId3);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
-        this.alterGatewaySenderId2);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerB");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerC");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerA");
-    cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    stringResult = commandResultToString(cmdResult);
-    assertEquals(4, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm1.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(3, attributes.getAsyncEventQueueIds().size());
-      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
-      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId2));
-      assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId3));
-      assertEquals(3, attributes.getGatewaySenderIds().size());
-      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
-      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId3));
-      assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId2));
-      assertEquals(3, attributes.getCacheListeners().length);
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
-          attributes.getCacheListeners()[0].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
-          attributes.getCacheListeners()[1].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
-          attributes.getCacheListeners()[2].getClass().getName());
-    });
-  }
-
-  @Category(FlakyTest.class) // GEODE-3018
-  @Test
-  public void testAlterRegionResetCacheListeners() throws IOException {
-    setUpJmxManagerOnVm0ThenConnect(null);
-
-    CommandResult cmdResult = executeCommand(CliStrings.LIST_REGION);
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    assertTrue(commandResultToString(cmdResult).contains("No Regions Found"));
-
-    Host.getHost(0).getVM(0).invoke(() -> {
-      Cache cache = getCache();
-      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
-          .create(alterRegionName);
-    });
-
-    this.alterVm1 = Host.getHost(0).getVM(1);
-    this.alterVm1Name = "VM" + this.alterVm1.getPid();
-    this.alterVm1.invoke(() -> {
-      Properties localProps = new Properties();
-      localProps.setProperty(NAME, alterVm1Name);
-      localProps.setProperty(GROUPS, "Group1");
-      getSystem(localProps);
-      Cache cache = getCache();
-
-      // Setup queues and gateway senders to be used by all tests
-      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
-          .create(alterRegionName);
-    });
-
-    this.alterVm2 = Host.getHost(0).getVM(2);
-    this.alterVm2Name = "VM" + this.alterVm2.getPid();
-    this.alterVm2.invoke(() -> {
-      Properties localProps = new Properties();
-      localProps.setProperty(NAME, alterVm2Name);
-      localProps.setProperty(GROUPS, "Group1,Group2");
-      getSystem(localProps);
-      Cache cache = getCache();
-
-      cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
-          .create(alterRegionName);
-    });
-
-    deployJarFilesForRegionAlter();
-
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
-        "com.cadrdunit.RegionAlterCacheListenerA,com.cadrdunit.RegionAlterCacheListenerB,com.cadrdunit.RegionAlterCacheListenerC");
-
-    cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    String stringResult = commandResultToString(cmdResult);
-
-    assertEquals(5, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm1.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(3, attributes.getCacheListeners().length);
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
-          attributes.getCacheListeners()[0].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
-          attributes.getCacheListeners()[1].getClass().getName());
-      assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
-          attributes.getCacheListeners()[2].getClass().getName());
-    });
-
-    // Add 1 back to each of the sets
-    commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
-    commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
-    commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER, "''");
-    cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-    stringResult = commandResultToString(cmdResult);
-    assertEquals(4, countLinesInString(stringResult, false));
-    assertEquals(false, stringResult.contains("ERROR"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-    assertTrue(stringContainsLine(stringResult,
-        this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
-    this.alterVm1.invoke(() -> {
-      RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
-      assertEquals(0, attributes.getCacheListeners().length);
-    });
-  }
-
   /**
    * Asserts that creating, altering and destroying regions correctly updates the shared
    * configuration.
@@ -969,7 +117,6 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
       jmxHost = "localhost";
     }
 
-
     final String regionName = "testRegionSharedConfigRegion";
     final String regionPath = "/" + regionName;
     final String groupName = "testRegionSharedConfigGroup";
@@ -994,7 +141,7 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
         final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locatorPort,
             locatorLogFile, null, locatorProps);
 
-        waitAtMost(5, TimeUnit.SECONDS).until(() -> locator.isSharedConfigurationRunning());
+        waitAtMost(5, TimeUnit.SECONDS).until(locator::isSharedConfigurationRunning);
 
         ManagementService managementService =
             ManagementService.getExistingManagementService(GemFireCacheImpl.getInstance());
@@ -1030,7 +177,7 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
     assertEquals(Result.Status.OK, cmdResult.getStatus());
 
     // Make sure that the region has been registered with the Manager MXBean
-    waitForRegionMBeanCreation(regionPath, 1);
+    waitForRegionMBeanCreation(regionPath);
 
     // Make sure the region exists in the shared config
     Host.getHost(0).getVM(0).invoke(() -> {
@@ -1109,251 +256,8 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
         return null;
       }
     });
-
-  }
-
-  @Test
-  public void testDestroyRegionWithSharedConfig() {
-    disconnectAllFromDS();
-
-    final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
-    jmxPort = ports[0];
-    httpPort = ports[1];
-    try {
-      jmxHost = InetAddress.getLocalHost().getHostName();
-    } catch (UnknownHostException ignore) {
-      jmxHost = "localhost";
-    }
-
-
-    final String regionName = "testRegionSharedConfigRegion";
-    final String regionPath = "/" + regionName;
-    final String groupName = "testRegionSharedConfigGroup";
-
-    // Start the Locator and wait for shared configuration to be available
-    final int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-
-    final Properties locatorProps = new Properties();
-    locatorProps.setProperty(NAME, "Locator");
-    locatorProps.setProperty(MCAST_PORT, "0");
-    locatorProps.setProperty(LOG_LEVEL, "fine");
-    locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
-    locatorProps.setProperty(JMX_MANAGER, "true");
-    locatorProps.setProperty(JMX_MANAGER_START, "true");
-    locatorProps.setProperty(JMX_MANAGER_BIND_ADDRESS, String.valueOf(jmxHost));
-    locatorProps.setProperty(JMX_MANAGER_PORT, String.valueOf(jmxPort));
-    locatorProps.setProperty(HTTP_SERVICE_PORT, String.valueOf(httpPort));
-
-    Host.getHost(0).getVM(0).invoke(() -> {
-      final File locatorLogFile = new File("locator-" + locatorPort + ".log");
-      try {
-        final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locatorPort,
-            locatorLogFile, null, locatorProps);
-
-        waitAtMost(5, TimeUnit.SECONDS).until(() -> locator.isSharedConfigurationRunning());
-      } catch (IOException ioex) {
-        fail("Unable to create a locator with a shared configuration");
-      }
-    });
-
-    connect(jmxHost, jmxPort, httpPort, getDefaultShell());
-
-    // Create a cache in VM 1
-    VM vm = Host.getHost(0).getVM(1);
-    vm.invoke(() -> {
-      Properties localProps = new Properties();
-      localProps.setProperty(MCAST_PORT, "0");
-      localProps.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
-      localProps.setProperty(GROUPS, groupName);
-      getSystem(localProps);
-      assertNotNull(getCache());
-    });
-
-    // Test creating the region
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, regionName);
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__STATISTICSENABLED, "true");
-    commandStringBuilder.addOption(CliStrings.GROUP, groupName);
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    // Make sure that the region has been registered with the Manager MXBean
-    waitForRegionMBeanCreation(regionPath, 1);
-
-    // Make sure the region exists in the shared config
-    Host.getHost(0).getVM(0).invoke(() -> {
-      ClusterConfigurationService sharedConfig =
-          ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
-      try {
-        assertTrue(
-            sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
-      } catch (Exception e) {
-        fail("Error occurred in cluster configuration service");
-      }
-    });
-
-    // Test destroying the region
-    commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
-    commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, regionName);
-    cmdResult = executeCommand(commandStringBuilder.toString());
-    getLogWriter().info("#SB" + commandResultToString(cmdResult));
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    // Make sure the region was removed from the shared config
-    Host.getHost(0).getVM(0).invoke(() -> {
-      ClusterConfigurationService sharedConfig =
-          ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
-      try {
-        assertFalse(
-            sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
-      } catch (Exception e) {
-        fail("Error occurred in cluster configuration service");
-      }
-    });
-
-
-    // Restart the data vm to make sure the region is not existing any more
-    vm = Host.getHost(0).getVM(1);
-    vm.invoke(() -> {
-      Cache cache = getCache();
-      assertNotNull(cache);
-      cache.close();
-      assertTrue(cache.isClosed());
-
-      Properties localProps = new Properties();
-      localProps.setProperty(MCAST_PORT, "0");
-      localProps.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
-      localProps.setProperty(GROUPS, groupName);
-      localProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
-      getSystem(localProps);
-      cache = getCache();
-      assertNotNull(cache);
-      Region region = cache.getRegion(regionName);
-      assertNull(region);
-
-      return null;
-    });
   }
 
-
-  final String PR_STRING = " package com.cadrdunit;"
-      + " public class TestPartitionResolver implements org.apache.geode.cache.PartitionResolver { "
-      + "   @Override" + "   public void close() {" + "   }" + "   @Override"
-      + "   public Object getRoutingObject(org.apache.geode.cache.EntryOperation opDetails) { "
-      + "    return null; " + "   }" + "   @Override" + "   public String getName() { "
-      + "    return \"TestPartitionResolver\";" + "   }" + " }";
-
-  /**
-   * Test Description 1. Deploy a JAR with Custom Partition Resolver 2. Create Region with Partition
-   * Resolver 3. Region should get created with no Errors 4. Verify Region Partition Attributes for
-   * Partition Resolver
-   */
-  @Test
-  public void testCreateRegionWithPartitionResolver() throws IOException {
-    setUpJmxManagerOnVm0ThenConnect(null);
-    VM vm = Host.getHost(0).getVM(1);
-    // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
-
-    ClassBuilder classBuilder = new ClassBuilder();
-    // classBuilder.addToClassPath(".");
-    final File prJarFile = new File(temporaryFolder.getRoot().getCanonicalPath() + File.separator,
-        "myPartitionResolver.jar");
-    this.filesToBeDeleted.add(prJarFile.getAbsolutePath());
-    byte[] jarBytes =
-        classBuilder.createJarFromClassContent("com/cadrdunit/TestPartitionResolver", PR_STRING);
-    writeJarBytesToFile(prJarFile, jarBytes);
-
-    CommandResult cmdResult = executeCommand("deploy --jar=" + prJarFile.getAbsolutePath());
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-
-    // Create a region with an unrecognized compressor
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "regionWithPartitionResolver");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER,
-        "com.cadrdunit.TestPartitionResolver");
-    CommandResult cmdResult1 = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.OK, cmdResult1.getStatus());
-
-    // Assert that our region was not created
-    vm.invoke(() -> {
-      Region region = getCache().getRegion("regionWithPartitionResolver");
-      assertNotNull(region);
-
-      PartitionedRegion pr = (PartitionedRegion) region;
-      PartitionAttributes partitionAttributes = pr.getPartitionAttributes();
-      assertNotNull(partitionAttributes);
-      PartitionResolver partitionResolver = partitionAttributes.getPartitionResolver();
-      assertNotNull(partitionResolver);
-      assertEquals("TestPartitionResolver", partitionResolver.getName());
-    });
-
-    vm.invoke(() -> {
-      getCache().getRegion("regionWithPartitionResolver").destroyRegion();
-    });
-  }
-
-  @Test
-  public void testCreateRegionWithInvalidPartitionResolver() {
-    setUpJmxManagerOnVm0ThenConnect(null);
-    VM vm = Host.getHost(0).getVM(1);
-    // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
-
-    // Create a region with an unrecognized compressor
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION,
-        "testCreateRegionWithInvalidPartitionResolver");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER, "a.b.c.d");
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
-    // Assert that our region was not created
-    vm.invoke(() -> {
-      Region region = getCache().getRegion("testCreateRegionWithInvalidPartitionResolver");
-      assertNull(region);
-    });
-  }
-
-  /**
-   * Test Description Try creating region of type REPLICATED and specify partition resolver Region
-   * Creation should fail.
-   */
-  @Test
-  public void testCreateRegionForReplicatedRegionWithParitionResolver() {
-    setUpJmxManagerOnVm0ThenConnect(null);
-    VM vm = Host.getHost(0).getVM(1);
-    // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
-
-    // Create a region with an unrecognized compressor
-    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION,
-        "testCreateRegionForReplicatedRegionWithParitionResolver");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
-    commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER, "a.b.c.d");
-    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
-    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
-    // Assert that our region was not created
-    vm.invoke(() -> {
-      Region region =
-          getCache().getRegion("testCreateRegionForReplicatedRegionWithParitionResolver");
-      assertNull(region);
-    });
-  }
-
-
   @Override
   protected final void preTearDownCliCommandTestBase() throws Exception {
     for (String path : this.filesToBeDeleted) {
@@ -1369,69 +273,4 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
     }
     this.filesToBeDeleted.clear();
   }
-
-  /**
-   * Deploys JAR files which contain classes to be instantiated by the "alter region" test.
-   */
-  private void deployJarFilesForRegionAlter() throws IOException {
-    ClassBuilder classBuilder = new ClassBuilder();
-    final File jarFile1 = new File(new File(".").getAbsolutePath(), "testAlterRegion1.jar");
-    this.filesToBeDeleted.add(jarFile1.getAbsolutePath());
-    final File jarFile2 = new File(new File(".").getAbsolutePath(), "testAlterRegion2.jar");
-    this.filesToBeDeleted.add(jarFile2.getAbsolutePath());
-    final File jarFile3 = new File(new File(".").getAbsolutePath(), "testAlterRegion3.jar");
-    this.filesToBeDeleted.add(jarFile3.getAbsolutePath());
-    final File jarFile4 = new File(new File(".").getAbsolutePath(), "testAlterRegion4.jar");
-    this.filesToBeDeleted.add(jarFile4.getAbsolutePath());
-    final File jarFile5 = new File(new File(".").getAbsolutePath(), "testAlterRegion5.jar");
-    this.filesToBeDeleted.add(jarFile5.getAbsolutePath());
-
-    byte[] jarBytes =
-        classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerA",
-            "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
-                + "public class RegionAlterCacheListenerA extends CacheListenerAdapter {}");
-    writeJarBytesToFile(jarFile1, jarBytes);
-    CommandResult cmdResult = executeCommand("deploy --jar=testAlterRegion1.jar");
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerB",
-        "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
-            + "public class RegionAlterCacheListenerB extends CacheListenerAdapter {}");
-    writeJarBytesToFile(jarFile2, jarBytes);
-    cmdResult = executeCommand("deploy --jar=testAlterRegion2.jar");
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerC",
-        "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
-            + "public class RegionAlterCacheListenerC extends CacheListenerAdapter {}");
-    writeJarBytesToFile(jarFile3, jarBytes);
-    cmdResult = executeCommand("deploy --jar=testAlterRegion3.jar");
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheLoader",
-        "package com.cadrdunit;" + "import org.apache.geode.cache.CacheLoader;"
-            + "import org.apache.geode.cache.CacheLoaderException;"
-            + "import org.apache.geode.cache.LoaderHelper;"
-            + "public class RegionAlterCacheLoader implements CacheLoader {"
-            + "public void close() {}"
-            + "public Object load(LoaderHelper helper) throws CacheLoaderException {return null;}}");
-    writeJarBytesToFile(jarFile4, jarBytes);
-    cmdResult = executeCommand("deploy --jar=testAlterRegion4.jar");
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-    jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheWriter",
-        "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheWriterAdapter;"
-            + "public class RegionAlterCacheWriter extends CacheWriterAdapter {}");
-    writeJarBytesToFile(jarFile5, jarBytes);
-    cmdResult = executeCommand("deploy --jar=testAlterRegion5.jar");
-    assertEquals(Result.Status.OK, cmdResult.getStatus());
-  }
-
-  private void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException {
-    final OutputStream outStream = new FileOutputStream(jarFile);
-    outStream.write(jarBytes);
-    outStream.flush();
-    outStream.close();
-  }
-
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
deleted file mode 100644
index 85b660d..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package org.apache.geode.management.internal.cli.commands;
-
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.mockito.Mockito;
-
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.test.dunit.rules.GfshParserRule;
-import org.apache.geode.test.junit.categories.IntegrationTest;
-
-@Category(IntegrationTest.class)
-public class CreateAlterDestroyRegionCommandsTest {
-
-  @Rule
-  public GfshParserRule parser = new GfshParserRule();
-
-  @Test
-  public void testCreateRegionWithInvalidPartitionResolver() throws Exception {
-    InternalCache cache = mock(InternalCache.class);
-    DistributedSystemMXBean dsMBean = mock(DistributedSystemMXBean.class);
-    CreateAlterDestroyRegionCommands spy = Mockito.spy(CreateAlterDestroyRegionCommands.class);
-
-    doReturn(cache).when(spy).getCache();
-    doReturn(dsMBean).when(spy).getDSMBean(cache);
-
-    String command = "create region --name=region3 --type=PARTITION --partition-resolver=Foo";
-
-    assertThatThrownBy(() -> parser.executeCommandWithInstance(spy, command))
-        .hasMessageContaining("Foo is an invalid Partition Resolver");
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
new file mode 100644
index 0000000..04168d5
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
@@ -0,0 +1,318 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.PartitionAttributes;
+import org.apache.geode.cache.PartitionResolver;
+import org.apache.geode.cache.Region;
+import org.apache.geode.compression.SnappyCompressor;
+import org.apache.geode.internal.ClassBuilder;
+import org.apache.geode.internal.cache.PartitionedRegion;
+import org.apache.geode.internal.cache.RegionEntryContext;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CommandResult;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
+
+@Category(DistributedTest.class)
+public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
+  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
+
+  /**
+   * Asserts that the "compressor" option for the "create region" command succeeds for a recognized
+   * compressor.
+   */
+  @Test
+  public void testCreateRegionWithGoodCompressor() {
+    setUpJmxManagerOnVm0ThenConnect(null);
+    VM vm = Host.getHost(0).getVM(1);
+
+    // Create a cache in vm 1
+    vm.invoke(() -> {
+      assertNotNull(getCache());
+    });
+
+    // Run create region command with compression
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "compressedRegion");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__COMPRESSOR,
+        RegionEntryContext.DEFAULT_COMPRESSION_PROVIDER);
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    // Make sure our region exists with compression enabled
+    vm.invoke(() -> {
+      Region region = getCache().getRegion("compressedRegion");
+      assertNotNull(region);
+      assertTrue(
+          SnappyCompressor.getDefaultInstance().equals(region.getAttributes().getCompressor()));
+    });
+
+    // cleanup
+    commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
+    commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, "compressedRegion");
+    cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+  }
+
+  /**
+   * Asserts that the "compressor" option for the "create region" command fails for an unrecognized
+   * compressorc.
+   */
+  @Test
+  public void testCreateRegionWithBadCompressor() {
+    setUpJmxManagerOnVm0ThenConnect(null);
+
+    VM vm = Host.getHost(0).getVM(1);
+
+    // Create a cache in vm 1
+    vm.invoke(() -> {
+      assertNotNull(getCache());
+    });
+
+    // Create a region with an unrecognized compressor
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "compressedRegion");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__COMPRESSOR, "BAD_COMPRESSOR");
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+    // Assert that our region was not created
+    vm.invoke(() -> {
+      Region region = getCache().getRegion("compressedRegion");
+      assertNull(region);
+    });
+  }
+
+  /**
+   * Asserts that a missing "compressor" option for the "create region" command results in a region
+   * with no compression.
+   */
+  @Test
+  public void testCreateRegionWithNoCompressor() {
+    setUpJmxManagerOnVm0ThenConnect(null);
+
+    VM vm = Host.getHost(0).getVM(1);
+
+    // Create a cache in vm 1
+    vm.invoke(() -> {
+      assertNotNull(getCache());
+    });
+
+    // Create a region with no compression
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "testRegion");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    // Assert that our newly created region has no compression
+    vm.invoke(() -> {
+      Region region = getCache().getRegion("testRegion");
+      assertNotNull(region);
+      assertNull(region.getAttributes().getCompressor());
+    });
+
+    // Cleanup
+    commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
+    commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, "testRegion");
+    cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+  }
+
+  @Category(FlakyTest.class) // GEODE-973: random ports, BindException,
+  // java.rmi.server.ExportException: Port already in use
+  @Test
+  public void testCreateRegion46391() throws IOException {
+    setUpJmxManagerOnVm0ThenConnect(null); // GEODE-973: getRandomAvailablePort
+    String region46391 = "region46391";
+    String command = CliStrings.CREATE_REGION + " --" + CliStrings.CREATE_REGION__REGION + "="
+        + region46391 + " --" + CliStrings.CREATE_REGION__REGIONSHORTCUT + "=REPLICATE";
+
+    getLogWriter().info("testCreateRegion46391 create region command=" + command);
+
+    CommandResult cmdResult = executeCommand(command);
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+    command = CliStrings.PUT + " --" + CliStrings.PUT__KEY + "=k1" + " --" + CliStrings.PUT__VALUE
+        + "=k1" + " --" + CliStrings.PUT__REGIONNAME + "=" + region46391;
+
+    getLogWriter().info("testCreateRegion46391 put command=" + command);
+
+    CommandResult cmdResult2 = executeCommand(command);
+    assertEquals(Result.Status.OK, cmdResult2.getStatus());
+
+    getLogWriter().info("testCreateRegion46391  cmdResult2=" + commandResultToString(cmdResult2));
+    String str1 = "Result      : true";
+    String str2 = "Key         : k1";
+    String str3 = "Key Class   : java.lang.String";
+    String str4 = "Value Class : java.lang.String";
+    String str5 = "Old Value   : <NULL>";
+
+    assertTrue(
+        commandResultToString(cmdResult).contains("Region \"/" + region46391 + "\" created on"));
+
+    assertTrue(commandResultToString(cmdResult2).contains(str1));
+    assertTrue(commandResultToString(cmdResult2).contains(str2));
+    assertTrue(commandResultToString(cmdResult2).contains(str3));
+    assertTrue(commandResultToString(cmdResult2).contains(str4));
+    assertTrue(commandResultToString(cmdResult2).contains(str5));
+  }
+
+  /**
+   * Test Description 1. Deploy a JAR with Custom Partition Resolver 2. Create Region with Partition
+   * Resolver 3. Region should get created with no Errors 4. Verify Region Partition Attributes for
+   * Partition Resolver
+   */
+  @Test
+  public void testCreateRegionWithPartitionResolver() throws IOException {
+    setUpJmxManagerOnVm0ThenConnect(null);
+    VM vm = Host.getHost(0).getVM(1);
+    // Create a cache in vm 1
+    vm.invoke(() -> {
+      assertNotNull(getCache());
+    });
+
+    ClassBuilder classBuilder = new ClassBuilder();
+    // classBuilder.addToClassPath(".");
+    final File prJarFile = new File(temporaryFolder.getRoot().getCanonicalPath() + File.separator,
+        "myPartitionResolver.jar");
+    this.filesToBeDeleted.add(prJarFile.getAbsolutePath());
+    String PR_STRING = " package com.cadrdunit;"
+        + " public class TestPartitionResolver implements org.apache.geode.cache.PartitionResolver { "
+        + "   @Override" + "   public void close() {" + "   }" + "   @Override"
+        + "   public Object getRoutingObject(org.apache.geode.cache.EntryOperation opDetails) { "
+        + "    return null; " + "   }" + "   @Override" + "   public String getName() { "
+        + "    return \"TestPartitionResolver\";" + "   }" + " }";
+    byte[] jarBytes =
+        classBuilder.createJarFromClassContent("com/cadrdunit/TestPartitionResolver", PR_STRING);
+    writeJarBytesToFile(prJarFile, jarBytes);
+
+    CommandResult cmdResult = executeCommand("deploy --jar=" + prJarFile.getAbsolutePath());
+    assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+
+    // Create a region with an unrecognized compressor
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "regionWithPartitionResolver");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER,
+        "com.cadrdunit.TestPartitionResolver");
+    CommandResult cmdResult1 = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.OK, cmdResult1.getStatus());
+
+    // Assert that our region was not created
+    vm.invoke(() -> {
+      Region region = getCache().getRegion("regionWithPartitionResolver");
+      assertNotNull(region);
+
+      PartitionedRegion pr = (PartitionedRegion) region;
+      PartitionAttributes partitionAttributes = pr.getPartitionAttributes();
+      assertNotNull(partitionAttributes);
+      PartitionResolver partitionResolver = partitionAttributes.getPartitionResolver();
+      assertNotNull(partitionResolver);
+      assertEquals("TestPartitionResolver", partitionResolver.getName());
+    });
+
+    vm.invoke(() -> {
+      getCache().getRegion("regionWithPartitionResolver").destroyRegion();
+    });
+  }
+
+  @Test
+  public void testCreateRegionWithInvalidPartitionResolver() {
+    setUpJmxManagerOnVm0ThenConnect(null);
+    VM vm = Host.getHost(0).getVM(1);
+    // Create a cache in vm 1
+    vm.invoke(() -> {
+      assertNotNull(getCache());
+    });
+
+    // Create a region with an unrecognized compressor
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION,
+        "testCreateRegionWithInvalidPartitionResolver");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER, "a.b.c.d");
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+    // Assert that our region was not created
+    vm.invoke(() -> {
+      Region region = getCache().getRegion("testCreateRegionWithInvalidPartitionResolver");
+      assertNull(region);
+    });
+  }
+
+  /**
+   * Test Description Try creating region of type REPLICATED and specify partition resolver Region
+   * Creation should fail.
+   */
+  @Test
+  public void testCreateRegionForReplicatedRegionWithParitionResolver() {
+    setUpJmxManagerOnVm0ThenConnect(null);
+    VM vm = Host.getHost(0).getVM(1);
+    // Create a cache in vm 1
+    vm.invoke(() -> {
+      assertNotNull(getCache());
+    });
+
+    // Create a region with an unrecognized compressor
+    CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION,
+        "testCreateRegionForReplicatedRegionWithParitionResolver");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+    commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER, "a.b.c.d");
+    CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+    assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+    // Assert that our region was not created
+    vm.invoke(() -> {
+      Region region =
+          getCache().getRegion("testCreateRegionForReplicatedRegionWithParitionResolver");
+      assertNull(region);
+    });
+  }
+
+  private void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException {
+    final OutputStream outStream = new FileOutputStream(jarFile);
+    outStream.write(jarBytes);
+    outStream.flush();
+    outStream.close();
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/0c124b77/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandTest.java
new file mode 100644
index 0000000..5011d78
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandTest.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.geode.management.internal.cli.commands.CreateRegionCommand.regionExists;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.mockito.Mockito;
+
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.test.dunit.rules.GfshParserRule;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+
+@Category(IntegrationTest.class)
+public class CreateRegionCommandTest {
+  @Rule
+  public GfshParserRule parser = new GfshParserRule();
+
+  @Test
+  public void testCreateRegionWithInvalidPartitionResolver() throws Exception {
+    InternalCache cache = mock(InternalCache.class);
+    DistributedSystemMXBean dsMBean = mock(DistributedSystemMXBean.class);
+    CreateRegionCommand spy = Mockito.spy(CreateRegionCommand.class);
+
+    doReturn(cache).when(spy).getCache();
+    doReturn(dsMBean).when(spy).getDSMBean(cache);
+
+    String command = "create region --name=region3 --type=PARTITION --partition-resolver=Foo";
+    assertThatThrownBy(() -> parser.executeCommandWithInstance(spy, command))
+        .hasMessageContaining("Foo is an invalid Partition Resolver");
+  }
+
+  @Test
+  public void testRegionExistsReturnsCorrectValue() throws Exception {
+    InternalCache cache = mock(InternalCache.class);
+    assertThat(regionExists(cache, null)).isFalse();
+  }
+}


[31/47] geode git commit: Define acceptanceTest task for all submodules

Posted by ds...@apache.org.
Define acceptanceTest task for all submodules

- This allows combineReports to be finalizedBy acceptanceTest (thus
  html report is generated correctly).

Signed-off-by: Dick Cavender <dc...@pivotal.io>


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

Branch: refs/heads/feature/GEODE-3543
Commit: 4ac4600a1482a9b84acf6127c355da6a85b8afd0
Parents: 4ac5e65
Author: Jens Deppe <jd...@pivotal.io>
Authored: Tue Aug 29 12:40:20 2017 -0700
Committer: Dick Cavender <dc...@pivotal.io>
Committed: Tue Aug 29 12:40:20 2017 -0700

----------------------------------------------------------------------
 geode-assembly/build.gradle |  8 --------
 gradle/test.gradle          | 11 +++++++++--
 2 files changed, 9 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/4ac4600a/geode-assembly/build.gradle
----------------------------------------------------------------------
diff --git a/geode-assembly/build.gradle b/geode-assembly/build.gradle
index e135675..1f0c12a 100755
--- a/geode-assembly/build.gradle
+++ b/geode-assembly/build.gradle
@@ -106,14 +106,6 @@ sourceSets {
   //test.runtimeClasspath -= configurations.provided
 }
 
-task acceptanceTest(type:Test) {
-  useJUnit {
-    includeCategories 'org.apache.geode.test.junit.categories.AcceptanceTest'
-  }
-  forkEvery 1
-}
-
-
 test {
   // test from the actual classpath not the gradle classpath
   dependsOn installDist

http://git-wip-us.apache.org/repos/asf/geode/blob/4ac4600a/gradle/test.gradle
----------------------------------------------------------------------
diff --git a/gradle/test.gradle b/gradle/test.gradle
index 1b92a52..d321f28 100644
--- a/gradle/test.gradle
+++ b/gradle/test.gradle
@@ -220,6 +220,13 @@ subprojects {
     forkEvery 30
   }
 
+  task acceptanceTest(type:Test) {
+    useJUnit {
+      includeCategories 'org.apache.geode.test.junit.categories.AcceptanceTest'
+    }
+    forkEvery 1
+  }
+
   // apply common test configuration
   gradle.taskGraph.whenReady( { graph ->
     tasks.withType(Test).each { test ->
@@ -281,6 +288,6 @@ subprojects {
 
   check.dependsOn checkMissedTests
 
-  combineReports.mustRunAfter check, test, ":geode-assembly:acceptanceTest", integrationTest, distributedTest, flakyTest, checkMissedTests
-  [build, check, test, integrationTest, distributedTest, flakyTest, checkMissedTests].each {it.finalizedBy combineReports}
+  combineReports.mustRunAfter check, test, integrationTest, distributedTest, flakyTest, checkMissedTests, acceptanceTest
+  [build, check, test, integrationTest, distributedTest, flakyTest, checkMissedTests, acceptanceTest].each {it.finalizedBy combineReports}
 }


[18/47] geode git commit: GEODE-3436: Restore refactoring of Refactoring MiscellaneousCommands

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/NetstatCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/NetstatCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/NetstatCommand.java
new file mode 100644
index 0000000..a5d62fa
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/NetstatCommand.java
@@ -0,0 +1,212 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.zip.DataFormatException;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParser;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.NetstatFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class NetstatCommand implements GfshCommand {
+  private static final String NETSTAT_FILE_REQUIRED_EXTENSION = ".txt";
+
+  @CliCommand(value = CliStrings.NETSTAT, help = CliStrings.NETSTAT__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  // TODO : Verify the auto-completion for multiple values.
+  public Result netstat(
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+          help = CliStrings.NETSTAT__MEMBER__HELP) String[] members,
+      @CliOption(key = CliStrings.GROUP, optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.NETSTAT__GROUP__HELP) String group,
+      @CliOption(key = CliStrings.NETSTAT__FILE,
+          help = CliStrings.NETSTAT__FILE__HELP) String saveAs,
+      @CliOption(key = CliStrings.NETSTAT__WITHLSOF, specifiedDefaultValue = "true",
+          unspecifiedDefaultValue = "false",
+          help = CliStrings.NETSTAT__WITHLSOF__HELP) boolean withlsof) {
+    Result result;
+
+    Map<String, DistributedMember> hostMemberMap = new HashMap<>();
+    Map<String, List<String>> hostMemberListMap = new HashMap<>();
+
+    try {
+      if (members != null && members.length > 0 && group != null) {
+        throw new IllegalArgumentException(
+            CliStrings.NETSTAT__MSG__ONLY_ONE_OF_MEMBER_OR_GROUP_SHOULD_BE_SPECIFIED);
+      }
+      StringBuilder resultInfo = new StringBuilder();
+
+      // Execute for remote members whose id or name matches
+      InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
+
+      if (members != null) {
+        Set<String> notFoundMembers = new HashSet<>();
+        for (String memberIdOrName : members) {
+          Set<DistributedMember> membersToExecuteOn = CliUtil.getAllMembers(system);
+          boolean memberFound = false;
+          for (DistributedMember distributedMember : membersToExecuteOn) {
+            String memberName = distributedMember.getName();
+            String memberId = distributedMember.getId();
+            if (memberName.equals(memberIdOrName) || memberId.equals(memberIdOrName)) {
+              buildMaps(hostMemberMap, hostMemberListMap, memberIdOrName, distributedMember);
+
+              memberFound = true;
+              break;
+            }
+          }
+          if (!memberFound) {
+            notFoundMembers.add(memberIdOrName);
+          }
+        }
+        // if there are not found members, it's probably unknown member or member has departed
+        if (!notFoundMembers.isEmpty()) {
+          throw new IllegalArgumentException(
+              CliStrings.format(CliStrings.NETSTAT__MSG__COULD_NOT_FIND_MEMBERS_0,
+                  new Object[] {CliUtil.collectionToString(notFoundMembers, -1)}));
+        }
+      } else {
+        Set<DistributedMember> membersToExecuteOn;
+        if (group != null) {
+          membersToExecuteOn = system.getGroupMembers(group);
+        } else {
+          // consider all members
+          membersToExecuteOn = CliUtil.getAllMembers(system);
+        }
+
+        for (DistributedMember distributedMember : membersToExecuteOn) {
+          String memberName = distributedMember.getName();
+          String memberId = distributedMember.getId();
+          String memberIdOrName =
+              memberName != null && !memberName.isEmpty() ? memberName : memberId;
+
+          buildMaps(hostMemberMap, hostMemberListMap, memberIdOrName, distributedMember);
+        }
+      }
+
+      String lineSeparatorToUse;
+      lineSeparatorToUse = CommandExecutionContext.getShellLineSeparator();
+      if (lineSeparatorToUse == null) {
+        lineSeparatorToUse = GfshParser.LINE_SEPARATOR;
+      }
+      NetstatFunction.NetstatFunctionArgument nfa =
+          new NetstatFunction.NetstatFunctionArgument(lineSeparatorToUse, withlsof);
+
+      if (!hostMemberMap.isEmpty()) {
+        Set<DistributedMember> membersToExecuteOn = new HashSet<>(hostMemberMap.values());
+        ResultCollector<?, ?> netstatResult =
+            CliUtil.executeFunction(NetstatFunction.INSTANCE, nfa, membersToExecuteOn);
+        List<?> resultList = (List<?>) netstatResult.getResult();
+        for (Object aResultList : resultList) {
+          NetstatFunction.NetstatFunctionResult netstatFunctionResult =
+              (NetstatFunction.NetstatFunctionResult) aResultList;
+          CliUtil.DeflaterInflaterData deflaterInflaterData =
+              netstatFunctionResult.getCompressedBytes();
+          try {
+            String remoteHost = netstatFunctionResult.getHost();
+            List<String> membersList = hostMemberListMap.get(remoteHost);
+            resultInfo.append(MessageFormat.format(netstatFunctionResult.getHeaderInfo(),
+                CliUtil.collectionToString(membersList, 120)));
+            CliUtil.DeflaterInflaterData uncompressedBytes = CliUtil.uncompressBytes(
+                deflaterInflaterData.getData(), deflaterInflaterData.getDataLength());
+            resultInfo.append(new String(uncompressedBytes.getData()));
+          } catch (DataFormatException e) {
+            resultInfo.append("Error in some data. Reason : ").append(e.getMessage());
+          }
+        }
+      }
+
+      InfoResultData resultData = ResultBuilder.createInfoResultData();
+      if (saveAs != null && !saveAs.isEmpty()) {
+        String saveToFile = saveAs;
+        if (!saveAs.endsWith(NETSTAT_FILE_REQUIRED_EXTENSION)) {
+          saveToFile = saveAs + NETSTAT_FILE_REQUIRED_EXTENSION;
+        }
+        resultData.addAsFile(saveToFile, resultInfo.toString(),
+            CliStrings.NETSTAT__MSG__SAVED_OUTPUT_IN_0, false); // Note: substitution for {0} will
+        // happen on client side.
+      } else {
+        resultData.addLine(resultInfo.toString());
+      }
+      result = ResultBuilder.buildResult(resultData);
+    } catch (IllegalArgumentException e) {
+      LogWrapper.getInstance()
+          .info(CliStrings.format(
+              CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
+              new Object[] {Arrays.toString(members)}));
+      result = ResultBuilder.createUserErrorResult(e.getMessage());
+    } catch (RuntimeException e) {
+      LogWrapper.getInstance()
+          .info(CliStrings.format(
+              CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
+              new Object[] {Arrays.toString(members)}), e);
+      result = ResultBuilder.createGemFireErrorResult(
+          CliStrings.format(CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
+              new Object[] {Arrays.toString(members)}));
+    } finally {
+      hostMemberMap.clear();
+      hostMemberListMap.clear();
+    }
+    return result;
+  }
+
+  private void buildMaps(Map<String, DistributedMember> hostMemberMap,
+      Map<String, List<String>> hostMemberListMap, String memberIdOrName,
+      DistributedMember distributedMember) {
+    String host = distributedMember.getHost();
+
+    // Maintain one member for a host - function execution purpose - once only for a host
+    if (!hostMemberMap.containsKey(host)) {
+      hostMemberMap.put(host, distributedMember);
+    }
+
+    // Maintain all members for a host - display purpose
+    List<String> list;
+    if (!hostMemberListMap.containsKey(host)) {
+      list = new ArrayList<>();
+      hostMemberListMap.put(host, list);
+    } else {
+      list = hostMemberListMap.get(host);
+    }
+    list.add(memberIdOrName);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockCommand.java
new file mode 100644
index 0000000..3b5fd78
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockCommand.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.text.MessageFormat;
+import java.util.Collection;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.deadlock.DeadlockDetector;
+import org.apache.geode.distributed.internal.deadlock.Dependency;
+import org.apache.geode.distributed.internal.deadlock.DependencyGraph;
+import org.apache.geode.distributed.internal.deadlock.GemFireDeadlockDetector;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ShowDeadlockCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.SHOW_DEADLOCK, help = CliStrings.SHOW_DEADLOCK__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result showDeadlock(@CliOption(key = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE,
+      help = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE__HELP,
+      mandatory = true) String filename) {
+
+    Result result;
+    try {
+      if (!filename.endsWith(".txt")) {
+        return ResultBuilder
+            .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".txt"));
+      }
+      InternalCache cache = getCache();
+
+      Set<DistributedMember> allMembers = CliUtil.getAllMembers(cache);
+      GemFireDeadlockDetector gfeDeadLockDetector = new GemFireDeadlockDetector(allMembers);
+      DependencyGraph dependencyGraph = gfeDeadLockDetector.find();
+      Collection<Dependency> deadlock = dependencyGraph.findCycle();
+      DependencyGraph deepest = null;
+      if (deadlock == null) {
+        deepest = dependencyGraph.findLongestCallChain();
+        if (deepest != null) {
+          deadlock = deepest.getEdges();
+        }
+      }
+      Set<Dependency> dependencies = (Set<Dependency>) dependencyGraph.getEdges();
+
+      InfoResultData resultData = ResultBuilder.createInfoResultData();
+
+      if (deadlock != null) {
+        if (deepest != null) {
+          resultData.addLine(CliStrings.SHOW_DEADLOCK__DEEPEST_FOUND);
+        } else {
+          resultData.addLine(CliStrings.SHOW_DEADLOCK__DEADLOCK__DETECTED);
+        }
+        resultData.addLine(DeadlockDetector.prettyFormat(deadlock));
+      } else {
+        resultData.addLine(CliStrings.SHOW_DEADLOCK__NO__DEADLOCK);
+      }
+      resultData.addAsFile(filename, DeadlockDetector.prettyFormat(dependencies),
+          MessageFormat.format(CliStrings.SHOW_DEADLOCK__DEPENDENCIES__REVIEW, filename), false);
+      result = ResultBuilder.buildResult(resultData);
+
+    } catch (Exception e) {
+      result = ResultBuilder
+          .createGemFireErrorResult(CliStrings.SHOW_DEADLOCK__ERROR + " : " + e.getMessage());
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowLogCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowLogCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowLogCommand.java
new file mode 100644
index 0000000..7780479
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowLogCommand.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import javax.management.ObjectName;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.MemberMXBean;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.ManagementConstants;
+import org.apache.geode.management.internal.SystemManagementService;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ShowLogCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.SHOW_LOG, help = CliStrings.SHOW_LOG_HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result showLog(
+      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+          help = CliStrings.SHOW_LOG_MEMBER_HELP, mandatory = true) String memberNameOrId,
+      @CliOption(key = CliStrings.SHOW_LOG_LINE_NUM, unspecifiedDefaultValue = "0",
+          help = CliStrings.SHOW_LOG_LINE_NUM_HELP) int numberOfLines) {
+    Result result;
+    try {
+      InternalCache cache = getCache();
+      SystemManagementService service =
+          (SystemManagementService) ManagementService.getExistingManagementService(cache);
+      MemberMXBean bean;
+      DistributedMember memberToBeInvoked = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+      if (memberToBeInvoked != null) {
+        String memberId = memberToBeInvoked.getId();
+
+        if (cache.getDistributedSystem().getDistributedMember().getId().equals(memberId)) {
+          bean = service.getMemberMXBean();
+        } else {
+          ObjectName objectName = service.getMemberMBeanName(memberToBeInvoked);
+          bean = service.getMBeanProxy(objectName, MemberMXBean.class);
+        }
+
+        if (numberOfLines > ManagementConstants.MAX_SHOW_LOG_LINES) {
+          numberOfLines = ManagementConstants.MAX_SHOW_LOG_LINES;
+        }
+        if (numberOfLines == 0 || numberOfLines < 0) {
+          numberOfLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES;
+        }
+        InfoResultData resultData = ResultBuilder.createInfoResultData();
+        if (bean != null) {
+          String log = bean.showLog(numberOfLines);
+          if (log != null) {
+            resultData.addLine(log);
+          } else {
+            resultData.addLine(CliStrings.SHOW_LOG_NO_LOG);
+          }
+        } else {
+          ErrorResultData errorResultData =
+              ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+                  .addLine(memberNameOrId + CliStrings.SHOW_LOG_MSG_MEMBER_NOT_FOUND);
+          return (ResultBuilder.buildResult(errorResultData));
+        }
+
+        result = ResultBuilder.buildResult(resultData);
+      } else {
+        ErrorResultData errorResultData =
+            ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+                .addLine(memberNameOrId + CliStrings.SHOW_LOG_MSG_MEMBER_NOT_FOUND);
+        return (ResultBuilder.buildResult(errorResultData));
+      }
+
+    } catch (Exception e) {
+      result = ResultBuilder
+          .createGemFireErrorResult(CliStrings.SHOW_LOG_ERROR + CliUtil.stackTraceAsString(e));
+    }
+    return result;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
new file mode 100644
index 0000000..7555a62
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
@@ -0,0 +1,1085 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import javax.management.ObjectName;
+
+import org.apache.logging.log4j.Logger;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.management.CacheServerMXBean;
+import org.apache.geode.management.DistributedRegionMXBean;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.JVMMetrics;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.MemberMXBean;
+import org.apache.geode.management.RegionMXBean;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.MBeanJMXAdapter;
+import org.apache.geode.management.internal.SystemManagementService;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.ResultData;
+import org.apache.geode.management.internal.cli.result.ResultDataException;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ShowMetricsCommand implements GfshCommand {
+  private final static Logger logger = LogService.getLogger();
+
+  @CliCommand(value = CliStrings.SHOW_METRICS, help = CliStrings.SHOW_METRICS__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_STATISTICS})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result showMetrics(
+      @CliOption(key = {CliStrings.MEMBER}, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+          help = CliStrings.SHOW_METRICS__MEMBER__HELP) String memberNameOrId,
+      @CliOption(key = {CliStrings.SHOW_METRICS__REGION}, optionContext = ConverterHint.REGION_PATH,
+          help = CliStrings.SHOW_METRICS__REGION__HELP) String regionName,
+      @CliOption(key = {CliStrings.SHOW_METRICS__FILE},
+          help = CliStrings.SHOW_METRICS__FILE__HELP) String export_to_report_to,
+      @CliOption(key = {CliStrings.SHOW_METRICS__CACHESERVER__PORT},
+          help = CliStrings.SHOW_METRICS__CACHESERVER__PORT__HELP) String cacheServerPortString,
+      @CliOption(key = {CliStrings.SHOW_METRICS__CATEGORY},
+          help = CliStrings.SHOW_METRICS__CATEGORY__HELP) String[] categories) {
+
+    Result result;
+    try {
+
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        if (!export_to_report_to.endsWith(".csv")) {
+          return ResultBuilder
+              .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".csv"));
+        }
+      }
+      if (regionName != null && !regionName.isEmpty()) {
+
+        if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
+          return ResultBuilder
+              .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
+        }
+
+        // MBean names contain the forward slash
+        if (!regionName.startsWith("/")) {
+          regionName = "/" + regionName;
+        }
+
+        if (memberNameOrId == null || memberNameOrId.isEmpty()) {
+          result = ResultBuilder.buildResult(
+              getDistributedRegionMetrics(regionName, export_to_report_to, categories));
+        } else {
+          DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+
+          if (member != null) {
+            result = ResultBuilder.buildResult(
+                getRegionMetricsFromMember(regionName, member, export_to_report_to, categories));
+          } else {
+            ErrorResultData erd = ResultBuilder.createErrorResultData();
+            erd.addLine(
+                CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId));
+            result = ResultBuilder.buildResult(erd);
+          }
+        }
+      } else if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
+
+        DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+
+        if (member != null) {
+          int cacheServerPort = -1;
+          if (cacheServerPortString != null && !cacheServerPortString.isEmpty()) {
+            try {
+              cacheServerPort = Integer.parseInt(cacheServerPortString);
+            } catch (NumberFormatException nfe) {
+              return ResultBuilder.createUserErrorResult("Invalid port");
+            }
+          }
+          result = ResultBuilder.buildResult(
+              getMemberMetrics(member, export_to_report_to, categories, cacheServerPort));
+        } else {
+          ErrorResultData erd = ResultBuilder.createErrorResultData();
+          erd.addLine(CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId));
+          result = ResultBuilder.buildResult(erd);
+        }
+      } else {
+        if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
+          return ResultBuilder
+              .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
+        }
+        result = ResultBuilder.buildResult(getSystemWideMetrics(export_to_report_to, categories));
+      }
+    } catch (Exception e) {
+      logger.error(e.getMessage(), e);
+      return ResultBuilder.createGemFireErrorResult(CliUtil.stackTraceAsString(e));
+    }
+    return result;
+  }
+
+  /**
+   * Gets the system wide metrics
+   *
+   * @return ResultData with required System wide statistics or ErrorResultData if DS MBean is not
+   *         found to gather metrics
+   */
+  private ResultData getSystemWideMetrics(String export_to_report_to, String[] categoriesArr) {
+    final InternalCache cache = getCache();
+    final ManagementService managementService = ManagementService.getManagementService(cache);
+    DistributedSystemMXBean dsMxBean = managementService.getDistributedSystemMXBean();
+    StringBuilder csvBuilder = null;
+    if (dsMxBean != null) {
+
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        csvBuilder = new StringBuilder();
+        csvBuilder.append("Category");
+        csvBuilder.append(',');
+        csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
+        csvBuilder.append(',');
+        csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
+        csvBuilder.append('\n');
+      }
+
+      CompositeResultData crd = ResultBuilder.createCompositeResultData();
+      CompositeResultData.SectionResultData section = crd.addSection();
+      TabularResultData metricsTable = section.addTable();
+      Map<String, Boolean> categoriesMap = getSystemMetricsCategories();
+
+      if (categoriesArr != null && categoriesArr.length != 0) {
+        Set<String> categories = createSet(categoriesArr);
+        Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
+        Set<String> userCategories = getSetDifference(categories, checkSet);
+
+        // Checking if the categories specified by the user are valid or not
+
+        if (userCategories.isEmpty()) {
+          for (String category : checkSet) {
+            categoriesMap.put(category, false);
+          }
+          for (String category : categories) {
+            categoriesMap.put(category.toLowerCase(), true);
+          }
+        } else {
+          StringBuilder sb = new StringBuilder();
+          sb.append("Invalid Categories\n");
+
+          for (String category : userCategories) {
+            sb.append(category);
+            sb.append('\n');
+          }
+          return ResultBuilder.createErrorResultData().addLine(sb.toString());
+        }
+      }
+      metricsTable.setHeader("Cluster-wide Metrics");
+
+      if (categoriesMap.get("cluster")) {
+        writeToTableAndCsv(metricsTable, "cluster", "totalHeapSize", dsMxBean.getTotalHeapSize(),
+            csvBuilder);
+      }
+
+      if (categoriesMap.get("cache")) {
+        writeToTableAndCsv(metricsTable, "cache", "totalRegionEntryCount",
+            dsMxBean.getTotalRegionEntryCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalRegionCount", dsMxBean.getTotalRegionCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalMissCount", dsMxBean.getTotalMissCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalHitCount", dsMxBean.getTotalHitCount(),
+            csvBuilder);
+      }
+
+      if (categoriesMap.get("diskstore")) {
+        writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
+            dsMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
+        writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
+            dsMxBean.getDiskReadsRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "diskWritesRate", dsMxBean.getDiskWritesRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "flushTimeAvgLatency",
+            dsMxBean.getDiskFlushAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalBackupInProgress",
+            dsMxBean.getTotalBackupInProgress(), csvBuilder);
+      }
+
+      if (categoriesMap.get("query")) {
+        writeToTableAndCsv(metricsTable, "query", "activeCQCount", dsMxBean.getActiveCQCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "queryRequestRate", dsMxBean.getQueryRequestRate(),
+            csvBuilder);
+      }
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        crd.addAsFile(export_to_report_to, csvBuilder.toString(),
+            "Cluster wide metrics exported to {0}.", false);
+      }
+
+      return crd;
+    } else {
+      String errorMessage =
+          CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Distributed System MBean not found");
+      return ResultBuilder.createErrorResultData().addLine(errorMessage);
+    }
+  }
+
+  /**
+   * Gets the Cluster wide metrics for a given member
+   *
+   * @return ResultData with required Member statistics or ErrorResultData if MemberMbean is not
+   *         found to gather metrics
+   * @throws ResultDataException if building result fails
+   */
+  private ResultData getMemberMetrics(DistributedMember distributedMember,
+      String export_to_report_to, String[] categoriesArr, int cacheServerPort)
+      throws ResultDataException {
+    final InternalCache cache = getCache();
+    final SystemManagementService managementService =
+        (SystemManagementService) ManagementService.getManagementService(cache);
+
+    ObjectName memberMBeanName = managementService.getMemberMBeanName(distributedMember);
+    MemberMXBean memberMxBean =
+        managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
+    ObjectName csMxBeanName;
+    CacheServerMXBean csMxBean = null;
+
+    if (memberMxBean != null) {
+
+      if (cacheServerPort != -1) {
+        csMxBeanName =
+            managementService.getCacheServerMBeanName(cacheServerPort, distributedMember);
+        csMxBean = managementService.getMBeanInstance(csMxBeanName, CacheServerMXBean.class);
+
+        if (csMxBean == null) {
+          ErrorResultData erd = ResultBuilder.createErrorResultData();
+          erd.addLine(CliStrings.format(CliStrings.SHOW_METRICS__CACHE__SERVER__NOT__FOUND,
+              cacheServerPort, MBeanJMXAdapter.getMemberNameOrId(distributedMember)));
+          return erd;
+        }
+      }
+
+      JVMMetrics jvmMetrics = memberMxBean.showJVMMetrics();
+
+      CompositeResultData crd = ResultBuilder.createCompositeResultData();
+      CompositeResultData.SectionResultData section = crd.addSection();
+      TabularResultData metricsTable = section.addTable();
+      metricsTable.setHeader("Member Metrics");
+      StringBuilder csvBuilder = null;
+
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        csvBuilder = new StringBuilder();
+        csvBuilder.append("Category");
+        csvBuilder.append(',');
+        csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
+        csvBuilder.append(',');
+        csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
+        csvBuilder.append('\n');
+      }
+
+      Map<String, Boolean> categoriesMap = getMemberMetricsCategories();
+
+      if (categoriesArr != null && categoriesArr.length != 0) {
+        Set<String> categories = createSet(categoriesArr);
+        Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
+        Set<String> userCategories = getSetDifference(categories, checkSet);
+
+        // Checking if the categories specified by the user are valid or not
+        if (userCategories.isEmpty()) {
+          for (String category : checkSet) {
+            categoriesMap.put(category, false);
+          }
+          for (String category : categories) {
+            categoriesMap.put(category.toLowerCase(), true);
+          }
+        } else {
+          StringBuilder sb = new StringBuilder();
+          sb.append("Invalid Categories\n");
+
+          for (String category : userCategories) {
+            sb.append(category);
+            sb.append('\n');
+          }
+          return ResultBuilder.createErrorResultData().addLine(sb.toString());
+        }
+      }
+
+      /*
+       * Member Metrics
+       */
+      // member, jvm, region, serialization, communication, function, transaction, diskstore, lock,
+      // eviction, distribution
+      if (categoriesMap.get("member")) {
+        writeToTableAndCsv(metricsTable, "member", "upTime", memberMxBean.getMemberUpTime(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "cpuUsage", memberMxBean.getCpuUsage(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "currentHeapSize", memberMxBean.getCurrentHeapSize(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "maximumHeapSize", memberMxBean.getMaximumHeapSize(),
+            csvBuilder);
+      }
+      /*
+       * JVM Metrics
+       */
+      if (categoriesMap.get("jvm")) {
+        writeToTableAndCsv(metricsTable, "jvm ", "jvmThreads ", jvmMetrics.getTotalThreads(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "fileDescriptorLimit",
+            memberMxBean.getFileDescriptorLimit(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalFileDescriptorOpen",
+            memberMxBean.getTotalFileDescriptorOpen(), csvBuilder);
+      }
+      /*
+       * Member wide region metrics
+       */
+      if (categoriesMap.get("region")) {
+        writeToTableAndCsv(metricsTable, "region ", "totalRegionCount ",
+            memberMxBean.getTotalRegionCount(), csvBuilder);
+        String[] regionNames = memberMxBean.listRegions();
+        if (regionNames != null) {
+          for (int i = 0; i < regionNames.length; i++) {
+            if (i == 0) {
+              writeToTableAndCsv(metricsTable, "listOfRegions", regionNames[i].substring(1),
+                  csvBuilder);
+            } else {
+              writeToTableAndCsv(metricsTable, "", regionNames[i].substring(1), csvBuilder);
+            }
+          }
+        }
+
+        String[] rootRegionNames = memberMxBean.getRootRegionNames();
+        if (rootRegionNames != null) {
+          for (int i = 0; i < rootRegionNames.length; i++) {
+            if (i == 0) {
+              writeToTableAndCsv(metricsTable, "rootRegions", rootRegionNames[i], csvBuilder);
+            } else {
+              writeToTableAndCsv(metricsTable, "", rootRegionNames[i], csvBuilder);
+            }
+          }
+        }
+        writeToTableAndCsv(metricsTable, "", "totalRegionEntryCount",
+            memberMxBean.getTotalRegionEntryCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalBucketCount", memberMxBean.getTotalBucketCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalPrimaryBucketCount",
+            memberMxBean.getTotalPrimaryBucketCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "getsAvgLatency", memberMxBean.getGetsAvgLatency(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putsAvgLatency", memberMxBean.getPutsAvgLatency(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "createsRate", memberMxBean.getCreatesRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "destroyRate", memberMxBean.getDestroysRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putAllAvgLatency", memberMxBean.getPutAllAvgLatency(),
+            csvBuilder);
+        // Not available from stats. After Stats re-org it will be available
+        // writeToTableAndCsv(metricsTable, "", "getAllAvgLatency",
+        // memberMxBean.getGetAllAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalMissCount", memberMxBean.getTotalMissCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalHitCount", memberMxBean.getTotalHitCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "getsRate", memberMxBean.getGetsRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putsRate", memberMxBean.getPutsRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "cacheWriterCallsAvgLatency",
+            memberMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
+            memberMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalLoadsCompleted",
+            memberMxBean.getTotalLoadsCompleted(), csvBuilder);
+      }
+
+      /*
+       * SERIALIZATION
+       */
+      if (categoriesMap.get("serialization")) {
+        writeToTableAndCsv(metricsTable, "serialization", "serializationRate",
+            memberMxBean.getSerializationRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "serializationLatency",
+            memberMxBean.getSerializationRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "deserializationRate",
+            memberMxBean.getDeserializationRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "deserializationLatency",
+            memberMxBean.getDeserializationLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "deserializationAvgLatency",
+            memberMxBean.getDeserializationAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "PDXDeserializationAvgLatency",
+            memberMxBean.getPDXDeserializationAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "PDXDeserializationRate",
+            memberMxBean.getPDXDeserializationRate(), csvBuilder);
+      }
+
+      /*
+       * Communication Metrics
+       */
+      if (categoriesMap.get("communication")) {
+        writeToTableAndCsv(metricsTable, "communication", "bytesSentRate",
+            memberMxBean.getBytesSentRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "bytesReceivedRate",
+            memberMxBean.getBytesReceivedRate(), csvBuilder);
+        String[] connectedGatewayReceivers = memberMxBean.listConnectedGatewayReceivers();
+        writeToTableAndCsv(metricsTable, "connectedGatewayReceivers", connectedGatewayReceivers,
+            csvBuilder);
+
+        String[] connectedGatewaySenders = memberMxBean.listConnectedGatewaySenders();
+        writeToTableAndCsv(metricsTable, "connectedGatewaySenders", connectedGatewaySenders,
+            csvBuilder);
+      }
+
+      /*
+       * Member wide function metrics
+       */
+      if (categoriesMap.get("function")) {
+        writeToTableAndCsv(metricsTable, "function", "numRunningFunctions",
+            memberMxBean.getNumRunningFunctions(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "functionExecutionRate",
+            memberMxBean.getFunctionExecutionRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "numRunningFunctionsHavingResults",
+            memberMxBean.getNumRunningFunctionsHavingResults(), csvBuilder);
+      }
+
+      /*
+       * totalTransactionsCount currentTransactionalThreadIds transactionCommitsAvgLatency
+       * transactionCommittedTotalCount transactionRolledBackTotalCount transactionCommitsRate
+       */
+      if (categoriesMap.get("transaction")) {
+        writeToTableAndCsv(metricsTable, "transaction", "totalTransactionsCount",
+            memberMxBean.getTotalTransactionsCount(), csvBuilder);
+
+        writeToTableAndCsv(metricsTable, "", "transactionCommitsAvgLatency",
+            memberMxBean.getTransactionCommitsAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "transactionCommittedTotalCount",
+            memberMxBean.getTransactionCommittedTotalCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "transactionRolledBackTotalCount",
+            memberMxBean.getTransactionRolledBackTotalCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "transactionCommitsRate",
+            memberMxBean.getTransactionCommitsRate(), csvBuilder);
+      }
+      /*
+       * Member wide disk metrics
+       */
+      if (categoriesMap.get("diskstore")) {
+        writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
+            memberMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
+        writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
+            memberMxBean.getDiskReadsRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "diskWritesRate", memberMxBean.getDiskWritesRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "flushTimeAvgLatency",
+            memberMxBean.getDiskFlushAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalQueueSize",
+            memberMxBean.getTotalDiskTasksWaiting(), csvBuilder); // deadcoded to workaround bug
+        // 46397
+        writeToTableAndCsv(metricsTable, "", "totalBackupInProgress",
+            memberMxBean.getTotalBackupInProgress(), csvBuilder);
+      }
+      /*
+       * Member wide Lock
+       */
+      if (categoriesMap.get("lock")) {
+        writeToTableAndCsv(metricsTable, "lock", "lockWaitsInProgress",
+            memberMxBean.getLockWaitsInProgress(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalLockWaitTime",
+            memberMxBean.getTotalLockWaitTime(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalNumberOfLockService",
+            memberMxBean.getTotalNumberOfLockService(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "requestQueues", memberMxBean.getLockRequestQueues(),
+            csvBuilder);
+      }
+      /*
+       * Eviction
+       */
+      if (categoriesMap.get("eviction")) {
+        writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
+            memberMxBean.getLruEvictionRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "lruDestroyRate", memberMxBean.getLruDestroyRate(),
+            csvBuilder);
+      }
+      /*
+       * Distribution
+       */
+      if (categoriesMap.get("distribution")) {
+        writeToTableAndCsv(metricsTable, "distribution", "getInitialImagesInProgress",
+            memberMxBean.getInitialImagesInProgress(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "getInitialImageTime",
+            memberMxBean.getInitialImageTime(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "getInitialImageKeysReceived",
+            memberMxBean.getInitialImageKeysReceived(), csvBuilder);
+      }
+
+      /*
+       * OffHeap
+       */
+      if (categoriesMap.get("offheap")) {
+        writeToTableAndCsv(metricsTable, "offheap", "maxMemory", memberMxBean.getOffHeapMaxMemory(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "freeMemory", memberMxBean.getOffHeapFreeMemory(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "usedMemory", memberMxBean.getOffHeapUsedMemory(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "objects", memberMxBean.getOffHeapObjects(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "fragmentation",
+            memberMxBean.getOffHeapFragmentation(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "compactionTime",
+            memberMxBean.getOffHeapCompactionTime(), csvBuilder);
+      }
+
+      /*
+       * CacheServer stats
+       */
+      if (csMxBean != null) {
+        writeToTableAndCsv(metricsTable, "cache-server", "clientConnectionCount",
+            csMxBean.getClientConnectionCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "hostnameForClients", csMxBean.getHostNameForClients(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "getRequestAvgLatency",
+            csMxBean.getGetRequestAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putRequestAvgLatency",
+            csMxBean.getPutRequestAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalConnectionsTimedOut",
+            csMxBean.getTotalConnectionsTimedOut(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "threadQueueSize", csMxBean.getPutRequestAvgLatency(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "connectionThreads", csMxBean.getConnectionThreads(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "connectionLoad", csMxBean.getConnectionLoad(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "loadPerConnection", csMxBean.getLoadPerConnection(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "queueLoad", csMxBean.getQueueLoad(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "loadPerQueue", csMxBean.getLoadPerQueue(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "getRequestRate", csMxBean.getGetRequestRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putRequestRate", csMxBean.getPutRequestRate(),
+            csvBuilder);
+
+        /*
+         * Notification
+         */
+        writeToTableAndCsv(metricsTable, "notification", "numClientNotificationRequests",
+            csMxBean.getNumClientNotificationRequests(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "clientNotificationRate",
+            csMxBean.getClientNotificationRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "clientNotificationAvgLatency",
+            csMxBean.getClientNotificationAvgLatency(), csvBuilder);
+
+        /*
+         * Query
+         */
+        writeToTableAndCsv(metricsTable, "query", "activeCQCount", csMxBean.getActiveCQCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "query", "queryRequestRate",
+            csMxBean.getQueryRequestRate(), csvBuilder);
+
+        writeToTableAndCsv(metricsTable, "", "indexCount", csMxBean.getIndexCount(), csvBuilder);
+
+        String[] indexList = csMxBean.getIndexList();
+        writeToTableAndCsv(metricsTable, "index list", indexList, csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalIndexMaintenanceTime",
+            csMxBean.getTotalIndexMaintenanceTime(), csvBuilder);
+      }
+
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        crd.addAsFile(export_to_report_to, csvBuilder != null ? csvBuilder.toString() : null,
+            "Member metrics exported to {0}.", false);
+      }
+      return crd;
+
+    } else {
+      String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Member MBean for "
+          + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
+      return ResultBuilder.createErrorResultData().addLine(errorMessage);
+    }
+  }
+
+  /**
+   * Gets the Cluster-wide metrics for a region
+   *
+   * @return ResultData containing the table
+   * @throws ResultDataException if building result fails
+   */
+  private ResultData getDistributedRegionMetrics(String regionName, String export_to_report_to,
+      String[] categoriesArr) throws ResultDataException {
+
+    final InternalCache cache = getCache();
+    final ManagementService managementService = ManagementService.getManagementService(cache);
+
+    DistributedRegionMXBean regionMxBean = managementService.getDistributedRegionMXBean(regionName);
+
+    if (regionMxBean != null) {
+      CompositeResultData crd = ResultBuilder.createCompositeResultData();
+      CompositeResultData.SectionResultData section = crd.addSection();
+      TabularResultData metricsTable = section.addTable();
+      metricsTable.setHeader("Cluster-wide Region Metrics");
+      StringBuilder csvBuilder = null;
+
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        csvBuilder = new StringBuilder();
+        csvBuilder.append("Category");
+        csvBuilder.append(',');
+        csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
+        csvBuilder.append(',');
+        csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
+        csvBuilder.append('\n');
+      }
+
+      Map<String, Boolean> categoriesMap = getSystemRegionMetricsCategories();
+
+      if (categoriesArr != null && categoriesArr.length != 0) {
+        Set<String> categories = createSet(categoriesArr);
+        Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
+        Set<String> userCategories = getSetDifference(categories, checkSet);
+
+        // Checking if the categories specified by the user are valid or not
+        if (userCategories.isEmpty()) {
+          for (String category : checkSet) {
+            categoriesMap.put(category, false);
+          }
+          for (String category : categories) {
+            categoriesMap.put(category.toLowerCase(), true);
+          }
+        } else {
+          StringBuilder sb = new StringBuilder();
+          sb.append("Invalid Categories\n");
+
+          for (String category : userCategories) {
+            sb.append(category);
+            sb.append('\n');
+          }
+          return ResultBuilder.createErrorResultData().addLine(sb.toString());
+        }
+      }
+      /*
+       * General System metrics
+       */
+      // cluster, region, partition , diskstore, callback, eviction
+      if (categoriesMap.get("cluster")) {
+        writeToTableAndCsv(metricsTable, "cluster", "member count", regionMxBean.getMemberCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "region entry count",
+            regionMxBean.getSystemRegionEntryCount(), csvBuilder);
+      }
+
+      if (categoriesMap.get("region")) {
+        writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
+            regionMxBean.getLastModifiedTime(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(),
+            csvBuilder);
+      }
+
+      if (categoriesMap.get("partition")) {
+        writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
+            regionMxBean.getPutLocalRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency",
+            regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
+
+        writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "primaryBucketCount",
+            regionMxBean.getPrimaryBucketCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy",
+            regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "averageBucketSize", regionMxBean.getAvgBucketSize(),
+            csvBuilder);
+      }
+      /*
+       * Disk store
+       */
+      if (categoriesMap.get("diskstore")) {
+        writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
+            regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "diskReadsRate", regionMxBean.getDiskReadsRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress",
+            regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(),
+            csvBuilder);
+
+      }
+      /*
+       * LISTENER
+       */
+      if (categoriesMap.get("callback")) {
+        writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
+            regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
+            regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
+      }
+
+      /*
+       * Eviction
+       */
+      if (categoriesMap.get("eviction")) {
+        writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
+            regionMxBean.getLruEvictionRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
+            csvBuilder);
+      }
+
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        crd.addAsFile(export_to_report_to, csvBuilder != null ? csvBuilder.toString() : null,
+            "Aggregate Region Metrics exported to {0}.", false);
+      }
+
+      return crd;
+    } else {
+      ErrorResultData erd = ResultBuilder.createErrorResultData();
+      String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR,
+          "Distributed Region MBean for " + regionName + " not found");
+      erd.addLine(errorMessage);
+      return erd;
+    }
+  }
+
+  /**
+   * Gets the metrics of region on a given member
+   *
+   * @return ResultData with required Region statistics or ErrorResultData if Region MBean is not
+   *         found to gather metrics
+   * @throws ResultDataException if building result fails
+   */
+  private ResultData getRegionMetricsFromMember(String regionName,
+      DistributedMember distributedMember, String export_to_report_to, String[] categoriesArr)
+      throws ResultDataException {
+
+    final InternalCache cache = getCache();
+    final SystemManagementService managementService =
+        (SystemManagementService) ManagementService.getManagementService(cache);
+
+    ObjectName regionMBeanName =
+        managementService.getRegionMBeanName(distributedMember, regionName);
+    RegionMXBean regionMxBean =
+        managementService.getMBeanInstance(regionMBeanName, RegionMXBean.class);
+
+    if (regionMxBean != null) {
+      CompositeResultData crd = ResultBuilder.createCompositeResultData();
+      CompositeResultData.SectionResultData section = crd.addSection();
+      TabularResultData metricsTable = section.addTable();
+      metricsTable.setHeader("Metrics for region:" + regionName + " On Member "
+          + MBeanJMXAdapter.getMemberNameOrId(distributedMember));
+      StringBuilder csvBuilder = null;
+
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        csvBuilder = new StringBuilder();
+        csvBuilder.append("Category");
+        csvBuilder.append(',');
+        csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
+        csvBuilder.append(',');
+        csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
+        csvBuilder.append('\n');
+      }
+
+      /*
+       * Region Metrics
+       */
+      Map<String, Boolean> categoriesMap = getRegionMetricsCategories();
+
+      if (categoriesArr != null && categoriesArr.length != 0) {
+        Set<String> categories = createSet(categoriesArr);
+        Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
+        Set<String> userCategories = getSetDifference(categories, checkSet);
+
+        // Checking if the categories specified by the user are valid or not
+        if (userCategories.isEmpty()) {
+          for (String category : checkSet) {
+            categoriesMap.put(category, false);
+          }
+          for (String category : categories) {
+            categoriesMap.put(category.toLowerCase(), true);
+          }
+        } else {
+          StringBuilder sb = new StringBuilder();
+          sb.append("Invalid Categories\n");
+
+          for (String category : userCategories) {
+            sb.append(category);
+            sb.append('\n');
+          }
+          return ResultBuilder.createErrorResultData().addLine(sb.toString());
+        }
+      }
+
+      if (categoriesMap.get("region")) {
+        writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
+            regionMxBean.getLastModifiedTime(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(),
+            csvBuilder);
+      }
+
+      if (categoriesMap.get("partition")) {
+        writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
+            regionMxBean.getPutLocalRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency",
+            regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
+
+        writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "primaryBucketCount",
+            regionMxBean.getPrimaryBucketCount(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "configuredRedundancy",
+            regionMxBean.getConfiguredRedundancy(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "actualRedundancy", regionMxBean.getActualRedundancy(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy",
+            regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(),
+            csvBuilder);
+      }
+      /*
+       * Disk store
+       */
+      if (categoriesMap.get("diskstore")) {
+        writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
+            regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "diskReadsRate", "" + regionMxBean.getDiskReadsRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(),
+            csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress",
+            regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(),
+            csvBuilder);
+      }
+      /*
+       * LISTENER
+       */
+      if (categoriesMap.get("callback")) {
+        writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
+            regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
+            regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
+      }
+
+      /*
+       * Eviction
+       */
+      if (categoriesMap.get("eviction")) {
+        writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
+            regionMxBean.getLruEvictionRate(), csvBuilder);
+        writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
+            csvBuilder);
+      }
+      if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+        crd.addAsFile(export_to_report_to, csvBuilder != null ? csvBuilder.toString() : null,
+            "Region Metrics exported to {0}.", false);
+      }
+
+      return crd;
+    } else {
+      ErrorResultData erd = ResultBuilder.createErrorResultData();
+      String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR,
+          "Region MBean for " + regionName + " on member "
+              + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
+      erd.addLine(errorMessage);
+      return erd;
+    }
+  }
+
+  /***
+   * Writes an entry to a TabularResultData and writes a comma separated entry to a string builder
+   */
+  private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
+      long metricValue, StringBuilder csvBuilder) {
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
+
+    if (csvBuilder != null) {
+      csvBuilder.append(type);
+      csvBuilder.append(',');
+      csvBuilder.append(metricName);
+      csvBuilder.append(',');
+      csvBuilder.append(metricValue);
+      csvBuilder.append('\n');
+    }
+  }
+
+  private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
+      double metricValue, StringBuilder csvBuilder) {
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
+
+    if (csvBuilder != null) {
+      csvBuilder.append(type);
+      csvBuilder.append(',');
+      csvBuilder.append(metricName);
+      csvBuilder.append(',');
+      csvBuilder.append(metricValue);
+      csvBuilder.append('\n');
+    }
+  }
+
+  private Set<String> createSet(String[] categories) {
+    Set<String> categoriesSet = new HashSet<>();
+    Collections.addAll(categoriesSet, categories);
+    return categoriesSet;
+  }
+
+  private Set<String> getSetDifference(Set<String> set1, Set<String> set2) {
+    Set<String> setDifference = new HashSet<>();
+    for (String element : set1) {
+      if (!(set2.contains(element.toLowerCase()))) {
+        setDifference.add(element);
+      }
+    }
+    return setDifference;
+  }
+
+  private void writeToTableAndCsv(TabularResultData metricsTable, String metricName,
+      String[] metricValue, StringBuilder csvBuilder) {
+    if (metricValue != null) {
+      for (int i = 0; i < metricValue.length; i++) {
+        if (i == 0) {
+          writeToTableAndCsv(metricsTable, metricName, metricValue[i], csvBuilder);
+        } else {
+          writeToTableAndCsv(metricsTable, "", metricValue[i], csvBuilder);
+        }
+      }
+    }
+  }
+
+  /**
+   * Writes to a TabularResultData and also appends a CSV string to a String builder
+   */
+  private void writeToTableAndCsv(TabularResultData metricsTable, String metricName,
+      String metricValue, StringBuilder csvBuilder) {
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, "");
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
+    metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
+
+    if (csvBuilder != null) {
+      csvBuilder.append("");
+      csvBuilder.append(',');
+      csvBuilder.append(metricName);
+      csvBuilder.append(',');
+      csvBuilder.append(metricValue);
+      csvBuilder.append('\n');
+    }
+  }
+
+  /**
+   * Defines and returns map of categories for Region Metrics
+   *
+   * @return map with categories for region metrics and display flag set to true
+   */
+  private Map<String, Boolean> getRegionMetricsCategories() {
+    Map<String, Boolean> categories = new HashMap<>();
+
+    categories.put("region", true);
+    categories.put("partition", true);
+    categories.put("diskstore", true);
+    categories.put("callback", true);
+    categories.put("gatewayreceiver", true);
+    categories.put("distribution", true);
+    categories.put("query", true);
+    categories.put("eviction", true);
+    return categories;
+  }
+
+  /**
+   * Defines and returns map of categories for System metrics.
+   *
+   * @return map with categories for system metrics and display flag set to true
+   */
+  private Map<String, Boolean> getSystemMetricsCategories() {
+    Map<String, Boolean> categories = new HashMap<>();
+    categories.put("cluster", true);
+    categories.put("cache", true);
+    categories.put("diskstore", true);
+    categories.put("query", true);
+    return categories;
+  }
+
+  /**
+   * Defines and returns map of categories for system-wide region metrics
+   *
+   * @return map with categories for system wide region metrics and display flag set to true
+   */
+  private Map<String, Boolean> getSystemRegionMetricsCategories() {
+    Map<String, Boolean> categories = getRegionMetricsCategories();
+    categories.put("cluster", true);
+    return categories;
+  }
+
+  /**
+   * Defines and returns map of categories for member metrics
+   *
+   * @return map with categories for member metrics and display flag set to true
+   */
+  private Map<String, Boolean> getMemberMetricsCategories() {
+    Map<String, Boolean> categories = new HashMap<>();
+    categories.put("member", true);
+    categories.put("jvm", true);
+    categories.put("region", true);
+    categories.put("serialization", true);
+    categories.put("communication", true);
+    categories.put("function", true);
+    categories.put("transaction", true);
+    categories.put("diskstore", true);
+    categories.put("lock", true);
+    categories.put("eviction", true);
+    categories.put("distribution", true);
+    categories.put("offheap", true);
+    return categories;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
new file mode 100644
index 0000000..fcee9d8
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.logging.log4j.Logger;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionException;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.functions.ShutDownFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ShutdownCommand implements GfshCommand {
+  private final static String DEFAULT_TIME_OUT = "10";
+  private final static Logger logger = LogService.getLogger();
+
+  @CliCommand(value = CliStrings.SHUTDOWN, help = CliStrings.SHUTDOWN__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_LIFECYCLE},
+      interceptor = "org.apache.geode.management.internal.cli.commands.ShutdownCommand$ShutdownCommandInterceptor")
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE)
+  public Result shutdown(
+      @CliOption(key = CliStrings.SHUTDOWN__TIMEOUT, unspecifiedDefaultValue = DEFAULT_TIME_OUT,
+          help = CliStrings.SHUTDOWN__TIMEOUT__HELP) int userSpecifiedTimeout,
+      @CliOption(key = CliStrings.INCLUDE_LOCATORS, unspecifiedDefaultValue = "false",
+          help = CliStrings.INCLUDE_LOCATORS_HELP) boolean shutdownLocators) {
+    try {
+
+      if (userSpecifiedTimeout < Integer.parseInt(DEFAULT_TIME_OUT)) {
+        return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__IMPROPER_TIMEOUT);
+      }
+
+      // convert to milliseconds
+      long timeout = userSpecifiedTimeout * 1000;
+      InternalCache cache = getCache();
+      int numDataNodes = CliUtil.getAllNormalMembers(cache).size();
+      Set<DistributedMember> locators = CliUtil.getAllMembers(cache);
+      Set<DistributedMember> dataNodes = CliUtil.getAllNormalMembers(cache);
+      locators.removeAll(dataNodes);
+
+      if (!shutdownLocators && numDataNodes == 0) {
+        return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__NO_DATA_NODE_FOUND);
+      }
+
+      String managerName = cache.getJmxManagerAdvisor().getDistributionManager().getId().getId();
+
+      final DistributedMember manager = CliUtil.getDistributedMemberByNameOrId(managerName);
+
+      dataNodes.remove(manager);
+
+      // shut down all data members excluding this manager if manager is a data node
+      long timeElapsed = shutDownNodeWithTimeOut(timeout, dataNodes);
+      timeout = timeout - timeElapsed;
+
+      // shut down locators one by one
+      if (shutdownLocators) {
+        if (manager == null) {
+          return ResultBuilder.createUserErrorResult(CliStrings.SHUTDOWN__MSG__MANAGER_NOT_FOUND);
+        }
+
+        // remove current locator as that would get shutdown last
+        if (locators.contains(manager)) {
+          locators.remove(manager);
+        }
+
+        for (DistributedMember locator : locators) {
+          Set<DistributedMember> lsSet = new HashSet<>();
+          lsSet.add(locator);
+          long elapsedTime = shutDownNodeWithTimeOut(timeout, lsSet);
+          timeout = timeout - elapsedTime;
+        }
+      }
+
+      if (locators.contains(manager) && !shutdownLocators) { // This means manager is a locator and
+        // shutdownLocators is false. Hence we
+        // should not stop the manager
+        return ResultBuilder.createInfoResult("Shutdown is triggered");
+      }
+      // now shut down this manager
+      Set<DistributedMember> mgrSet = new HashSet<>();
+      mgrSet.add(manager);
+      // No need to check further timeout as this is the last node we will be
+      // shutting down
+      shutDownNodeWithTimeOut(timeout, mgrSet);
+
+    } catch (TimeoutException tex) {
+      return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN_TIMEDOUT);
+    } catch (Exception ex) {
+      ex.printStackTrace();
+      return ResultBuilder.createUserErrorResult(ex.getMessage());
+    }
+    // @TODO. List all the nodes which could be successfully shutdown
+    return ResultBuilder.createInfoResult("Shutdown is triggered");
+  }
+
+  /**
+   * @param timeout user specified timeout
+   * @param nodesToBeStopped list of nodes to be stopped
+   * @return Elapsed time to shutdown the given nodes;
+   */
+  private long shutDownNodeWithTimeOut(long timeout, Set<DistributedMember> nodesToBeStopped)
+      throws TimeoutException, InterruptedException, ExecutionException {
+
+    long shutDownTimeStart = System.currentTimeMillis();
+    shutdownNode(timeout, nodesToBeStopped);
+
+    long shutDownTimeEnd = System.currentTimeMillis();
+
+    long timeElapsed = shutDownTimeEnd - shutDownTimeStart;
+
+    if (timeElapsed > timeout || Boolean.getBoolean("ThrowTimeoutException")) {
+      // The second check for ThrowTimeoutException is a test hook
+      throw new TimeoutException();
+    }
+    return timeElapsed;
+  }
+
+  private void shutdownNode(final long timeout, final Set<DistributedMember> includeMembers)
+      throws TimeoutException, InterruptedException, ExecutionException {
+    ExecutorService exec = Executors.newSingleThreadExecutor();
+    try {
+      final Function shutDownFunction = new ShutDownFunction();
+      logger.info("Gfsh executing shutdown on members " + includeMembers);
+      Callable<String> shutdownNodes = new Callable<String>() {
+
+        @Override
+        public String call() {
+          try {
+            Execution execution = FunctionService.onMembers(includeMembers);
+            execution.execute(shutDownFunction);
+          } catch (FunctionException functionEx) {
+            // Expected Exception as the function is shutting down the target members and the result
+            // collector will get member departed exception
+          }
+          return "SUCCESS";
+        }
+      };
+      Future<String> result = exec.submit(shutdownNodes);
+      result.get(timeout, TimeUnit.MILLISECONDS);
+    } catch (TimeoutException te) {
+      logger.error("TimeoutException in shutting down members." + includeMembers);
+      throw te;
+    } catch (InterruptedException e) {
+      logger.error("InterruptedException in shutting down members." + includeMembers);
+      throw e;
+    } catch (ExecutionException e) {
+      logger.error("ExecutionException in shutting down members." + includeMembers);
+      throw e;
+    } finally {
+      exec.shutdownNow();
+    }
+  }
+
+  public static class ShutdownCommandInterceptor extends AbstractCliAroundInterceptor {
+    @Override
+    public Result preExecution(GfshParseResult parseResult) {
+
+      // This hook is for testing purpose only.
+      if (Boolean.getBoolean(CliStrings.IGNORE_INTERCEPTORS)) {
+        return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__SHUTDOWN_ENTIRE_DS);
+      }
+
+      Response response = readYesNo(CliStrings.SHUTDOWN__MSG__WARN_USER, Response.YES);
+      if (response == Response.NO) {
+        return ResultBuilder
+            .createShellClientAbortOperationResult(CliStrings.SHUTDOWN__MSG__ABORTING_SHUTDOWN);
+      } else {
+        return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__SHUTDOWN_ENTIRE_DS);
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
index 79952b9..7bce3d0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
@@ -30,7 +30,14 @@ import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
  * endpoints for the Gfsh Miscellaneous Commands.
  * <p/>
  * 
- * @see org.apache.geode.management.internal.cli.commands.MiscellaneousCommands
+ * @see org.apache.geode.management.internal.cli.commands.ChangeLogLevelCommand
+ * @see org.apache.geode.management.internal.cli.commands.ExportStackTraceCommand
+ * @see org.apache.geode.management.internal.cli.commands.GCCommand
+ * @see org.apache.geode.management.internal.cli.commands.NetstatCommand
+ * @see org.apache.geode.management.internal.cli.commands.ShowDeadlockCommand
+ * @see org.apache.geode.management.internal.cli.commands.ShowLogCommand
+ * @see org.apache.geode.management.internal.cli.commands.ShowMetricsCommand
+ * @see org.apache.geode.management.internal.cli.commands.ShutdownCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.PathVariable

http://git-wip-us.apache.org/repos/asf/geode/blob/611095f0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
index bcbe07c..9feac1a 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
@@ -18,19 +18,20 @@ package org.apache.geode.management.internal.cli.commands;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.when;
 
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.test.junit.categories.UnitTest;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.mockito.Mockito;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.test.junit.categories.UnitTest;
 
 @Category(UnitTest.class)
 public class LogLevelInterceptorTest {
@@ -43,7 +44,7 @@ public class LogLevelInterceptorTest {
   public void before() {
     interceptors.add(new ExportLogsInterceptor());
     interceptors.add(new ConfigCommands.AlterRuntimeInterceptor());
-    interceptors.add(new MiscellaneousCommands.ChangeLogLevelInterceptor());
+    interceptors.add(new ChangeLogLevelCommand.ChangeLogLevelCommandInterceptor());
 
     parseResult = Mockito.mock(GfshParseResult.class);
     arguments = new HashMap<>();


[09/47] geode git commit: GEODE-3436: Restore refactoring of Refactoring FunctionCommands

Posted by ds...@apache.org.
GEODE-3436: Restore refactoring of Refactoring FunctionCommands

* See initial commit GEODE-3260 (90f5440de8ec747f301a309a0a34101e8defcd29)


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

Branch: refs/heads/feature/GEODE-3543
Commit: 39fff4544c8ddc0b96ff58ed56c7394b1e9e10e4
Parents: 0c124b7
Author: YehEmily <em...@gmail.com>
Authored: Mon Aug 7 12:56:17 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:27:25 2017 -0700

----------------------------------------------------------------------
 .../cli/commands/DestroyFunctionCommand.java    | 163 ++++++
 .../cli/commands/ExecuteFunctionCommand.java    | 330 ++++++++++++
 .../internal/cli/commands/FunctionCommands.java | 537 -------------------
 .../cli/commands/ListFunctionCommand.java       | 103 ++++
 .../controllers/FunctionCommandsController.java |  13 +-
 .../internal/security/TestCommand.java          |   4 +-
 6 files changed, 606 insertions(+), 544 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/39fff454/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyFunctionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyFunctionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyFunctionCommand.java
new file mode 100644
index 0000000..37beb97
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyFunctionCommand.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionException;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.functions.UnregisterFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class DestroyFunctionCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.DESTROY_FUNCTION, help = CliStrings.DESTROY_FUNCTION__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION},
+      interceptor = "org.apache.geode.management.internal.cli.commands.DestroyFunctionCommand$Interceptor")
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
+  // TODO: Add optioncontext for functionId
+  public Result destroyFunction(
+      @CliOption(key = CliStrings.DESTROY_FUNCTION__ID, mandatory = true,
+          help = CliStrings.DESTROY_FUNCTION__HELP) String functionId,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.DESTROY_FUNCTION__ONGROUPS__HELP) String[] groups,
+      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
+          help = CliStrings.DESTROY_FUNCTION__ONMEMBER__HELP) String memberId) {
+    try {
+      InternalCache cache = getCache();
+      Set<DistributedMember> dsMembers = new HashSet<>();
+      if (groups != null && memberId != null) {
+        return ResultBuilder
+            .createUserErrorResult(CliStrings.DESTROY_FUNCTION__MSG__PROVIDE_OPTION);
+      } else if (groups != null && groups.length > 0) {
+        // execute on group members
+        for (String grp : groups) {
+          dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
+        }
+        @SuppressWarnings("unchecked")
+        Result results = executeFunction(cache, dsMembers, functionId);
+        return results;
+      } else if (memberId != null) {
+        // execute on member
+        dsMembers.add(getMember(cache, memberId));
+        @SuppressWarnings("unchecked")
+        Result results = executeFunction(cache, dsMembers, functionId);
+        return results;
+      } else {
+        // no option provided.
+        @SuppressWarnings("unchecked")
+        Result results = executeFunction(cache, cache.getMembers(), functionId);
+        return results;
+      }
+    } catch (Exception e) {
+      ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
+          .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
+      return ResultBuilder.buildResult(errorResultData);
+    }
+  }
+
+  private Result executeFunction(InternalCache cache, Set<DistributedMember> DsMembers,
+      String functionId) {
+    // unregister on a set of of members
+    Function unregisterFunction = new UnregisterFunction();
+    FunctionService.registerFunction(unregisterFunction);
+    List resultList;
+
+    if (DsMembers.isEmpty()) {
+      return ResultBuilder.createInfoResult("No members for execution");
+    }
+    Object[] obj = new Object[1];
+    obj[0] = functionId;
+
+    Execution execution = FunctionService.onMembers(DsMembers).setArguments(obj);
+
+    if (execution == null) {
+      cache.getLogger().error("executeUnregister execution is null");
+      ErrorResultData errorResultData =
+          ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+              .addLine(CliStrings.DESTROY_FUNCTION__MSG__CANNOT_EXECUTE);
+      return (ResultBuilder.buildResult(errorResultData));
+    }
+    try {
+      resultList = (ArrayList) execution.execute(unregisterFunction).getResult();
+    } catch (FunctionException ex) {
+      ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
+          .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(ex.getMessage());
+      return (ResultBuilder.buildResult(errorResultData));
+    }
+    String resultStr = ((String) resultList.get(0));
+    if (resultStr.equals("Succeeded in unregistering")) {
+      StringBuilder members = new StringBuilder();
+      for (DistributedMember member : DsMembers) {
+        members.append(member.getId());
+        members.append(",");
+      }
+      return ResultBuilder.createInfoResult("Destroyed " + functionId + " Successfully on "
+          + members.toString().substring(0, members.toString().length() - 1));
+    } else {
+      return ResultBuilder.createInfoResult("Failed in unregistering");
+    }
+  }
+
+  /**
+   * Interceptor used by gfsh to intercept execution of destroy.
+   */
+  public static class Interceptor extends AbstractCliAroundInterceptor {
+    @Override
+    public Result preExecution(GfshParseResult parseResult) {
+      Map<String, String> paramValueMap = parseResult.getParamValueStrings();
+      paramValueMap.entrySet();
+      String onGroup = paramValueMap.get(CliStrings.GROUP);
+      String onMember = paramValueMap.get(CliStrings.MEMBER);
+
+      if ((onGroup == null && onMember == null)) {
+        Response response = readYesNo("Do you really want to destroy "
+            + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID) + " on entire DS?", Response.NO);
+        if (response == Response.NO) {
+          return ResultBuilder.createShellClientAbortOperationResult(
+              "Aborted destroy of " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
+        } else {
+          return ResultBuilder
+              .createInfoResult("Destroying " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
+        }
+      } else {
+        return ResultBuilder
+            .createInfoResult("Destroying " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/39fff454/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
new file mode 100644
index 0000000..a016ccf
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
@@ -0,0 +1,330 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Stream;
+
+import org.apache.commons.lang.BooleanUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionException;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.ClassPathLoader;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.DistributedRegionMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.MBeanJMXAdapter;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.UserFunctionExecution;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ExecuteFunctionCommand implements GfshCommand {
+  @CliCommand(value = CliStrings.EXECUTE_FUNCTION, help = CliStrings.EXECUTE_FUNCTION__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION})
+  @ResourceOperation(resource = ResourcePermission.Resource.DATA,
+      operation = ResourcePermission.Operation.WRITE)
+  public Result executeFunction(
+      // TODO: Add optioncontext for functionID
+      @CliOption(key = CliStrings.EXECUTE_FUNCTION__ID, mandatory = true,
+          help = CliStrings.EXECUTE_FUNCTION__ID__HELP) String functionId,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.EXECUTE_FUNCTION__ONGROUPS__HELP) String[] onGroups,
+      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
+          help = CliStrings.EXECUTE_FUNCTION__ONMEMBER__HELP) String onMember,
+      @CliOption(key = CliStrings.EXECUTE_FUNCTION__ONREGION,
+          optionContext = ConverterHint.REGION_PATH,
+          help = CliStrings.EXECUTE_FUNCTION__ONREGION__HELP) String onRegion,
+      @CliOption(key = CliStrings.EXECUTE_FUNCTION__ARGUMENTS,
+          help = CliStrings.EXECUTE_FUNCTION__ARGUMENTS__HELP) String[] arguments,
+      @CliOption(key = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR,
+          help = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR__HELP) String resultCollector,
+      @CliOption(key = CliStrings.EXECUTE_FUNCTION__FILTER,
+          help = CliStrings.EXECUTE_FUNCTION__FILTER__HELP) String filterString) {
+    CompositeResultData executeFunctionResultTable = ResultBuilder.createCompositeResultData();
+    TabularResultData resultTable = executeFunctionResultTable.addSection().addTable("Table1");
+    String headerText = "Execution summary";
+    resultTable.setHeader(headerText);
+    ResultCollector resultCollectorInstance = null;
+    Set<String> filters = new HashSet<>();
+    Execution execution;
+    if (functionId != null) {
+      functionId = functionId.trim();
+    }
+    if (onRegion != null) {
+      onRegion = onRegion.trim();
+    }
+    if (onMember != null) {
+      onMember = onMember.trim();
+    }
+    if (filterString != null) {
+      filterString = filterString.trim();
+    }
+
+    try {
+      // validate otherwise return right away. no need to process anything
+      if (functionId == null || functionId.length() == 0) {
+        ErrorResultData errorResultData =
+            ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+                .addLine(CliStrings.EXECUTE_FUNCTION__MSG__MISSING_FUNCTIONID);
+        return ResultBuilder.buildResult(errorResultData);
+      }
+
+      if (isMoreThanOneTrue(onRegion != null, onMember != null, onGroups != null)) {
+        // Provide Only one of region/member/groups
+        ErrorResultData errorResultData =
+            ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+                .addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
+        return ResultBuilder.buildResult(errorResultData);
+      } else if ((onRegion == null || onRegion.length() == 0) && (filterString != null)) {
+        ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
+            .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+            .addLine(CliStrings.EXECUTE_FUNCTION__MSG__MEMBER_SHOULD_NOT_HAVE_FILTER_FOR_EXECUTION);
+        return ResultBuilder.buildResult(errorResultData);
+      }
+
+      InternalCache cache = getCache();
+
+      if (resultCollector != null) {
+        resultCollectorInstance =
+            (ResultCollector) ClassPathLoader.getLatest().forName(resultCollector).newInstance();
+      }
+
+      if (filterString != null && filterString.length() > 0) {
+        filters.add(filterString);
+      }
+
+      if (onRegion == null && onMember == null && onGroups == null) {
+        // run function on all the members excluding locators bug#46113
+        // if user wish to execute on locator then he can choose --member or --group option
+        Set<DistributedMember> dsMembers = CliUtil.getAllNormalMembers(cache);
+        if (dsMembers.size() > 0) {
+          new UserFunctionExecution();
+          LogWrapper.getInstance().info(CliStrings
+              .format(CliStrings.EXECUTE_FUNCTION__MSG__EXECUTING_0_ON_ENTIRE_DS, functionId));
+          for (DistributedMember member : dsMembers) {
+            executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
+                member, resultTable, onRegion);
+          }
+          return ResultBuilder.buildResult(resultTable);
+        } else {
+          return ResultBuilder
+              .createUserErrorResult(CliStrings.EXECUTE_FUNCTION__MSG__DS_HAS_NO_MEMBERS);
+        }
+      } else if (onRegion != null && onRegion.length() > 0) {
+        if (cache.getRegion(onRegion) == null) {
+          // find a member where region is present
+          DistributedRegionMXBean bean = ManagementService.getManagementService(getCache())
+              .getDistributedRegionMXBean(onRegion);
+          if (bean == null) {
+            bean = ManagementService.getManagementService(getCache())
+                .getDistributedRegionMXBean(Region.SEPARATOR + onRegion);
+
+            if (bean == null) {
+              return ResultBuilder.createGemFireErrorResult(CliStrings
+                  .format(CliStrings.EXECUTE_FUNCTION__MSG__MXBEAN_0_FOR_NOT_FOUND, onRegion));
+            }
+          }
+
+          DistributedMember member = null;
+          String[] membersName = bean.getMembers();
+          Set<DistributedMember> dsMembers = CliUtil.getAllMembers(cache);
+          Iterator it = dsMembers.iterator();
+          boolean matchFound = false;
+
+          if (membersName.length > 0) {
+            while (it.hasNext() && !matchFound) {
+              DistributedMember dsmember = (DistributedMember) it.next();
+              for (String memberName : membersName) {
+                if (MBeanJMXAdapter.getMemberNameOrId(dsmember).equals(memberName)) {
+                  member = dsmember;
+                  matchFound = true;
+                  break;
+                }
+              }
+            }
+          }
+          if (matchFound) {
+            executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
+                member, resultTable, onRegion);
+            return ResultBuilder.buildResult(resultTable);
+          } else {
+            return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+                CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER_REGION, " " + onRegion));
+          }
+        } else {
+          execution = FunctionService.onRegion(cache.getRegion(onRegion));
+          if (execution != null) {
+            if (resultCollectorInstance != null) {
+              execution = execution.withCollector(resultCollectorInstance);
+            }
+            if (filters.size() > 0) {
+              execution = execution.withFilter(filters);
+            }
+            if (arguments != null && arguments.length > 0) {
+              execution = execution.setArguments(arguments);
+            }
+
+            try {
+              List<Object> results = (List<Object>) execution.execute(functionId).getResult();
+              if (results.size() > 0) {
+                StringBuilder strResult = new StringBuilder();
+                for (Object obj : results) {
+                  strResult.append(obj);
+                }
+                toTabularResultData(resultTable,
+                    cache.getDistributedSystem().getDistributedMember().getId(),
+                    strResult.toString());
+              }
+              return ResultBuilder.buildResult(resultTable);
+            } catch (FunctionException e) {
+              return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+                  CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2,
+                  functionId, onRegion, e.getMessage()));
+            }
+          } else {
+            return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+                CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2,
+                functionId, onRegion,
+                CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR));
+          }
+        }
+      } else if (onGroups != null) {
+        // execute on group members
+        Set<DistributedMember> dsMembers = new HashSet<>();
+        for (String grp : onGroups) {
+          dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
+        }
+
+        if (dsMembers.size() > 0) {
+          for (DistributedMember member : dsMembers) {
+            executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
+                member, resultTable, onRegion);
+          }
+          return ResultBuilder.buildResult(resultTable);
+        } else {
+          StringBuilder grps = new StringBuilder();
+          for (String grp : onGroups) {
+            grps.append(grp);
+            grps.append(", ");
+          }
+          return ResultBuilder.createUserErrorResult(
+              CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__GROUPS_0_HAS_NO_MEMBERS,
+                  grps.toString().substring(0, grps.toString().length() - 1)));
+        }
+      } else if (onMember != null && onMember.length() > 0) {
+        DistributedMember member = CliUtil.getDistributedMemberByNameOrId(onMember); // fix for bug
+        // 45658
+        if (member != null) {
+          executeAndGetResults(functionId, filterString, resultCollector, arguments, cache, member,
+              resultTable, onRegion);
+        } else {
+          toTabularResultData(resultTable, onMember, CliStrings
+              .format(CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER + " " + onMember));
+        }
+        return ResultBuilder.buildResult(resultTable);
+      }
+    } catch (Exception e) {
+      ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
+          .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
+      return ResultBuilder.buildResult(errorResultData);
+    }
+    return null;
+  }
+
+  private boolean isMoreThanOneTrue(Boolean... values) {
+    return Stream.of(values).mapToInt(BooleanUtils::toInteger).sum() > 1;
+  }
+
+  void executeAndGetResults(String functionId, String filterString, String resultCollector,
+      String[] arguments, InternalCache cache, DistributedMember member,
+      TabularResultData resultTable, String onRegion) {
+    StringBuilder resultMessage = new StringBuilder();
+    try {
+      Function function = new UserFunctionExecution();
+      Object[] args = new Object[5];
+      args[0] = functionId;
+      if (filterString != null) {
+        args[1] = filterString;
+      }
+      if (resultCollector != null) {
+        args[2] = resultCollector;
+      }
+      if (arguments != null && arguments.length > 0) {
+        args[3] = "";
+        for (String str : arguments) {
+          // send via CSV separated value format
+          if (str != null) {
+            args[3] = args[3] + str + ",";
+          }
+        }
+      }
+      args[4] = onRegion;
+
+      Execution execution = FunctionService.onMember(member).setArguments(args);
+      if (execution != null) {
+        List<Object> results = (List<Object>) execution.execute(function).getResult();
+        if (results != null) {
+          for (Object resultObj : results) {
+            if (resultObj != null) {
+              if (resultObj instanceof String) {
+                resultMessage.append(((String) resultObj));
+              } else if (resultObj instanceof Exception) {
+                resultMessage.append(((Exception) resultObj).getMessage());
+              } else {
+                resultMessage.append(resultObj);
+              }
+            }
+          }
+        }
+        toTabularResultData(resultTable, member.getId(), resultMessage.toString());
+      } else {
+        toTabularResultData(resultTable, member.getId(),
+            CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR);
+      }
+    } catch (Exception e) {
+      resultMessage.append(CliStrings.format(
+          CliStrings.EXECUTE_FUNCTION__MSG__COULD_NOT_EXECUTE_FUNCTION_0_ON_MEMBER_1_ERROR_2,
+          functionId, member.getId(), e.getMessage()));
+      toTabularResultData(resultTable, member.getId(), resultMessage.toString());
+    }
+  }
+
+  private void toTabularResultData(TabularResultData table, String memberId, String memberResult) {
+    table.accumulate("Member ID/Name", memberId);
+    table.accumulate("Function Execution Result", memberResult);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/39fff454/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
deleted file mode 100644
index 21d89c1..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
+++ /dev/null
@@ -1,537 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.commands;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.stream.Stream;
-
-import org.apache.commons.lang.BooleanUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.Function;
-import org.apache.geode.cache.execute.FunctionException;
-import org.apache.geode.cache.execute.FunctionService;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.ClassPathLoader;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.DistributedRegionMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.ListFunctionFunction;
-import org.apache.geode.management.internal.cli.functions.UnregisterFunction;
-import org.apache.geode.management.internal.cli.functions.UserFunctionExecution;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.geode.security.ResourcePermission.Target;
-
-/**
- * @since GemFire 7.0
- */
-@SuppressWarnings("unused")
-public class FunctionCommands implements GfshCommand {
-
-  private final ListFunctionFunction listFunctionFunction = new ListFunctionFunction();
-
-  @CliCommand(value = CliStrings.EXECUTE_FUNCTION, help = CliStrings.EXECUTE_FUNCTION__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION})
-  @ResourceOperation(resource = Resource.DATA, operation = Operation.WRITE)
-  public Result executeFunction(
-      // TODO: Add optioncontext for functionID
-      @CliOption(key = CliStrings.EXECUTE_FUNCTION__ID, mandatory = true,
-          help = CliStrings.EXECUTE_FUNCTION__ID__HELP) String functionId,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.EXECUTE_FUNCTION__ONGROUPS__HELP) String[] onGroups,
-      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
-          help = CliStrings.EXECUTE_FUNCTION__ONMEMBER__HELP) String onMember,
-      @CliOption(key = CliStrings.EXECUTE_FUNCTION__ONREGION,
-          optionContext = ConverterHint.REGION_PATH,
-          help = CliStrings.EXECUTE_FUNCTION__ONREGION__HELP) String onRegion,
-      @CliOption(key = CliStrings.EXECUTE_FUNCTION__ARGUMENTS,
-          help = CliStrings.EXECUTE_FUNCTION__ARGUMENTS__HELP) String[] arguments,
-      @CliOption(key = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR,
-          help = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR__HELP) String resultCollector,
-      @CliOption(key = CliStrings.EXECUTE_FUNCTION__FILTER,
-          help = CliStrings.EXECUTE_FUNCTION__FILTER__HELP) String filterString) {
-
-    Result result = null;
-    CompositeResultData executeFunctionResultTable = ResultBuilder.createCompositeResultData();
-    TabularResultData resultTable = executeFunctionResultTable.addSection().addTable("Table1");
-    String headerText = "Execution summary";
-    resultTable.setHeader(headerText);
-    ResultCollector resultCollectorInstance = null;
-    Function function;
-    Set<String> filters = new HashSet<>();
-    Execution execution;
-    if (functionId != null) {
-      functionId = functionId.trim();
-    }
-    if (onRegion != null) {
-      onRegion = onRegion.trim();
-    }
-    if (onMember != null) {
-      onMember = onMember.trim();
-    }
-    if (filterString != null) {
-      filterString = filterString.trim();
-    }
-
-    try {
-      // validate otherwise return right away. no need to process anything
-      if (functionId == null || functionId.length() == 0) {
-        ErrorResultData errorResultData =
-            ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
-                .addLine(CliStrings.EXECUTE_FUNCTION__MSG__MISSING_FUNCTIONID);
-        result = ResultBuilder.buildResult(errorResultData);
-        return result;
-      }
-
-      if (isMoreThanOneIsTrue(onRegion != null, onMember != null, onGroups != null)) {
-        // Provide Only one of region/member/groups
-        ErrorResultData errorResultData =
-            ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
-                .addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
-        result = ResultBuilder.buildResult(errorResultData);
-        return result;
-      } else if ((onRegion == null || onRegion.length() == 0) && (filterString != null)) {
-        ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
-            .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
-            .addLine(CliStrings.EXECUTE_FUNCTION__MSG__MEMBER_SHOULD_NOT_HAVE_FILTER_FOR_EXECUTION);
-        result = ResultBuilder.buildResult(errorResultData);
-        return result;
-      }
-
-      InternalCache cache = getCache();
-
-      if (resultCollector != null) {
-        resultCollectorInstance =
-            (ResultCollector) ClassPathLoader.getLatest().forName(resultCollector).newInstance();
-      }
-
-      if (filterString != null && filterString.length() > 0) {
-        filters.add(filterString);
-      }
-
-      if (onRegion == null && onMember == null && onGroups == null) {
-        // run function on all the members excluding locators bug#46113
-        // if user wish to execute on locator then he can choose --member or --group option
-        Set<DistributedMember> dsMembers = CliUtil.getAllNormalMembers(cache);
-        if (dsMembers.size() > 0) {
-          function = new UserFunctionExecution();
-          LogWrapper.getInstance().info(CliStrings
-              .format(CliStrings.EXECUTE_FUNCTION__MSG__EXECUTING_0_ON_ENTIRE_DS, functionId));
-          for (DistributedMember member : dsMembers) {
-            executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
-                member, resultTable, onRegion);
-          }
-          return ResultBuilder.buildResult(resultTable);
-        } else {
-          return ResultBuilder
-              .createUserErrorResult(CliStrings.EXECUTE_FUNCTION__MSG__DS_HAS_NO_MEMBERS);
-        }
-      } else if (onRegion != null && onRegion.length() > 0) {
-        if (cache.getRegion(onRegion) == null) {
-          // find a member where region is present
-          DistributedRegionMXBean bean = ManagementService.getManagementService(getCache())
-              .getDistributedRegionMXBean(onRegion);
-          if (bean == null) {
-            bean = ManagementService.getManagementService(getCache())
-                .getDistributedRegionMXBean(Region.SEPARATOR + onRegion);
-
-            if (bean == null) {
-              return ResultBuilder.createGemFireErrorResult(CliStrings
-                  .format(CliStrings.EXECUTE_FUNCTION__MSG__MXBEAN_0_FOR_NOT_FOUND, onRegion));
-            }
-          }
-
-          DistributedMember member = null;
-          String[] membersName = bean.getMembers();
-          Set<DistributedMember> dsMembers = CliUtil.getAllMembers(cache);
-          Iterator it = dsMembers.iterator();
-          boolean matchFound = false;
-
-          if (membersName.length > 0) {
-            while (it.hasNext() && !matchFound) {
-              DistributedMember dsmember = (DistributedMember) it.next();
-              for (String memberName : membersName) {
-                if (MBeanJMXAdapter.getMemberNameOrId(dsmember).equals(memberName)) {
-                  member = dsmember;
-                  matchFound = true;
-                  break;
-                }
-              }
-            }
-          }
-          if (matchFound) {
-            executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
-                member, resultTable, onRegion);
-            return ResultBuilder.buildResult(resultTable);
-          } else {
-            return ResultBuilder.createGemFireErrorResult(CliStrings.format(
-                CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER_REGION, " " + onRegion));
-          }
-        } else {
-          execution = FunctionService.onRegion(cache.getRegion(onRegion));
-          if (execution != null) {
-            if (resultCollectorInstance != null) {
-              execution = execution.withCollector(resultCollectorInstance);
-            }
-            if (filters != null && filters.size() > 0) {
-              execution = execution.withFilter(filters);
-            }
-            if (arguments != null && arguments.length > 0) {
-              execution = execution.setArguments(arguments);
-            }
-
-            try {
-              List<Object> results = (List<Object>) execution.execute(functionId).getResult();
-              if (results.size() > 0) {
-                StringBuilder strResult = new StringBuilder();
-                for (Object obj : results) {
-                  strResult.append(obj);
-                }
-                toTabularResultData(resultTable,
-                    cache.getDistributedSystem().getDistributedMember().getId(),
-                    strResult.toString());
-              }
-              return ResultBuilder.buildResult(resultTable);
-            } catch (FunctionException e) {
-              return ResultBuilder.createGemFireErrorResult(CliStrings.format(
-                  CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2,
-                  functionId, onRegion, e.getMessage()));
-            }
-          } else {
-            return ResultBuilder.createGemFireErrorResult(CliStrings.format(
-                CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2,
-                functionId, onRegion,
-                CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR));
-          }
-        }
-      } else if (onGroups != null) {
-        // execute on group members
-        Set<DistributedMember> dsMembers = new HashSet<>();
-        for (String grp : onGroups) {
-          dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
-        }
-
-        StringBuilder successMessage = new StringBuilder();
-        if (dsMembers.size() > 0) {
-          for (DistributedMember member : dsMembers) {
-            executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
-                member, resultTable, onRegion);
-          }
-          return ResultBuilder.buildResult(resultTable);
-        } else {
-          StringBuilder grps = new StringBuilder();
-          for (String grp : onGroups) {
-            grps.append(grp);
-            grps.append(", ");
-          }
-          return ResultBuilder.createUserErrorResult(
-              CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__GROUPS_0_HAS_NO_MEMBERS,
-                  grps.toString().substring(0, grps.toString().length() - 1)));
-        }
-      } else if (onMember != null && onMember.length() > 0) {
-        DistributedMember member = CliUtil.getDistributedMemberByNameOrId(onMember); // fix for bug
-        // 45658
-        if (member != null) {
-          executeAndGetResults(functionId, filterString, resultCollector, arguments, cache, member,
-              resultTable, onRegion);
-        } else {
-          toTabularResultData(resultTable, onMember, CliStrings
-              .format(CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER + " " + onMember));
-        }
-        return ResultBuilder.buildResult(resultTable);
-      }
-    } catch (Exception e) {
-      ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
-          .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
-      result = ResultBuilder.buildResult(errorResultData);
-      return result;
-    }
-
-    return result;
-  }
-
-  private boolean isMoreThanOneIsTrue(Boolean... values) {
-    return Stream.of(values).mapToInt(BooleanUtils::toInteger).sum() > 1;
-  }
-
-  void executeAndGetResults(String functionId, String filterString, String resultCollector,
-      String[] arguments, InternalCache cache, DistributedMember member,
-      TabularResultData resultTable, String onRegion) {
-    StringBuilder resultMessage = new StringBuilder();
-    try {
-      Function function = new UserFunctionExecution();
-      Object[] args = new Object[5];
-      args[0] = functionId;
-      if (filterString != null) {
-        args[1] = filterString;
-      }
-      if (resultCollector != null) {
-        args[2] = resultCollector;
-      }
-      if (arguments != null && arguments.length > 0) {
-        args[3] = "";
-        for (String str : arguments) {
-          // send via CSV separated value format
-          if (str != null) {
-            args[3] = args[3] + str + ",";
-          }
-        }
-      }
-      args[4] = onRegion;
-
-      Execution execution = FunctionService.onMember(member).setArguments(args);
-      if (execution != null) {
-        List<Object> results = (List<Object>) execution.execute(function).getResult();
-        if (results != null) {
-          for (Object resultObj : results) {
-            if (resultObj != null) {
-              if (resultObj instanceof String) {
-                resultMessage.append(((String) resultObj));
-              } else if (resultObj instanceof Exception) {
-                resultMessage.append(((Exception) resultObj).getMessage());
-              } else {
-                resultMessage.append(resultObj);
-              }
-            }
-          }
-        }
-        toTabularResultData(resultTable, member.getId(), resultMessage.toString());
-      } else {
-        toTabularResultData(resultTable, member.getId(),
-            CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR);
-      }
-    } catch (Exception e) {
-      resultMessage.append(CliStrings.format(
-          CliStrings.EXECUTE_FUNCTION__MSG__COULD_NOT_EXECUTE_FUNCTION_0_ON_MEMBER_1_ERROR_2,
-          functionId, member.getId(), e.getMessage()));
-      toTabularResultData(resultTable, member.getId(), resultMessage.toString());
-    }
-  }
-
-  protected void toTabularResultData(TabularResultData table, String memberId,
-      String memberResult) {
-    String newLine = System.getProperty("line.separator");
-    table.accumulate("Member ID/Name", memberId);
-    table.accumulate("Function Execution Result", memberResult);
-  }
-
-  @CliCommand(value = CliStrings.DESTROY_FUNCTION, help = CliStrings.DESTROY_FUNCTION__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION},
-      interceptor = "org.apache.geode.management.internal.cli.commands.FunctionCommands$Interceptor")
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
-  // TODO: Add optioncontext for functionId
-  public Result destroyFunction(
-      @CliOption(key = CliStrings.DESTROY_FUNCTION__ID, mandatory = true,
-          help = CliStrings.DESTROY_FUNCTION__HELP) String functionId,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.DESTROY_FUNCTION__ONGROUPS__HELP) String[] groups,
-      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
-          help = CliStrings.DESTROY_FUNCTION__ONMEMBER__HELP) String memberId) {
-    Result result;
-    try {
-      InternalCache cache = getCache();
-      Set<DistributedMember> dsMembers = new HashSet<>();
-      if (groups != null && memberId != null) {
-        return ResultBuilder
-            .createUserErrorResult(CliStrings.DESTROY_FUNCTION__MSG__PROVIDE_OPTION);
-      } else if (groups != null && groups.length > 0) {
-        // execute on group members
-        for (String grp : groups) {
-          dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
-        }
-        @SuppressWarnings("unchecked")
-        Result results = executeFunction(cache, dsMembers, functionId);
-        return results;
-      } else if (memberId != null) {
-        // execute on member
-        dsMembers.add(getMember(cache, memberId));
-        @SuppressWarnings("unchecked")
-        Result results = executeFunction(cache, dsMembers, functionId);
-        return results;
-      } else {
-        // no option provided.
-        @SuppressWarnings("unchecked")
-        Result results = executeFunction(cache, cache.getMembers(), functionId);
-        return results;
-      }
-    } catch (Exception e) {
-      ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
-          .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
-      result = ResultBuilder.buildResult(errorResultData);
-      return result;
-    }
-  }
-
-  /**
-   * Interceptor used by gfsh to intercept execution of destroy.
-   */
-  public static class Interceptor extends AbstractCliAroundInterceptor {
-    @Override
-    public Result preExecution(GfshParseResult parseResult) {
-      Map<String, String> paramValueMap = parseResult.getParamValueStrings();
-      Set<Entry<String, String>> setEnvMap = paramValueMap.entrySet();
-      String onGroup = paramValueMap.get(CliStrings.GROUP);
-      String onMember = paramValueMap.get(CliStrings.MEMBER);
-
-      if ((onGroup == null && onMember == null)) {
-        Response response = readYesNo("Do you really want to destroy "
-            + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID) + " on entire DS?", Response.NO);
-        if (response == Response.NO) {
-          return ResultBuilder.createShellClientAbortOperationResult(
-              "Aborted destroy of " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
-        } else {
-          return ResultBuilder
-              .createInfoResult("Destroying " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
-        }
-      } else {
-        return ResultBuilder
-            .createInfoResult("Destroying " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
-      }
-    }
-  }
-
-  Result executeFunction(InternalCache cache, Set<DistributedMember> DsMembers, String functionId) {
-    // unregister on a set of of members
-    Function unregisterFunction = new UnregisterFunction();
-    FunctionService.registerFunction(unregisterFunction);
-    List resultList;
-
-    if (DsMembers.isEmpty()) {
-      return ResultBuilder.createInfoResult("No members for execution");
-    }
-    Object[] obj = new Object[1];
-    obj[0] = functionId;
-
-    Execution execution = FunctionService.onMembers(DsMembers).setArguments(obj);
-
-    if (execution == null) {
-      cache.getLogger().error("executeUnregister execution is null");
-      ErrorResultData errorResultData =
-          ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
-              .addLine(CliStrings.DESTROY_FUNCTION__MSG__CANNOT_EXECUTE);
-      return (ResultBuilder.buildResult(errorResultData));
-    }
-    try {
-      resultList = (ArrayList) execution.execute(unregisterFunction).getResult();
-    } catch (FunctionException ex) {
-      ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
-          .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(ex.getMessage());
-      return (ResultBuilder.buildResult(errorResultData));
-    }
-    String resultStr = ((String) resultList.get(0));
-    if (resultStr.equals("Succeeded in unregistering")) {
-      StringBuilder members = new StringBuilder();
-      for (DistributedMember member : DsMembers) {
-        members.append(member.getId());
-        members.append(",");
-      }
-      return ResultBuilder.createInfoResult("Destroyed " + functionId + " Successfully on "
-          + members.toString().substring(0, members.toString().length() - 1));
-    } else {
-      return ResultBuilder.createInfoResult("Failed in unregistering");
-    }
-  }
-
-  @CliCommand(value = CliStrings.LIST_FUNCTION, help = CliStrings.LIST_FUNCTION__HELP)
-  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION})
-  @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
-  public Result listFunction(
-      @CliOption(key = CliStrings.LIST_FUNCTION__MATCHES,
-          help = CliStrings.LIST_FUNCTION__MATCHES__HELP) String matches,
-      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
-          optionContext = ConverterHint.MEMBERGROUP,
-          help = CliStrings.LIST_FUNCTION__GROUP__HELP) String[] groups,
-      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
-          optionContext = ConverterHint.MEMBERIDNAME,
-          help = CliStrings.LIST_FUNCTION__MEMBER__HELP) String[] members) {
-    TabularResultData tabularData = ResultBuilder.createTabularResultData();
-    boolean accumulatedData = false;
-
-    InternalCache cache = getCache();
-
-    Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, members);
-
-    if (targetMembers.isEmpty()) {
-      return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
-    }
-
-    try {
-      ResultCollector<?, ?> rc =
-          CliUtil.executeFunction(this.listFunctionFunction, new Object[] {matches}, targetMembers);
-      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
-      for (CliFunctionResult result : results) {
-        if (result.getThrowable() != null) {
-          tabularData.accumulate("Member", result.getMemberIdOrName());
-          tabularData.accumulate("Function", "<ERROR: " + result.getThrowable().getMessage() + ">");
-          accumulatedData = true;
-          tabularData.setStatus(Status.ERROR);
-        } else if (result.isSuccessful()) {
-          String[] strings = (String[]) result.getSerializables();
-          Arrays.sort(strings);
-          for (String string : strings) {
-            tabularData.accumulate("Member", result.getMemberIdOrName());
-            tabularData.accumulate("Function", string);
-            accumulatedData = true;
-          }
-        }
-      }
-
-      if (!accumulatedData) {
-        return ResultBuilder
-            .createInfoResult(CliStrings.LIST_FUNCTION__NO_FUNCTIONS_FOUND_ERROR_MESSAGE);
-      }
-      return ResultBuilder.buildResult(tabularData);
-    } catch (VirtualMachineError e) {
-      SystemFailure.initiateFailure(e);
-      throw e;
-    } catch (Throwable th) {
-      SystemFailure.checkFailure();
-      return ResultBuilder.createGemFireErrorResult(
-          "Exception while attempting to list functions: " + th.getMessage());
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/geode/blob/39fff454/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
new file mode 100644
index 0000000..c7fe51b
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.commands;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.ListFunctionFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission;
+
+public class ListFunctionCommand implements GfshCommand {
+  private final ListFunctionFunction listFunctionFunction = new ListFunctionFunction();
+
+  @CliCommand(value = CliStrings.LIST_FUNCTION, help = CliStrings.LIST_FUNCTION__HELP)
+  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION})
+  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
+      operation = ResourcePermission.Operation.READ)
+  public Result listFunction(
+      @CliOption(key = CliStrings.LIST_FUNCTION__MATCHES,
+          help = CliStrings.LIST_FUNCTION__MATCHES__HELP) String matches,
+      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+          optionContext = ConverterHint.MEMBERGROUP,
+          help = CliStrings.LIST_FUNCTION__GROUP__HELP) String[] groups,
+      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+          optionContext = ConverterHint.MEMBERIDNAME,
+          help = CliStrings.LIST_FUNCTION__MEMBER__HELP) String[] members) {
+    TabularResultData tabularData = ResultBuilder.createTabularResultData();
+    boolean accumulatedData = false;
+
+    getCache(); // TODO PSR: Can this safely be removed?
+
+    Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, members);
+
+    if (targetMembers.isEmpty()) {
+      return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+    }
+
+    try {
+      ResultCollector<?, ?> rc =
+          CliUtil.executeFunction(this.listFunctionFunction, new Object[] {matches}, targetMembers);
+      List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+      for (CliFunctionResult result : results) {
+        if (result.getThrowable() != null) {
+          tabularData.accumulate("Member", result.getMemberIdOrName());
+          tabularData.accumulate("Function", "<ERROR: " + result.getThrowable().getMessage() + ">");
+          accumulatedData = true;
+          tabularData.setStatus(Result.Status.ERROR);
+        } else if (result.isSuccessful()) {
+          String[] strings = (String[]) result.getSerializables();
+          Arrays.sort(strings);
+          for (String string : strings) {
+            tabularData.accumulate("Member", result.getMemberIdOrName());
+            tabularData.accumulate("Function", string);
+            accumulatedData = true;
+          }
+        }
+      }
+
+      if (!accumulatedData) {
+        return ResultBuilder
+            .createInfoResult(CliStrings.LIST_FUNCTION__NO_FUNCTIONS_FOUND_ERROR_MESSAGE);
+      }
+      return ResultBuilder.buildResult(tabularData);
+    } catch (VirtualMachineError e) {
+      SystemFailure.initiateFailure(e);
+      throw e;
+    } catch (Throwable th) {
+      SystemFailure.checkFailure();
+      return ResultBuilder.createGemFireErrorResult(
+          "Exception while attempting to list functions: " + th.getMessage());
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/39fff454/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java
index 855947e..da3fc65 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java
@@ -14,9 +14,8 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import java.util.concurrent.Callable;
+
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
@@ -25,14 +24,18 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
-import java.util.concurrent.Callable;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 
 /**
  * The FunctionCommandsController class implements GemFire Management REST API web service endpoints
  * for the Gfsh Function Commands.
  * <p/>
  * 
- * @see org.apache.geode.management.internal.cli.commands.FunctionCommands
+ * @see org.apache.geode.management.internal.cli.commands.DestroyFunctionCommand
+ * @see org.apache.geode.management.internal.cli.commands.ExecuteFunctionCommand
+ * @see org.apache.geode.management.internal.cli.commands.ListFunctionCommand
  * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
  * @see org.springframework.stereotype.Controller
  * @see org.springframework.web.bind.annotation.PathVariable

http://git-wip-us.apache.org/repos/asf/geode/blob/39fff454/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index b19cfd0..e0d13b6 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -184,8 +184,8 @@ public class TestCommand {
         clusterRead);
     createTestCommand("import cluster-configuration --zip-file-name=value.zip", clusterManage);
 
-    // FunctionCommands
-    // createTestCommand("destroy function --id=InterestCalculations", dataManage);
+    // DestroyFunctionCommand, ExecuteFunctionCommand, ListFunctionCommand
+    createTestCommand("destroy function --id=InterestCalculations", dataManage);
     createTestCommand("execute function --id=InterestCalculations --groups=Group1", dataWrite);
     createTestCommand("list functions", clusterRead);
 


[39/47] geode git commit: GEODE-3472: Remove a great deal of commented-out code.

Posted by ds...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/XmlEntity.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/XmlEntity.java b/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/XmlEntity.java
index 00902a9..6789416 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/XmlEntity.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/configuration/domain/XmlEntity.java
@@ -14,25 +14,6 @@
  */
 package org.apache.geode.management.internal.configuration.domain;
 
-import org.apache.commons.lang.StringUtils;
-import org.apache.geode.DataSerializer;
-import org.apache.geode.InternalGemFireError;
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.internal.Assert;
-import org.apache.geode.internal.Version;
-import org.apache.geode.internal.VersionedDataSerializable;
-import org.apache.geode.internal.cache.xmlcache.CacheXml;
-import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.management.internal.configuration.utils.XmlUtils;
-import org.apache.geode.management.internal.configuration.utils.XmlUtils.XPathContext;
-import org.apache.logging.log4j.Logger;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
 import java.io.DataInput;
 import java.io.DataOutput;
 import java.io.IOException;
@@ -43,11 +24,32 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Map.Entry;
+
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactoryConfigurationError;
 import javax.xml.xpath.XPathExpressionException;
 
+import org.apache.commons.lang.StringUtils;
+import org.apache.logging.log4j.Logger;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import org.apache.geode.DataSerializer;
+import org.apache.geode.InternalGemFireError;
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.internal.Assert;
+import org.apache.geode.internal.Version;
+import org.apache.geode.internal.VersionedDataSerializable;
+import org.apache.geode.internal.cache.xmlcache.CacheXml;
+import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.management.internal.configuration.utils.XmlUtils;
+import org.apache.geode.management.internal.configuration.utils.XmlUtils.XPathContext;
+
 /****
  * Domain class for defining a GemFire entity in XML.
  * 
@@ -60,7 +62,7 @@ public class XmlEntity implements VersionedDataSerializable {
   private String type;
   @SuppressWarnings("unused")
   private String parentType;
-  private Map<String, String> attributes = new HashMap<String, String>();
+  private Map<String, String> attributes = new HashMap<>();
   private String xmlDefinition;
   private String searchString;
 
@@ -112,13 +114,10 @@ public class XmlEntity implements VersionedDataSerializable {
    */
   public XmlEntity(final String parentType, final String parentKey, final String parentValue,
       final String childType, final String childKey, final String childValue) {
-    // TODO this should be replaced with a builder.
-    // TODO consider parent as nested XmlEntity type.
     this.parentType = parentType;
     this.type = childType;
     initializeSearchString(parentKey, parentValue, this.prefix, childKey, childValue);
 
-    // no init();
   }
 
   /****
@@ -268,13 +267,10 @@ public class XmlEntity implements VersionedDataSerializable {
     if (attributes.size() > 0) {
       queryStringBuilder.append("[");
       Entry<String, String> attrEntry = attributeIter.next();
-      // queryStringBuilder.append("@").append(attrEntry.getKey()).append("=\"").append(attrEntry.getValue()).append("\"");
       queryStringBuilder.append("@").append(attrEntry.getKey()).append("='")
           .append(attrEntry.getValue()).append("'");
       while (attributeIter.hasNext()) {
         attrEntry = attributeIter.next();
-        // queryStringBuilder.append(" and
-        // @").append(attrEntry.getKey()).append("=\"").append(attrEntry.getValue()).append("\"");
         queryStringBuilder.append(" and @").append(attrEntry.getKey()).append("='")
             .append(attrEntry.getValue()).append("'");
       }
@@ -463,7 +459,7 @@ public class XmlEntity implements VersionedDataSerializable {
     private XmlEntity xmlEntity;
 
     /**
-     * Private contstructor.
+     * Private constructor.
      * 
      * @since GemFire 8.1
      */

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/configuration/messages/ConfigurationRequest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/configuration/messages/ConfigurationRequest.java b/geode-core/src/main/java/org/apache/geode/management/internal/configuration/messages/ConfigurationRequest.java
index ac5e99a..698c68a 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/configuration/messages/ConfigurationRequest.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/configuration/messages/ConfigurationRequest.java
@@ -14,23 +14,24 @@
  */
 package org.apache.geode.management.internal.configuration.messages;
 
-import org.apache.commons.lang.StringUtils;
-import org.apache.geode.internal.DataSerializableFixedID;
-import org.apache.geode.internal.Version;
-
 import java.io.DataInput;
 import java.io.DataOutput;
 import java.io.IOException;
 import java.util.HashSet;
 import java.util.Set;
 
+import org.apache.commons.lang.StringUtils;
+
+import org.apache.geode.internal.DataSerializableFixedID;
+import org.apache.geode.internal.Version;
+
 /***
  * Request sent by a member to the locator requesting the shared configuration
  *
  */
 public class ConfigurationRequest implements DataSerializableFixedID {
   private static int DEFAULT_NUM_ATTEMPTS = 5;
-  private Set<String> groups = new HashSet<String>();
+  private Set<String> groups = new HashSet<>();
   private boolean isRequestForEntireConfiguration = false;
   private int numAttempts = DEFAULT_NUM_ATTEMPTS;
 
@@ -74,7 +75,7 @@ public class ConfigurationRequest implements DataSerializableFixedID {
   public void fromData(DataInput in) throws IOException, ClassNotFoundException {
     this.isRequestForEntireConfiguration = in.readBoolean();
     int size = in.readInt();
-    Set<String> groups = new HashSet<String>();
+    Set<String> groups = new HashSet<>();
     if (size > 0) {
       for (int i = 0; i < size; i++) {
         groups.add(in.readUTF());
@@ -105,11 +106,8 @@ public class ConfigurationRequest implements DataSerializableFixedID {
     return sb.toString();
   }
 
-  // TODO Sourabh, please review for correctness
-  // Asif: Returning null, as otherwise backward compatibility tests fail
-  // due to missing pre to & from data functions.
   public Version[] getSerializationVersions() {
-    return null;// new Version[] { Version.CURRENT };
+    return null;
   }
 
   public int getNumAttempts() {

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/configuration/utils/XmlUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/configuration/utils/XmlUtils.java b/geode-core/src/main/java/org/apache/geode/management/internal/configuration/utils/XmlUtils.java
index f86b9a3..63aa1ec 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/configuration/utils/XmlUtils.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/configuration/utils/XmlUtils.java
@@ -19,19 +19,6 @@ import static javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI;
 import static org.apache.geode.management.internal.configuration.utils.XmlConstants.W3C_XML_SCHEMA_INSTANCE_ATTRIBUTE_SCHEMA_LOCATION;
 import static org.apache.geode.management.internal.configuration.utils.XmlConstants.W3C_XML_SCHEMA_INSTANCE_PREFIX;
 
-import org.apache.commons.lang.StringUtils;
-import org.apache.geode.internal.cache.xmlcache.CacheXml;
-import org.apache.geode.internal.cache.xmlcache.CacheXmlParser;
-import org.apache.geode.management.internal.configuration.domain.CacheElement;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
 import java.io.IOException;
 import java.io.Reader;
 import java.io.StringReader;
@@ -45,6 +32,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.StringTokenizer;
+
 import javax.xml.namespace.NamespaceContext;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
@@ -61,6 +49,20 @@ import javax.xml.xpath.XPathConstants;
 import javax.xml.xpath.XPathExpressionException;
 import javax.xml.xpath.XPathFactory;
 
+import org.apache.commons.lang.StringUtils;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import org.apache.geode.internal.cache.xmlcache.CacheXml;
+import org.apache.geode.internal.cache.xmlcache.CacheXmlParser;
+import org.apache.geode.management.internal.configuration.domain.CacheElement;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+
 public class XmlUtils {
 
   /**
@@ -75,7 +77,7 @@ public class XmlUtils {
    */
   public static Document createDocumentFromReader(final Reader reader)
       throws SAXException, ParserConfigurationException, IOException {
-    Document doc = null;
+    Document doc;
     InputSource inputSource = new InputSource(reader);
 
     doc = getDocumentBuilder().parse(inputSource);
@@ -148,7 +150,6 @@ public class XmlUtils {
         final String namespace = childElement.getNamespaceURI();
 
         if (namespace.equals(xmlEntity.getNamespace()) && type.equals(xmlEntity.getType())) {
-          // TODO this should really be checking all attributes in xmlEntity.getAttributes
           // First check if the element has a name
           String nameOrId = getAttribute(childElement, "name");
           // If not then check if the element has an Id
@@ -233,15 +234,15 @@ public class XmlUtils {
    * Creates a node from the String xml definition
    * 
    * @param owner
-   * @param xmlDefintion
+   * @param xmlDefinition
    * @return Node representing the xml definition
    * @throws ParserConfigurationException
    * @throws IOException
    * @throws SAXException
    */
-  private static Node createNode(Document owner, String xmlDefintion)
+  private static Node createNode(Document owner, String xmlDefinition)
       throws SAXException, IOException, ParserConfigurationException {
-    InputSource inputSource = new InputSource(new StringReader(xmlDefintion));
+    InputSource inputSource = new InputSource(new StringReader(xmlDefinition));
     Document document = getDocumentBuilder().parse(inputSource);
     Node newNode = document.getDocumentElement();
     return owner.importNode(newNode, true);
@@ -279,7 +280,7 @@ public class XmlUtils {
    * @since GemFire 8.1
    */
   public static Map<String, List<String>> buildSchemaLocationMap(final String schemaLocation) {
-    return buildSchemaLocationMap(new HashMap<String, List<String>>(), schemaLocation);
+    return buildSchemaLocationMap(new HashMap<>(), schemaLocation);
   }
 
   /**
@@ -296,12 +297,7 @@ public class XmlUtils {
    */
   static Map<String, List<String>> buildSchemaLocationMap(
       Map<String, List<String>> schemaLocationMap, final String schemaLocation) {
-    if (null == schemaLocation) {
-      return schemaLocationMap;
-    }
-
     if (null == schemaLocation || schemaLocation.isEmpty()) {
-      // should really ever be null but being safe.
       return schemaLocationMap;
     }
 
@@ -323,7 +319,7 @@ public class XmlUtils {
   }
 
   /*****
-   * Deletes all the node from the document which match the definition provided by xmlentity
+   * Deletes all the node from the document which match the definition provided by xmlEntity
    * 
    * @param doc
    * @param xmlEntity
@@ -366,8 +362,8 @@ public class XmlUtils {
    *
    */
   public static class XPathContext implements NamespaceContext {
-    private HashMap<String, String> prefixToUri = new HashMap<String, String>();
-    private HashMap<String, String> uriToPrefix = new HashMap<String, String>();
+    private HashMap<String, String> prefixToUri = new HashMap<>();
+    private HashMap<String, String> uriToPrefix = new HashMap<>();
 
 
     public XPathContext() {}
@@ -408,7 +404,7 @@ public class XmlUtils {
    * @throws TransformerFactoryConfigurationError
    */
   public static String prettyXml(Node doc)
-      throws IOException, TransformerFactoryConfigurationError, TransformerException {
+      throws TransformerFactoryConfigurationError, TransformerException {
     Transformer transformer = TransformerFactory.newInstance().newTransformer();
     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
 
@@ -428,8 +424,7 @@ public class XmlUtils {
     DOMSource source = new DOMSource(element);
     transformer.transform(source, result);
 
-    String xmlString = result.getWriter().toString();
-    return xmlString;
+    return result.getWriter().toString();
   }
 
   /****
@@ -510,7 +505,6 @@ public class XmlUtils {
     }
 
     if (null != document.getDoctype()) {
-      // doc.setDocType(null);
       Node root = document.getDocumentElement();
 
       Document copiedDocument = getDocumentBuilder().newDocument();
@@ -551,7 +545,7 @@ public class XmlUtils {
         buildSchemaLocationMap(schemaLocationAttribute);
     List<String> schemaLocations = schemaLocationMap.get(namespaceUri);
     if (null == schemaLocations) {
-      schemaLocations = new ArrayList<String>();
+      schemaLocations = new ArrayList<>();
       schemaLocationMap.put(namespaceUri, schemaLocations);
     }
     schemaLocations.clear();
@@ -665,7 +659,7 @@ public class XmlUtils {
    * @param xmlEntity xml entity for the root , it also contains the attributes
    * @throws IOException
    */
-  public static void modifyRootAttributes(Document doc, XmlEntity xmlEntity) throws IOException {
+  public static void modifyRootAttributes(Document doc, XmlEntity xmlEntity) {
     if (xmlEntity == null || xmlEntity.getAttributes() == null) {
       return;
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DataCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DataCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DataCommandsController.java
index ce7ebfc..8a16aa4 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DataCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DataCommandsController.java
@@ -16,6 +16,7 @@ package org.apache.geode.management.internal.web.controllers;
 
 import java.util.concurrent.Callable;
 
+import org.apache.commons.lang.StringUtils;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
@@ -25,7 +26,6 @@ import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.context.request.WebRequest;
 
-import org.apache.geode.internal.lang.StringUtils;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 
@@ -194,7 +194,6 @@ public class DataCommandsController extends AbstractCommandsController {
       @RequestParam(CliStrings.QUERY__QUERY) final String oql,
       @RequestParam(value = CliStrings.QUERY__INTERACTIVE,
           defaultValue = "true") final Boolean interactive) {
-    // logRequest(request);
 
     final CommandStringBuilder command = new CommandStringBuilder(CliStrings.QUERY);
 
@@ -219,12 +218,12 @@ public class DataCommandsController extends AbstractCommandsController {
 
     if (hasValue(includedRegions)) {
       command.addOption(CliStrings.REBALANCE__INCLUDEREGION,
-          StringUtils.join(includedRegions, StringUtils.COMMA_DELIMITER));
+          StringUtils.join(includedRegions, ","));
     }
 
     if (hasValue(excludedRegions)) {
       command.addOption(CliStrings.REBALANCE__EXCLUDEREGION,
-          StringUtils.join(excludedRegions, StringUtils.COMMA_DELIMITER));
+          StringUtils.join(excludedRegions, ","));
     }
 
     command.addOption(CliStrings.REBALANCE__SIMULATE, String.valueOf(simulate));

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
index 815bc47..9180414 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
@@ -14,6 +14,7 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
+import org.apache.commons.lang.StringUtils;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -22,7 +23,6 @@ import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.context.request.WebRequest;
 
-import org.apache.geode.internal.lang.StringUtils;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 
@@ -108,14 +108,13 @@ public class RegionCommandsController extends AbstractCommandsController {
           required = false) final Boolean enableCloning,
       @RequestParam(value = CliStrings.ALTER_REGION__EVICTIONMAX,
           required = false) final Integer evictionMax) {
-    // logRequest(request);
 
     final CommandStringBuilder command = new CommandStringBuilder(CliStrings.ALTER_REGION);
 
     command.addOption(CliStrings.ALTER_REGION__REGION, decode(regionNamePath));
 
     if (hasValue(groups)) {
-      command.addOption(CliStrings.GROUP, StringUtils.join(groups, StringUtils.COMMA_DELIMITER));
+      command.addOption(CliStrings.GROUP, StringUtils.join(groups, ","));
     }
 
     addCommandOption(request, command, CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME,
@@ -240,7 +239,7 @@ public class RegionCommandsController extends AbstractCommandsController {
     }
 
     if (hasValue(groups)) {
-      command.addOption(CliStrings.GROUP, StringUtils.join(groups, StringUtils.COMMA_DELIMITER));
+      command.addOption(CliStrings.GROUP, StringUtils.join(groups, ","));
     }
 
     command.addOption(CliStrings.CREATE_REGION__SKIPIFEXISTS,
@@ -320,7 +319,7 @@ public class RegionCommandsController extends AbstractCommandsController {
 
     if (hasValue(cacheListeners)) {
       command.addOption(CliStrings.CREATE_REGION__CACHELISTENER,
-          StringUtils.join(cacheListeners, StringUtils.COMMA_DELIMITER));
+          StringUtils.join(cacheListeners, ","));
     }
 
     if (hasValue(cacheLoader)) {
@@ -333,12 +332,12 @@ public class RegionCommandsController extends AbstractCommandsController {
 
     if (hasValue(asyncEventQueueIds)) {
       command.addOption(CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID,
-          StringUtils.join(asyncEventQueueIds, StringUtils.COMMA_DELIMITER));
+          StringUtils.join(asyncEventQueueIds, ","));
     }
 
     if (hasValue(gatewaySenderIds)) {
       command.addOption(CliStrings.CREATE_REGION__GATEWAYSENDERID,
-          StringUtils.join(gatewaySenderIds, StringUtils.COMMA_DELIMITER));
+          StringUtils.join(gatewaySenderIds, ","));
     }
 
     if (Boolean.TRUE.equals(enableConcurrencyChecks)) {

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java
index e983f2a..63413b0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ShellCommandsController.java
@@ -14,15 +14,15 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
+import java.io.IOException;
+import java.util.Set;
+
+import javax.management.AttributeNotFoundException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
 import org.apache.commons.lang.ArrayUtils;
-import org.apache.geode.internal.GemFireVersion;
-import org.apache.geode.internal.lang.ObjectUtils;
-import org.apache.geode.internal.util.IOUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.web.domain.Link;
-import org.apache.geode.management.internal.web.domain.LinkIndex;
-import org.apache.geode.management.internal.web.domain.QueryParameterSource;
-import org.apache.geode.management.internal.web.http.HttpMethod;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
@@ -33,12 +33,14 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
-import java.io.IOException;
-import java.util.Set;
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
+import org.apache.geode.internal.GemFireVersion;
+import org.apache.geode.internal.lang.ObjectUtils;
+import org.apache.geode.internal.util.IOUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.web.domain.Link;
+import org.apache.geode.management.internal.web.domain.LinkIndex;
+import org.apache.geode.management.internal.web.domain.QueryParameterSource;
+import org.apache.geode.management.internal.web.http.HttpMethod;
 
 /**
  * The ShellCommandsController class implements GemFire REST API calls for Gfsh Shell Commands.
@@ -69,7 +71,6 @@ public class ShellCommandsController extends AbstractCommandsController {
     return processCommand(decode(command));
   }
 
-  // TODO research the use of Jolokia instead
   @RequestMapping(method = RequestMethod.GET, value = "/mbean/attribute")
   public ResponseEntity<?> getAttribute(@RequestParam("resourceName") final String resourceName,
       @RequestParam("attributeName") final String attributeName) {
@@ -77,19 +78,16 @@ public class ShellCommandsController extends AbstractCommandsController {
       final Object attributeValue = getMBeanServer()
           .getAttribute(ObjectName.getInstance(decode(resourceName)), decode(attributeName));
 
-      return new ResponseEntity<byte[]>(IOUtils.serializeObject(attributeValue), HttpStatus.OK);
-    } catch (AttributeNotFoundException e) {
-      return new ResponseEntity<String>(printStackTrace(e), HttpStatus.BAD_REQUEST);
+      return new ResponseEntity<>(IOUtils.serializeObject(attributeValue), HttpStatus.OK);
+    } catch (AttributeNotFoundException | MalformedObjectNameException e) {
+      return new ResponseEntity<>(printStackTrace(e), HttpStatus.BAD_REQUEST);
     } catch (InstanceNotFoundException e) {
-      return new ResponseEntity<String>(printStackTrace(e), HttpStatus.NOT_FOUND);
-    } catch (MalformedObjectNameException e) {
-      return new ResponseEntity<String>(printStackTrace(e), HttpStatus.BAD_REQUEST);
+      return new ResponseEntity<>(printStackTrace(e), HttpStatus.NOT_FOUND);
     } catch (Exception e) {
-      return new ResponseEntity<String>(printStackTrace(e), HttpStatus.INTERNAL_SERVER_ERROR);
+      return new ResponseEntity<>(printStackTrace(e), HttpStatus.INTERNAL_SERVER_ERROR);
     }
   }
 
-  // TODO research the use of Jolokia instead
   @RequestMapping(method = RequestMethod.POST, value = "/mbean/operation")
   public ResponseEntity<?> invoke(@RequestParam("resourceName") final String resourceName,
       @RequestParam("operationName") final String operationName,
@@ -102,13 +100,13 @@ public class ShellCommandsController extends AbstractCommandsController {
       final Object result = getMBeanServer().invoke(ObjectName.getInstance(decode(resourceName)),
           decode(operationName), parameters, signature);
 
-      return new ResponseEntity<byte[]>(IOUtils.serializeObject(result), HttpStatus.OK);
+      return new ResponseEntity<>(IOUtils.serializeObject(result), HttpStatus.OK);
     } catch (InstanceNotFoundException e) {
-      return new ResponseEntity<String>(printStackTrace(e), HttpStatus.NOT_FOUND);
+      return new ResponseEntity<>(printStackTrace(e), HttpStatus.NOT_FOUND);
     } catch (MalformedObjectNameException e) {
-      return new ResponseEntity<String>(printStackTrace(e), HttpStatus.BAD_REQUEST);
+      return new ResponseEntity<>(printStackTrace(e), HttpStatus.BAD_REQUEST);
     } catch (Exception e) {
-      return new ResponseEntity<String>(printStackTrace(e), HttpStatus.INTERNAL_SERVER_ERROR);
+      return new ResponseEntity<>(printStackTrace(e), HttpStatus.INTERNAL_SERVER_ERROR);
     }
   }
 
@@ -118,9 +116,9 @@ public class ShellCommandsController extends AbstractCommandsController {
       final Set<ObjectName> objectNames =
           getMBeanServer().queryNames(query.getObjectName(), query.getQueryExpression());
 
-      return new ResponseEntity<byte[]>(IOUtils.serializeObject(objectNames), HttpStatus.OK);
+      return new ResponseEntity<>(IOUtils.serializeObject(objectNames), HttpStatus.OK);
     } catch (IOException e) {
-      return new ResponseEntity<String>(printStackTrace(e), HttpStatus.INTERNAL_SERVER_ERROR);
+      return new ResponseEntity<>(printStackTrace(e), HttpStatus.INTERNAL_SERVER_ERROR);
     }
   }
 
@@ -135,16 +133,11 @@ public class ShellCommandsController extends AbstractCommandsController {
    * @see org.apache.geode.management.internal.web.domain.LinkIndex
    * @see org.apache.geode.management.internal.web.http.HttpMethod
    */
-  // TODO figure out a better way to maintain this link index, such as using an automated way to
-  // introspect
-  // the Spring Web MVC Controller RequestMapping Annotations.
   @RequestMapping(method = RequestMethod.GET, value = "/index",
       produces = MediaType.APPLICATION_XML_VALUE)
   @ResponseBody
   public LinkIndex index(@RequestParam(value = "scheme", required = false,
       defaultValue = "http") final String scheme) {
-    // logger.warning(String.format("Returning Link Index for Context Path (%1$s).",
-    // ServletUriComponentsBuilder.fromCurrentContextPath().build().toString()));
     return new LinkIndex()
         // Cluster Commands
         .add(new Link(CliStrings.STATUS_SHARED_CONFIG, toUri("/services/cluster-config", scheme)))
@@ -293,7 +286,7 @@ public class ShellCommandsController extends AbstractCommandsController {
 
   @RequestMapping(method = {RequestMethod.GET, RequestMethod.HEAD}, value = "/ping")
   public ResponseEntity<String> ping() {
-    return new ResponseEntity<String>("<html><body><h1>Mischief Managed!</h1></body></html>",
+    return new ResponseEntity<>("<html><body><h1>Mischief Managed!</h1></body></html>",
         HttpStatus.OK);
   }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/fb9a405f/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java
index a0788a0..3bda1c0 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/FunctionCommandsDUnitTest.java
@@ -41,7 +41,6 @@ import org.apache.geode.management.DistributedRegionMXBean;
 import org.apache.geode.management.ManagementService;
 import org.apache.geode.management.cli.Result;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.json.GfJsonException;
 import org.apache.geode.management.internal.cli.result.CommandResult;
 import org.apache.geode.management.internal.cli.result.TabularResultData;
 import org.apache.geode.test.dunit.Host;
@@ -227,7 +226,7 @@ public class FunctionCommandsDUnitTest extends CliCommandTestBase {
   SerializableRunnable checkRegionMBeans = new SerializableRunnable() {
     @Override
     public void run() {
-      final WaitCriterion waitForMaangerMBean = new WaitCriterion() {
+      final WaitCriterion waitForManagerMBean = new WaitCriterion() {
         @Override
         public boolean done() {
           final ManagementService service = ManagementService.getManagementService(getCache());
@@ -247,7 +246,7 @@ public class FunctionCommandsDUnitTest extends CliCommandTestBase {
           return "Probing for testExecuteFunctionOnRegionBug51480";
         }
       };
-      waitForCriterion(waitForMaangerMBean, 2 * 60 * 1000, 2000, true);
+      waitForCriterion(waitForManagerMBean, 2 * 60 * 1000, 2000, true);
       DistributedRegionMXBean bean = ManagementService.getManagementService(getCache())
           .getDistributedRegionMXBean(Region.SEPARATOR + REGION_ONE);
       assertNotNull(bean);
@@ -294,7 +293,7 @@ public class FunctionCommandsDUnitTest extends CliCommandTestBase {
     Function function = new TestFunction(true, TestFunction.TEST_FUNCTION1);
     FunctionService.registerFunction(function);
     final VM vm1 = Host.getHost(0).getVM(1);
-    final String vm1MemberId = (String) vm1.invoke(() -> getMemberId());
+    final String vm1MemberId = vm1.invoke(this::getMemberId);
 
     Host.getHost(0).getVM(0).invoke(new SerializableRunnable() {
       public void run() {
@@ -494,7 +493,7 @@ public class FunctionCommandsDUnitTest extends CliCommandTestBase {
     Function function = new TestFunction(true, TestFunction.TEST_FUNCTION1);
     FunctionService.registerFunction(function);
     final VM vm1 = Host.getHost(0).getVM(1);
-    final String vm1MemberId = (String) vm1.invoke(() -> getMemberId());
+    final String vm1MemberId = vm1.invoke(this::getMemberId);
     String command = "destroy function --id=" + function.getId() + " --member=" + vm1MemberId;
     getLogWriter().info("testDestroyOnMember command=" + command);
     CommandResult cmdResult = executeCommand(command);
@@ -560,13 +559,9 @@ public class FunctionCommandsDUnitTest extends CliCommandTestBase {
     CommandResult cmdResult = executeCommand(command);
     getLogWriter().info("testDestroyOnGroups cmdResult=" + cmdResult);
     assertEquals(Result.Status.OK, cmdResult.getStatus());
-    String content = null;
-    try {
-      content = cmdResult.getContent().get("message").toString();
-      getLogWriter().info("testDestroyOnGroups content = " + content);
-    } catch (GfJsonException e) {
-      fail("testDestroyOnGroups exception=" + e);
-    }
+    String content;
+    content = cmdResult.getContent().get("message").toString();
+    getLogWriter().info("testDestroyOnGroups content = " + content);
     assertNotNull(content);
     assertTrue(content
         .equals("[\"Destroyed " + TestFunction.TEST_FUNCTION1 + " Successfully on " + vm1id + ","


[27/47] geode git commit: GEODE-3436: Suggested improvements to touched files.

Posted by ds...@apache.org.
GEODE-3436: Suggested improvements to touched files.

* this closes #745


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

Branch: refs/heads/feature/GEODE-3543
Commit: be8a135681d2fe156559c2dd60a501beb07b1ab8
Parents: 851932e
Author: Patrick Rhomberg <pr...@pivotal.io>
Authored: Fri Aug 25 17:18:17 2017 -0700
Committer: Jinmei Liao <ji...@pivotal.io>
Committed: Tue Aug 29 09:29:22 2017 -0700

----------------------------------------------------------------------
 .../org/apache/geode/BundledJarsJUnitTest.java  | 10 +++----
 .../commands/CreateDefinedIndexesCommand.java   |  3 --
 .../cli/commands/CreateIndexCommand.java        |  3 --
 .../cli/commands/CreateRegionCommand.java       |  8 +++---
 .../cli/commands/ExecuteFunctionCommand.java    |  1 -
 .../cli/commands/ExportStackTraceCommand.java   | 25 ----------------
 .../internal/cli/commands/GfshHelpCommand.java  |  6 ++--
 .../cli/commands/ListFunctionCommand.java       |  2 --
 .../cli/commands/ShowMetricsCommand.java        |  7 +++--
 .../internal/cli/commands/ShutdownCommand.java  | 24 +++++++---------
 .../StatusClusterConfigServiceCommand.java      |  2 +-
 .../cli/functions/RegionCreateFunction.java     | 15 ++++------
 .../web/controllers/PdxCommandsController.java  |  7 +++--
 .../controllers/RegionCommandsController.java   |  7 +++--
 .../geode/redis/internal/RegionProvider.java    | 14 ++++-----
 .../commands/AlterRegionCommandDUnitTest.java   |  6 ++--
 ...eateAlterDestroyRegionCommandsDUnitTest.java |  7 ++---
 .../commands/CreateRegionCommandDUnitTest.java  | 30 ++++++--------------
 .../commands/DestroyRegionCommandDUnitTest.java | 10 +++----
 .../commands/DiskStoreCommandsDUnitTest.java    |  4 +--
 .../cli/commands/ListIndexCommandDUnitTest.java |  2 +-
 .../cli/commands/ListIndexCommandJUnitTest.java |  4 +--
 .../cli/commands/ShowDeadlockDUnitTest.java     |  1 -
 .../internal/security/TestCommand.java          |  7 -----
 24 files changed, 70 insertions(+), 135 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java b/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
index 3a5538c..8e99a7a 100644
--- a/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
@@ -57,13 +57,13 @@ public class BundledJarsJUnitTest {
     TreeMap<String, String> sortedJars = getBundledJars();
     Stream<String> lines =
         sortedJars.entrySet().stream().map(entry -> removeVersion(entry.getKey()));
-    Set<String> bundledJarNames = new TreeSet<String>(lines.collect(Collectors.toSet()));
+    Set<String> bundledJarNames = new TreeSet<>(lines.collect(Collectors.toSet()));
 
     Files.write(Paths.get("bundled_jars.txt"), bundledJarNames);
 
-    TreeSet<String> newJars = new TreeSet<String>(bundledJarNames);
+    TreeSet<String> newJars = new TreeSet<>(bundledJarNames);
     newJars.removeAll(expectedJars);
-    TreeSet<String> missingJars = new TreeSet<String>(expectedJars);
+    TreeSet<String> missingJars = new TreeSet<>(expectedJars);
     missingJars.removeAll(bundledJarNames);
 
     String message =
@@ -89,11 +89,11 @@ public class BundledJarsJUnitTest {
         geodeHomeDirectory.isDirectory());
 
     Collection<File> jars = FileUtils.listFiles(geodeHomeDirectory, new String[] {"jar"}, true);
-    TreeMap<String, String> sortedJars = new TreeMap<String, String>();
+    TreeMap<String, String> sortedJars = new TreeMap<>();
     jars.forEach(jar -> sortedJars.put(jar.getName(), jar.getPath()));
 
     Collection<File> wars = FileUtils.listFiles(geodeHomeDirectory, new String[] {"war"}, true);
-    TreeSet<File> sortedWars = new TreeSet<File>(wars);
+    TreeSet<File> sortedWars = new TreeSet<>(wars);
     sortedWars.stream().flatMap(BundledJarsJUnitTest::extractJarNames)
         .forEach(jar -> sortedJars.put(jar.getName(), jar.getPath()));
 

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
index 3487279..0b34a26 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
@@ -25,7 +25,6 @@ import java.util.concurrent.atomic.AtomicReference;
 import org.springframework.shell.core.annotation.CliCommand;
 import org.springframework.shell.core.annotation.CliOption;
 
-import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.execute.ResultCollector;
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.management.cli.CliMetaData;
@@ -77,8 +76,6 @@ public class CreateDefinedIndexesCommand implements GfshCommand {
         return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
       }
 
-      // TODO PSR: is this safe to remove?
-      CacheFactory.getAnyInstance();
       final ResultCollector<?, ?> rc = CliUtil.executeFunction(createDefinedIndexesFunction,
           IndexDefinition.indexDefinitions, targetMembers);
 

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
index 5bae92d..6f379d7 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
@@ -25,7 +25,6 @@ import java.util.concurrent.atomic.AtomicReference;
 import org.springframework.shell.core.annotation.CliCommand;
 import org.springframework.shell.core.annotation.CliOption;
 
-import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.execute.ResultCollector;
 import org.apache.geode.distributed.DistributedMember;
@@ -79,8 +78,6 @@ public class CreateIndexCommand implements GfshCommand {
     AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
 
     try {
-      // TODO PSR: Is this safe to remove?
-      CacheFactory.getAnyInstance();
       int idxType;
 
       // Index type check

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
index 294e4f3..88c032a 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
@@ -204,7 +204,7 @@ public class CreateRegionCommand implements GfshCommand {
         if (!regionExists(cache, useAttributesFrom)) {
           throw new IllegalArgumentException(CliStrings.format(
               CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
-              new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
+              CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom));
         }
 
         FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult =
@@ -349,7 +349,7 @@ public class CreateRegionCommand implements GfshCommand {
       if (!regionExists(cache, useAttributesFrom)) { // check already done in createRegion !!!
         throw new IllegalArgumentException(CliStrings.format(
             CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
-            new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
+            CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom));
       }
       if (!regionFunctionArgs.isSetUseAttributesFrom()
           || regionFunctionArgs.getRegionAttributes() == null) {
@@ -374,7 +374,7 @@ public class CreateRegionCommand implements GfshCommand {
         if (foundRegionPath == null) {
           throw new IllegalArgumentException(CliStrings.format(
               CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
-              new Object[] {CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith}));
+              CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith));
         }
         ManagementService mgmtService = ManagementService.getExistingManagementService(cache);
         DistributedRegionMXBean distributedRegionMXBean =
@@ -606,7 +606,7 @@ public class CreateRegionCommand implements GfshCommand {
               LogWrapper.getInstance().info(CliUtil.stackTraceAsString((th)));
               throw new IllegalArgumentException(CliStrings.format(
                   CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1,
-                  new Object[] {regionPath, th.getMessage()}));
+                  regionPath, th.getMessage()));
             } else { // has to be RegionAttributes
               @SuppressWarnings("unchecked") // to avoid warning :(
               FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> regAttr =

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
index a016ccf..46ad6e5 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
@@ -132,7 +132,6 @@ public class ExecuteFunctionCommand implements GfshCommand {
         // if user wish to execute on locator then he can choose --member or --group option
         Set<DistributedMember> dsMembers = CliUtil.getAllNormalMembers(cache);
         if (dsMembers.size() > 0) {
-          new UserFunctionExecution();
           LogWrapper.getInstance().info(CliStrings
               .format(CliStrings.EXECUTE_FUNCTION__MSG__EXECUTING_0_ON_ENTIRE_DS, functionId));
           for (DistributedMember member : dsMembers) {

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
index a5749ca..4f8693d 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
@@ -38,9 +38,7 @@ import org.apache.geode.internal.cache.InternalCache;
 import org.apache.geode.management.cli.CliMetaData;
 import org.apache.geode.management.cli.ConverterHint;
 import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
 import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
 import org.apache.geode.management.internal.cli.domain.StackTracesPerMember;
 import org.apache.geode.management.internal.cli.functions.GetStackTracesFunction;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
@@ -121,29 +119,6 @@ public class ExportStackTraceCommand implements GfshCommand {
     return result;
   }
 
-  // TODO PSR: ExportStackTrace Interceptor appeared to exist, but was not hooked to command and has
-  // a clearly incorrect javadoc.
-  // TODO PSR: It appears it was introduced in 2016-11-26: 903135115a0466d86fa663e965ace3ff47eba6b4,
-  // but never correctly linked to the command.
-  public static class ExportStackTraceInterceptor extends AbstractCliAroundInterceptor {
-    @Override
-    public Result preExecution(GfshParseResult parseResult) {
-
-      Map<String, String> paramValueMap = parseResult.getParamValueStrings();
-      String fileName = paramValueMap.get(CliStrings.EXPORT_STACKTRACE__FILE);
-
-      Response response = readYesNo(
-          CliStrings.format(CliStrings.EXPORT_STACKTRACE_WARN_USER, fileName), Response.YES);
-      if (response == Response.NO) {
-        return ResultBuilder
-            .createShellClientAbortOperationResult(CliStrings.EXPORT_STACKTRACE_MSG_ABORTING);
-      } else {
-        // we don't to show any info result
-        return ResultBuilder.createInfoResult("");
-      }
-    }
-  }
-
   /***
    * Writes the Stack traces member-wise to a text file
    *

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
index 1161f65..5b39647 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
@@ -15,6 +15,9 @@
 
 package org.apache.geode.management.internal.cli.commands;
 
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
 import org.apache.geode.management.cli.CliMetaData;
 import org.apache.geode.management.cli.ConverterHint;
 import org.apache.geode.management.cli.Result;
@@ -22,9 +25,6 @@ import org.apache.geode.management.internal.cli.CommandManager;
 import org.apache.geode.management.internal.cli.CommandManagerAware;
 import org.apache.geode.management.internal.cli.i18n.CliStrings;
 import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.springframework.shell.core.CommandMarker;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
 
 public class GfshHelpCommand implements GfshCommand, CommandManagerAware {
   private CommandManager commandManager = null;

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
index c7fe51b..86b8985 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
@@ -56,8 +56,6 @@ public class ListFunctionCommand implements GfshCommand {
     TabularResultData tabularData = ResultBuilder.createTabularResultData();
     boolean accumulatedData = false;
 
-    getCache(); // TODO PSR: Can this safely be removed?
-
     Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, members);
 
     if (targetMembers.isEmpty()) {

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
index 7555a62..6236b38 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
@@ -23,6 +23,7 @@ import java.util.Set;
 
 import javax.management.ObjectName;
 
+import org.apache.commons.lang.StringUtils;
 import org.apache.logging.log4j.Logger;
 import org.springframework.shell.core.annotation.CliCommand;
 import org.springframework.shell.core.annotation.CliOption;
@@ -54,7 +55,7 @@ import org.apache.geode.management.internal.security.ResourceOperation;
 import org.apache.geode.security.ResourcePermission;
 
 public class ShowMetricsCommand implements GfshCommand {
-  private final static Logger logger = LogService.getLogger();
+  private static final Logger logger = LogService.getLogger();
 
   @CliCommand(value = CliStrings.SHOW_METRICS, help = CliStrings.SHOW_METRICS__HELP)
   @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_STATISTICS})
@@ -83,7 +84,7 @@ public class ShowMetricsCommand implements GfshCommand {
       }
       if (regionName != null && !regionName.isEmpty()) {
 
-        if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
+        if (StringUtils.isNotBlank(cacheServerPortString)) {
           return ResultBuilder
               .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
         }
@@ -130,7 +131,7 @@ public class ShowMetricsCommand implements GfshCommand {
           result = ResultBuilder.buildResult(erd);
         }
       } else {
-        if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
+        if (StringUtils.isNotBlank(cacheServerPortString)) {
           return ResultBuilder
               .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
         }

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
index fcee9d8..c89331a 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
@@ -48,8 +48,8 @@ import org.apache.geode.management.internal.security.ResourceOperation;
 import org.apache.geode.security.ResourcePermission;
 
 public class ShutdownCommand implements GfshCommand {
-  private final static String DEFAULT_TIME_OUT = "10";
-  private final static Logger logger = LogService.getLogger();
+  private static final String DEFAULT_TIME_OUT = "10";
+  private static final Logger logger = LogService.getLogger();
 
   @CliCommand(value = CliStrings.SHUTDOWN, help = CliStrings.SHUTDOWN__HELP)
   @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_LIFECYCLE},
@@ -158,19 +158,15 @@ public class ShutdownCommand implements GfshCommand {
     try {
       final Function shutDownFunction = new ShutDownFunction();
       logger.info("Gfsh executing shutdown on members " + includeMembers);
-      Callable<String> shutdownNodes = new Callable<String>() {
-
-        @Override
-        public String call() {
-          try {
-            Execution execution = FunctionService.onMembers(includeMembers);
-            execution.execute(shutDownFunction);
-          } catch (FunctionException functionEx) {
-            // Expected Exception as the function is shutting down the target members and the result
-            // collector will get member departed exception
-          }
-          return "SUCCESS";
+      Callable<String> shutdownNodes = () -> {
+        try {
+          Execution execution = FunctionService.onMembers(includeMembers);
+          execution.execute(shutDownFunction);
+        } catch (FunctionException functionEx) {
+          // Expected Exception as the function is shutting down the target members and the result
+          // collector will get member departed exception
         }
+        return "SUCCESS";
       };
       Future<String> result = exec.submit(shutdownNodes);
       result.get(timeout, TimeUnit.MILLISECONDS);

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
index 6a0fc1e..fd4eee0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
@@ -48,7 +48,7 @@ public class StatusClusterConfigServiceCommand implements GfshCommand {
   @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
   public Result statusSharedConfiguration() {
     final InternalCache cache = GemFireCacheImpl.getInstance();
-    final Set<DistributedMember> locators = new HashSet<DistributedMember>(
+    final Set<DistributedMember> locators = new HashSet<>(
         cache.getDistributionManager().getAllHostedLocatorsWithSharedConfiguration().keySet());
     if (locators.isEmpty()) {
       return ResultBuilder.createInfoResult(CliStrings.NO_LOCATORS_WITH_SHARED_CONFIG);

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
index 45cb104..4b205ce 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
@@ -94,7 +94,7 @@ public class RegionCreateFunction extends FunctionAdapter implements InternalEnt
       XmlEntity xmlEntity = new XmlEntity(CacheXml.REGION, "name", createdRegion.getName());
       resultSender.lastResult(new CliFunctionResult(memberNameOrId, xmlEntity,
           CliStrings.format(CliStrings.CREATE_REGION__MSG__REGION_0_CREATED_ON_1,
-              new Object[] {createdRegion.getFullPath(), memberNameOrId})));
+              createdRegion.getFullPath(), memberNameOrId)));
     } catch (IllegalStateException e) {
       String exceptionMsg = e.getMessage();
       String localizedString =
@@ -105,15 +105,13 @@ public class RegionCreateFunction extends FunctionAdapter implements InternalEnt
                 new Object[] {String.valueOf(RegionCommandsUtils.PERSISTENT_OVERFLOW_SHORTCUTS)});
       }
       resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, null/* do not log */));
-    } catch (IllegalArgumentException e) {
+    } catch (IllegalArgumentException | CreateSubregionException e) {
       resultSender.lastResult(handleException(memberNameOrId, e.getMessage(), e));
     } catch (RegionExistsException e) {
       String exceptionMsg =
           CliStrings.format(CliStrings.CREATE_REGION__MSG__REGION_PATH_0_ALREADY_EXISTS_ON_1,
               regionCreateArgs.getRegionPath(), memberNameOrId);
       resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, e));
-    } catch (CreateSubregionException e) {
-      resultSender.lastResult(handleException(memberNameOrId, e.getMessage(), e));
     } catch (Exception e) {
       String exceptionMsg = e.getMessage();
       if (exceptionMsg == null) {
@@ -370,9 +368,9 @@ public class RegionCreateFunction extends FunctionAdapter implements InternalEnt
 
     PartitionAttributes<K, V> partitionAttributes = regionAttributes.getPartitionAttributes();
     if (partitionAttributes != null) {
-      prAttrFactory = new PartitionAttributesFactory<K, V>(partitionAttributes);
+      prAttrFactory = new PartitionAttributesFactory<>(partitionAttributes);
     } else {
-      prAttrFactory = new PartitionAttributesFactory<K, V>();
+      prAttrFactory = new PartitionAttributesFactory<>();
     }
 
     String colocatedWith = partitionArgs.getPrColocatedWith();
@@ -421,9 +419,8 @@ public class RegionCreateFunction extends FunctionAdapter implements InternalEnt
 
   private static Class<PartitionResolver> forName(String className, String neededFor) {
     if (StringUtils.isBlank(className)) {
-      throw new IllegalArgumentException(
-          CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER,
-              new Object[] {className, neededFor}));
+      throw new IllegalArgumentException(CliStrings
+          .format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER, className, neededFor));
     }
     try {
       return (Class<PartitionResolver>) ClassPathLoader.getLatest().forName(className);

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
index 2722964..dd84444 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
@@ -14,15 +14,16 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+
 /**
  * The PdxCommandsController class implements GemFire Management REST API web service endpoints for
  * Gfsh PDX Commands.

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
index 6d30d74..815bc47 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
@@ -14,9 +14,6 @@
  */
 package org.apache.geode.management.internal.web.controllers;
 
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -25,6 +22,10 @@ import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.context.request.WebRequest;
 
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+
 /**
  * The ListRegionCommand and DescribeRegionCommand classes implement GemFire Management REST API web
  * service endpoints for the Gfsh Region Commands.

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java b/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
index a626c62..86478a3 100644
--- a/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
+++ b/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
@@ -81,7 +81,7 @@ public class RegionProvider implements Closeable {
   private final Cache cache;
   private final QueryService queryService;
   private final ConcurrentMap<ByteArrayWrapper, Map<Enum<?>, Query>> preparedQueries =
-      new ConcurrentHashMap<ByteArrayWrapper, Map<Enum<?>, Query>>();
+      new ConcurrentHashMap<>();
   private final ConcurrentMap<ByteArrayWrapper, ScheduledFuture<?>> expirationsMap;
   private final ScheduledExecutorService expirationExecutor;
   private final RegionShortcut defaultRegionType;
@@ -95,7 +95,7 @@ public class RegionProvider implements Closeable {
       ScheduledExecutorService expirationExecutor, RegionShortcut defaultShortcut) {
     if (stringsRegion == null || hLLRegion == null || redisMetaRegion == null)
       throw new NullPointerException();
-    this.regions = new ConcurrentHashMap<ByteArrayWrapper, Region<?, ?>>();
+    this.regions = new ConcurrentHashMap<>();
     this.stringsRegion = stringsRegion;
     this.hLLRegion = hLLRegion;
     this.redisMetaRegion = redisMetaRegion;
@@ -104,7 +104,7 @@ public class RegionProvider implements Closeable {
     this.expirationsMap = expirationsMap;
     this.expirationExecutor = expirationExecutor;
     this.defaultRegionType = defaultShortcut;
-    this.locks = new ConcurrentHashMap<String, Lock>();
+    this.locks = new ConcurrentHashMap<>();
   }
 
   public boolean existsKey(ByteArrayWrapper key) {
@@ -364,7 +364,7 @@ public class RegionProvider implements Closeable {
     } catch (IndexNameConflictException | IndexExistsException | UnsupportedOperationException e) {
       // ignore, these indexes already exist or unsupported but make sure prepared queries are made
     }
-    HashMap<Enum<?>, Query> queryList = new HashMap<Enum<?>, Query>();
+    HashMap<Enum<?>, Query> queryList = new HashMap<>();
     for (SortedSetQuery lq : SortedSetQuery.values()) {
       String queryString = lq.getQueryString(fullpath);
       Query query = this.queryService.newQuery(queryString);
@@ -374,10 +374,10 @@ public class RegionProvider implements Closeable {
   }
 
   private void doInitializeList(ByteArrayWrapper key, Region r) {
-    r.put("head", Integer.valueOf(0));
-    r.put("tail", Integer.valueOf(0));
+    r.put("head", 0);
+    r.put("tail", 0);
     String fullpath = r.getFullPath();
-    HashMap<Enum<?>, Query> queryList = new HashMap<Enum<?>, Query>();
+    HashMap<Enum<?>, Query> queryList = new HashMap<>();
     for (ListQuery lq : ListQuery.values()) {
       String queryString = lq.getQueryString(fullpath);
       Query query = this.queryService.newQuery(queryString);

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
index 30e8728..fa368ab 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
@@ -64,7 +64,7 @@ public class AlterRegionCommandDUnitTest extends CliCommandTestBase {
   private VM alterVm2;
   private String alterVm2Name;
 
-  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
+  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<>();
 
   @Ignore("bug51924")
   @Test
@@ -135,9 +135,7 @@ public class AlterRegionCommandDUnitTest extends CliCommandTestBase {
     regionAlterSetDefaultsTest();
     regionAlterManipulatePlugInsTest();
 
-    this.alterVm1.invoke(() -> {
-      getCache().getRegion(alterRegionName).destroyRegion();
-    });
+    this.alterVm1.invoke(() -> getCache().getRegion(alterRegionName).destroyRegion());
   }
 
   @Category(FlakyTest.class) // GEODE-3018

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
index a1b9ade..f8644cb 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
@@ -76,12 +76,11 @@ import org.apache.geode.test.junit.categories.FlakyTest;
 @Category(DistributedTest.class)
 public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBase {
   private static final long serialVersionUID = 1L;
-  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
+  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<>();
 
   private void waitForRegionMBeanCreation(final String regionPath) {
-    Host.getHost(0).getVM(0).invoke(() -> {
-      waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath));
-    });
+    Host.getHost(0).getVM(0)
+        .invoke(() -> waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath)));
   }
 
   private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath) {

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
index 04168d5..4c0d2c2 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
@@ -49,7 +49,7 @@ import org.apache.geode.test.junit.categories.FlakyTest;
 
 @Category(DistributedTest.class)
 public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
-  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
+  private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<>();
 
   /**
    * Asserts that the "compressor" option for the "create region" command succeeds for a recognized
@@ -61,9 +61,7 @@ public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
     VM vm = Host.getHost(0).getVM(1);
 
     // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
+    vm.invoke(() -> assertNotNull(getCache()));
 
     // Run create region command with compression
     CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
@@ -100,9 +98,7 @@ public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
     VM vm = Host.getHost(0).getVM(1);
 
     // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
+    vm.invoke(() -> assertNotNull(getCache()));
 
     // Create a region with an unrecognized compressor
     CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
@@ -130,9 +126,7 @@ public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
     VM vm = Host.getHost(0).getVM(1);
 
     // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
+    vm.invoke(() -> assertNotNull(getCache()));
 
     // Create a region with no compression
     CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
@@ -204,9 +198,7 @@ public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
     setUpJmxManagerOnVm0ThenConnect(null);
     VM vm = Host.getHost(0).getVM(1);
     // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
+    vm.invoke(() -> assertNotNull(getCache()));
 
     ClassBuilder classBuilder = new ClassBuilder();
     // classBuilder.addToClassPath(".");
@@ -249,9 +241,7 @@ public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
       assertEquals("TestPartitionResolver", partitionResolver.getName());
     });
 
-    vm.invoke(() -> {
-      getCache().getRegion("regionWithPartitionResolver").destroyRegion();
-    });
+    vm.invoke(() -> getCache().getRegion("regionWithPartitionResolver").destroyRegion());
   }
 
   @Test
@@ -259,9 +249,7 @@ public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
     setUpJmxManagerOnVm0ThenConnect(null);
     VM vm = Host.getHost(0).getVM(1);
     // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
+    vm.invoke(() -> assertNotNull(getCache()));
 
     // Create a region with an unrecognized compressor
     CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
@@ -288,9 +276,7 @@ public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
     setUpJmxManagerOnVm0ThenConnect(null);
     VM vm = Host.getHost(0).getVM(1);
     // Create a cache in vm 1
-    vm.invoke(() -> {
-      assertNotNull(getCache());
-    });
+    vm.invoke(() -> assertNotNull(getCache()));
 
     // Create a region with an unrecognized compressor
     CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
index e178d8c..a3afe33 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
@@ -166,9 +166,8 @@ public class DestroyRegionCommandDUnitTest extends CliCommandTestBase {
 
     for (int i = 1; i <= 3; i++) {
       final int x = i;
-      Host.getHost(0).getVM(i).invoke(() -> {
-        assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
-      });
+      Host.getHost(0).getVM(i).invoke(
+          () -> assertNull("Region still exists in VM " + x, getCache().getRegion("Customer")));
     }
   }
 
@@ -365,9 +364,8 @@ public class DestroyRegionCommandDUnitTest extends CliCommandTestBase {
   }
 
   private void waitForRegionMBeanCreation(final String regionPath, final int mbeanCount) {
-    Host.getHost(0).getVM(0).invoke(() -> {
-      waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath, mbeanCount));
-    });
+    Host.getHost(0).getVM(0).invoke(() -> waitAtMost(5, TimeUnit.SECONDS)
+        .until(newRegionMBeanIsCreated(regionPath, mbeanCount)));
   }
 
   private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath, final int mbeanCount) {

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
index 1002f5d..341216c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
@@ -692,7 +692,7 @@ public class DiskStoreCommandsDUnitTest extends CliCommandTestBase {
     final String diskStoreName1 = "DiskStore1";
     final String region1 = "Region1";
     final String region2 = "Region2";
-    final Map<String, String> entries = new HashMap<String, String>();
+    final Map<String, String> entries = new HashMap<>();
     entries.put("key1", "value1");
     entries.put("key2", "value2");
 
@@ -1450,7 +1450,7 @@ public class DiskStoreCommandsDUnitTest extends CliCommandTestBase {
     diskStoreFactory.setAutoCompact(false);
     diskStoreFactory.create(diskStoreName);
 
-    /****
+    /*
      * Eviction Attributes
      */
     EvictionAttributes ea =

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
index 6dc23ce..7b9afc3 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
@@ -563,7 +563,7 @@ public class ListIndexCommandDUnitTest extends CliCommandTestBase {
     }
   }
 
-  private static abstract class AbstractBean<T extends Comparable<T>>
+  private abstract static class AbstractBean<T extends Comparable<T>>
       implements MutableIdentifiable<T>, Serializable {
 
     private T id;

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
index 8deb4ae..82b1ecd 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
@@ -111,7 +111,7 @@ public class ListIndexCommandJUnitTest {
     final List<IndexDetails> expectedIndexDetails =
         Arrays.asList(indexDetails1, indexDetails2, indexDetails3);
 
-    final List<Set<IndexDetails>> results = new ArrayList<Set<IndexDetails>>(2);
+    final List<Set<IndexDetails>> results = new ArrayList<>(2);
 
     results.add(CollectionUtils.asSet(indexDetails2, indexDetails1));
     results.add(CollectionUtils.asSet(indexDetails3));
@@ -169,7 +169,7 @@ public class ListIndexCommandJUnitTest {
 
     final List<IndexDetails> expectedIndexDetails = Collections.singletonList(indexDetails);
 
-    final List<Object> results = new ArrayList<Object>(2);
+    final List<Object> results = new ArrayList<>(2);
 
     results.add(CollectionUtils.asSet(indexDetails));
     results.add(new FunctionInvocationTargetException("expected"));

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java
index ca2a043..4df0b96 100755
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockDUnitTest.java
@@ -57,7 +57,6 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 
 /**
- * Distributed tests for show deadlock command in {@link MiscellaneousCommands}.
  *
  * @see GemFireDeadlockDetectorDUnitTest
  */

http://git-wip-us.apache.org/repos/asf/geode/blob/be8a1356/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index 5c91ca6..17719be 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -185,13 +185,6 @@ public class TestCommand {
     createTestCommand("import cluster-configuration --zip-file-name=value.zip", clusterManage);
 
     // DestroyFunctionCommand, ExecuteFunctionCommand, ListFunctionCommand
-    // TODO PSR: the `destroy function` command is interactive (in its interceptor) when both
-    // onGroup == null && onMember == null.
-    // This causes the function to throw
-    // CODE_SHELLCLIENT_ABORT_OP = 110;
-    // instead of the expected
-    // ERRORCODE_UNAUTHORIZED = 415;
-    // TODO: Should authorization occur before the interceptor resolves?
     // createTestCommand("destroy function --id=InterestCalculations", dataManage);
     createTestCommand("execute function --id=InterestCalculations --groups=Group1", dataWrite);
     createTestCommand("list functions", clusterRead);