geode-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bschucha...@apache.org
Subject [11/50] [abbrv] geode git commit: GEODE-3436: revert recent refactoring of GFSH commands
Date Tue, 15 Aug 2017 23:10:22 GMT
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/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
deleted file mode 100644
index 7555a62..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
+++ /dev/null
@@ -1,1085 +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.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/645a32d0/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
deleted file mode 100644
index 7b16581..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java
+++ /dev/null
@@ -1,150 +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.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) { // ignore FunctionInvocationTargetExceptions and other
-        // Exceptions...
-        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/645a32d0/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
deleted file mode 100644
index fcee9d8..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
+++ /dev/null
@@ -1,209 +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.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/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java
index 5e1df6f..72ccfbb 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java
@@ -57,7 +57,7 @@ import org.apache.geode.management.internal.cli.util.HostUtils;
 import org.apache.geode.management.internal.configuration.utils.ClusterConfigurationStatusRetriever;
 import org.apache.geode.security.AuthenticationFailedException;
 
-public class StartLocatorCommand extends StartMemberCommand implements GfshCommand {
+public class StartLocatorCommand implements GfshCommand {
   @CliCommand(value = CliStrings.START_LOCATOR, help = CliStrings.START_LOCATOR__HELP)
   @CliMetaData(shellOnly = true,
       relatedTopic = {CliStrings.TOPIC_GEODE_LOCATOR, CliStrings.TOPIC_GEODE_LIFECYCLE})
@@ -123,10 +123,10 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
     try {
       if (StringUtils.isBlank(memberName)) {
         // when the user doesn't give us a name, we make one up!
-        memberName = getNameGenerator().generate('-');
+        memberName = StartMemberUtils.getNameGenerator().generate('-');
       }
 
-      workingDirectory = resolveWorkingDir(workingDirectory, memberName);
+      workingDirectory = StartMemberUtils.resolveWorkingDir(workingDirectory, memberName);
 
       if (gemfirePropertiesFile != null && !gemfirePropertiesFile.exists()) {
         return ResultBuilder.createUserErrorResult(
@@ -142,28 +142,32 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
 
       File locatorPidFile = new File(workingDirectory, ProcessType.LOCATOR.getPidFileName());
 
-      final int oldPid = readPid(locatorPidFile);
+      final int oldPid = StartMemberUtils.readPid(locatorPidFile);
 
       Properties gemfireProperties = new Properties();
 
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.GROUPS, group);
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATORS, locators);
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOG_LEVEL, logLevel);
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_ADDRESS,
-          mcastBindAddress);
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_PORT, mcastPort);
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION,
-          enableSharedConfiguration);
-      setPropertyIfNotNull(gemfireProperties,
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.GROUPS,
+          group);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATORS,
+          locators);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOG_LEVEL,
+          logLevel);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+          ConfigurationProperties.MCAST_ADDRESS, mcastBindAddress);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_PORT,
+          mcastPort);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+          ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION, enableSharedConfiguration);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
           ConfigurationProperties.LOAD_CLUSTER_CONFIGURATION_FROM_DIR,
           loadSharedConfigurationFromDirectory);
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.CLUSTER_CONFIGURATION_DIR,
-          clusterConfigDir);
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.HTTP_SERVICE_PORT,
-          httpServicePort);
-      setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS,
-          httpServiceBindAddress);
-      setPropertyIfNotNull(gemfireProperties,
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+          ConfigurationProperties.CLUSTER_CONFIGURATION_DIR, clusterConfigDir);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+          ConfigurationProperties.HTTP_SERVICE_PORT, httpServicePort);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+          ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS, httpServiceBindAddress);
+      StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
           ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, jmxManagerHostnameForClients);
 
       // read the OSProcess enable redirect system property here
@@ -254,7 +258,7 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
             && locatorState.isStartingOrNotResponding());
       } finally {
         // stop will close
-        stderrReader.stopAsync(PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
+        stderrReader.stopAsync(StartMemberUtils.PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
 
         // ErrorStream
         getGfsh().getSignalHandler().unregisterListener(locatorSignalListener);
@@ -320,7 +324,6 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
       SystemFailure.initiateFailure(e);
       throw e;
     } catch (Throwable t) {
-      t.printStackTrace();
       SystemFailure.checkFailure();
       String errorMessage = String.format(CliStrings.START_LOCATOR__GENERAL_ERROR_MESSAGE,
           StringUtils.defaultIfBlank(workingDirectory, memberName),
@@ -436,19 +439,19 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
       final String maxHeap) throws MalformedObjectNameException {
     List<String> commandLine = new ArrayList<>();
 
-    commandLine.add(getJavaPath());
+    commandLine.add(StartMemberUtils.getJavaPath());
     commandLine.add("-server");
     commandLine.add("-classpath");
     commandLine
         .add(getLocatorClasspath(Boolean.TRUE.equals(includeSystemClasspath), userClasspath));
 
-    addCurrentLocators(this, commandLine, gemfireProperties);
-    addGemFirePropertyFile(commandLine, gemfirePropertiesFile);
-    addGemFireSecurityPropertyFile(commandLine, gemfireSecurityPropertiesFile);
-    addGemFireSystemProperties(commandLine, gemfireProperties);
-    addJvmArgumentsAndOptions(commandLine, jvmArgsOpts);
-    addInitialHeap(commandLine, initialHeap);
-    addMaxHeap(commandLine, maxHeap);
+    StartMemberUtils.addCurrentLocators(this, commandLine, gemfireProperties);
+    StartMemberUtils.addGemFirePropertyFile(commandLine, gemfirePropertiesFile);
+    StartMemberUtils.addGemFireSecurityPropertyFile(commandLine, gemfireSecurityPropertiesFile);
+    StartMemberUtils.addGemFireSystemProperties(commandLine, gemfireProperties);
+    StartMemberUtils.addJvmArgumentsAndOptions(commandLine, jvmArgsOpts);
+    StartMemberUtils.addInitialHeap(commandLine, initialHeap);
+    StartMemberUtils.addMaxHeap(commandLine, maxHeap);
 
     commandLine.add(
         "-D".concat(AbstractLauncher.SIGNAL_HANDLER_REGISTRATION_SYSTEM_PROPERTY.concat("=true")));
@@ -489,7 +492,7 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
   }
 
   String getLocatorClasspath(final boolean includeSystemClasspath, final String userClasspath) {
-    return toClasspath(includeSystemClasspath, new String[] {CORE_DEPENDENCIES_JAR_PATHNAME},
-        userClasspath);
+    return StartMemberUtils.toClasspath(includeSystemClasspath,
+        new String[] {StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME}, userClasspath);
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberCommand.java
deleted file mode 100644
index 6bdc25c..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberCommand.java
+++ /dev/null
@@ -1,248 +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.LOCATORS;
-import static org.apache.geode.management.internal.cli.shell.MXBeanProvider.getDistributedSystemMXBean;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Properties;
-
-import javax.management.MalformedObjectNameException;
-
-import org.apache.commons.lang.ArrayUtils;
-
-import org.apache.geode.distributed.internal.DistributionConfig;
-import org.apache.geode.internal.GemFireVersion;
-import org.apache.geode.internal.process.ProcessLauncherContext;
-import org.apache.geode.internal.util.IOUtils;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.internal.cli.util.ThreePhraseGenerator;
-
-/**
- * Encapsulates methods used by StartServerCommand and StartLocatorCommand and their associated
- * tests.
- * 
- * @see StartLocatorCommand
- * @see StartServerCommand
- */
-public class StartMemberCommand {
-  public static final String GEODE_HOME = System.getenv("GEODE_HOME");
-
-  private static final String JAVA_HOME = System.getProperty("java.home");
-  static final int CMS_INITIAL_OCCUPANCY_FRACTION = 60;
-  private static final ThreePhraseGenerator nameGenerator = new ThreePhraseGenerator();
-
-  static final String CORE_DEPENDENCIES_JAR_PATHNAME =
-      IOUtils.appendToPath(GEODE_HOME, "lib", "geode-dependencies.jar");
-  static final String GEODE_JAR_PATHNAME =
-      IOUtils.appendToPath(GEODE_HOME, "lib", GemFireVersion.getGemFireJarFileName());
-  static final long PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS = 5 * 1000;
-  static final int INVALID_PID = -1;
-
-  static ThreePhraseGenerator getNameGenerator() {
-    return nameGenerator;
-  }
-
-  void setPropertyIfNotNull(Properties properties, String key, Object value) {
-    if (key != null && value != null) {
-      properties.setProperty(key, value.toString());
-    }
-  }
-
-  String resolveWorkingDir(String userSpecifiedDir, String memberName) {
-    File workingDir =
-        (userSpecifiedDir == null) ? new File(memberName) : new File(userSpecifiedDir);
-    String workingDirPath = IOUtils.tryGetCanonicalPathElseGetAbsolutePath(workingDir);
-    if (!workingDir.exists()) {
-      if (!workingDir.mkdirs()) {
-        throw new IllegalStateException(String.format(
-            "Could not create directory %s. Please verify directory path or user permissions.",
-            workingDirPath));
-      }
-    }
-    return workingDirPath;
-  }
-
-  void addGemFirePropertyFile(final List<String> commandLine, final File gemfirePropertiesFile) {
-    if (gemfirePropertiesFile != null) {
-      commandLine.add("-DgemfirePropertyFile=" + gemfirePropertiesFile.getAbsolutePath());
-    }
-  }
-
-  void addGemFireSecurityPropertyFile(final List<String> commandLine,
-      final File gemfireSecurityPropertiesFile) {
-    if (gemfireSecurityPropertiesFile != null) {
-      commandLine
-          .add("-DgemfireSecurityPropertyFile=" + gemfireSecurityPropertiesFile.getAbsolutePath());
-    }
-  }
-
-  void addGemFireSystemProperties(final List<String> commandLine,
-      final Properties gemfireProperties) {
-    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)) {
-        commandLine.add(
-            "-D" + DistributionConfig.GEMFIRE_PREFIX + "" + propertyName + "=" + propertyValue);
-      }
-    }
-  }
-
-  void addJvmArgumentsAndOptions(final List<String> commandLine, final String[] jvmArgsOpts) {
-    if (jvmArgsOpts != null) {
-      commandLine.addAll(Arrays.asList(jvmArgsOpts));
-    }
-  }
-
-  void addInitialHeap(final List<String> commandLine, final String initialHeap) {
-    if (org.apache.geode.internal.lang.StringUtils.isNotBlank(initialHeap)) {
-      commandLine.add("-Xms" + initialHeap);
-    }
-  }
-
-  void addMaxHeap(final List<String> commandLine, final String maxHeap) {
-    if (org.apache.geode.internal.lang.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);
-    }
-  }
-
-  void addCurrentLocators(GfshCommand gfshCommand, final List<String> commandLine,
-      final Properties gemfireProperties) throws MalformedObjectNameException {
-    if (org.apache.geode.internal.lang.StringUtils
-        .isBlank(gemfireProperties.getProperty(LOCATORS))) {
-      String currentLocators = getCurrentLocators(gfshCommand);
-      if (org.apache.geode.internal.lang.StringUtils.isNotBlank(currentLocators)) {
-        commandLine.add("-D".concat(ProcessLauncherContext.OVERRIDDEN_DEFAULTS_PREFIX)
-            .concat(LOCATORS).concat("=").concat(currentLocators));
-      }
-    }
-  }
-
-  String getCurrentLocators(GfshCommand gfshCommand) throws MalformedObjectNameException {
-    String delimitedLocators = "";
-    try {
-      if (gfshCommand.isConnectedAndReady()) {
-        final DistributedSystemMXBean dsMBeanProxy = getDistributedSystemMXBean();
-        if (dsMBeanProxy != null) {
-          final String[] locators = dsMBeanProxy.listLocators();
-          if (locators != null && locators.length > 0) {
-            final StringBuilder sb = new StringBuilder();
-            for (int i = 0; i < locators.length; i++) {
-              if (i > 0) {
-                sb.append(",");
-              }
-              sb.append(locators[i]);
-            }
-            delimitedLocators = sb.toString();
-          }
-        }
-      }
-    } catch (IOException e) { // thrown by getDistributedSystemMXBean
-      // leave delimitedLocators = ""
-      gfshCommand.getGfsh().logWarning("DistributedSystemMXBean is unavailable\n", e);
-    }
-    return delimitedLocators;
-  }
-
-  int readPid(final File pidFile) {
-    assert pidFile != null : "The file from which to read the process ID (pid) cannot be null!";
-    if (pidFile.isFile()) {
-      BufferedReader fileReader = null;
-      try {
-        fileReader = new BufferedReader(new FileReader(pidFile));
-        return Integer.parseInt(fileReader.readLine());
-      } catch (IOException | NumberFormatException ignore) {
-      } finally {
-        IOUtils.close(fileReader);
-      }
-    }
-    return INVALID_PID;
-  }
-
-  String getJavaPath() {
-    return new File(new File(JAVA_HOME, "bin"), "java").getPath();
-  }
-
-  String getSystemClasspath() {
-    return System.getProperty("java.class.path");
-  }
-
-  String toClasspath(final boolean includeSystemClasspath, String[] jarFilePathnames,
-      String... userClasspaths) {
-    // gemfire jar must absolutely be the first JAR file on the CLASSPATH!!!
-    StringBuilder classpath = new StringBuilder(getGemFireJarPath());
-
-    userClasspaths = (userClasspaths != null ? userClasspaths : ArrayUtils.EMPTY_STRING_ARRAY);
-
-    // Then, include user-specified classes on CLASSPATH to enable the user to override GemFire JAR
-    // dependencies
-    // with application-specific versions; this logic/block corresponds to classes/jar-files
-    // specified with the
-    // --classpath option to the 'start locator' and 'start server commands'; also this will
-    // override any
-    // 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);
-        classpath.append(userClasspath);
-      }
-    }
-
-    // Now, include any System-specified CLASSPATH environment variable setting...
-    if (includeSystemClasspath) {
-      classpath.append(File.pathSeparator);
-      classpath.append(getSystemClasspath());
-    }
-
-    jarFilePathnames =
-        (jarFilePathnames != null ? jarFilePathnames : ArrayUtils.EMPTY_STRING_ARRAY);
-
-    // 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);
-        classpath.append(jarFilePathname);
-      }
-    }
-    return classpath.toString();
-  }
-
-  String getGemFireJarPath() {
-    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;
-      }
-    }
-    return gemfireJarPath;
-  }
-}


Mime
View raw message