You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by ji...@apache.org on 2017/11/11 04:54:27 UTC
[geode] branch develop updated: GEODE-3539: cleanup GfshCommand and
refactor tests
This is an automated email from the ASF dual-hosted git repository.
jinmeiliao pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git
The following commit(s) were added to refs/heads/develop by this push:
new e67456d GEODE-3539: cleanup GfshCommand and refactor tests
e67456d is described below
commit e67456dbce7d2781ad40824cb9e20b67bf7c4074
Author: Jinmei Liao <ji...@pivotal.io>
AuthorDate: Wed Nov 8 09:54:21 2017 -0800
GEODE-3539: cleanup GfshCommand and refactor tests
* remove more try catch blocks in commands
* make GfshCommand a pure wrapper around CliUtil for easy mocking
* unify EntityNotFoundException
---
.../StartLocatorCommandIntegrationTest.java | 6 +-
.../StartServerCommandIntegrationTest.java | 6 +-
.../cli/commands/DescribeDiskStoreCommand.java | 42 +-
.../cli/commands/DestroyRegionCommand.java | 55 ++-
.../internal/cli/commands/ExportLogsCommand.java | 20 +-
.../internal/cli/commands/GfshCommand.java | 80 ++--
.../cli/commands/ListDiskStoresCommand.java | 23 +-
.../internal/cli/commands/ListIndexCommand.java | 18 +-
.../internal/cli/commands/StartLocatorCommand.java | 344 +++++++---------
.../internal/cli/commands/StartServerCommand.java | 388 +++++++++---------
.../commands/lifecycle/StartJConsoleCommand.java | 2 +-
.../commands/lifecycle/StartJVisualVMCommand.java | 2 +-
.../cli/commands/lifecycle/StartPulseCommand.java | 2 +-
.../cli/commands/lifecycle/StartVsdCommand.java | 2 +-
.../commands/lifecycle/StatusLocatorCommand.java | 63 ++-
.../commands/lifecycle/StatusServerCommand.java | 68 ++-
.../cli/commands/lifecycle/StopLocatorCommand.java | 107 +++--
.../cli/commands/lifecycle/StopServerCommand.java | 101 ++---
...Exception.java => EntityNotFoundException.java} | 32 +-
.../cli/exceptions/IndexNotFoundException.java | 33 --
.../cli/functions/DescribeDiskStoreFunction.java | 4 +-
.../cli/functions/RegionCreateFunction.java | 3 +-
.../cli/functions/RegionDestroyFunction.java | 47 ++-
.../internal/cli/remote/CommandExecutor.java | 37 +-
.../cli/util/DiskStoreNotFoundException.java | 47 ---
.../internal/cli/util/MemberNotFoundException.java | 47 ---
.../commands/DestroyRegionCommandDUnitTest.java | 10 -
.../cli/commands/DestroyRegionCommandTest.java | 86 +++-
.../cli/commands/DiskStoreCommandsJUnitTest.java | 10 +-
.../cli/commands/ExportLogsCommandTest.java | 11 +-
.../cli/commands/GfshCommandJUnitTest.java | 454 +++------------------
.../ListAndDescribeDiskStoreCommandsDUnitTest.java | 6 +-
.../DescribeDiskStoreFunctionJUnitTest.java | 14 +-
.../cli/functions/RegionDestroyFunctionTest.java | 97 +++++
.../internal/cli/remote/CommandExecutorTest.java | 79 +++-
.../geode/codeAnalysis/sanctionedSerializables.txt | 5 +-
.../lucene/internal/cli/LuceneIndexCommands.java | 78 +---
.../internal/cli/LuceneIndexCommandsDUnitTest.java | 4 +-
38 files changed, 987 insertions(+), 1446 deletions(-)
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandIntegrationTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandIntegrationTest.java
index 6fa05c7..f8cd315 100644
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandIntegrationTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandIntegrationTest.java
@@ -29,7 +29,7 @@ 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.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
@@ -46,7 +46,7 @@ public class StartLocatorCommandIntegrationTest {
public GfshParserRule commandRule = new GfshParserRule();
@Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ public ExpectedException thrown = ExpectedException.none();
private StartLocatorCommand spy;
@@ -58,6 +58,7 @@ public class StartLocatorCommandIntegrationTest {
@Test
public void startLocatorWorksWithNoOptions() throws Exception {
+ thrown.expect(NullPointerException.class);
commandRule.executeCommandWithInstance(spy, "start locator");
ArgumentCaptor<Properties> gemfirePropertiesCaptor = ArgumentCaptor.forClass(Properties.class);
@@ -74,6 +75,7 @@ public class StartLocatorCommandIntegrationTest {
String startLocatorCommand = new CommandStringBuilder("start locator")
.addOption(JMX_MANAGER_HOSTNAME_FOR_CLIENTS, FAKE_HOSTNAME).toString();
+ thrown.expect(NullPointerException.class);
commandRule.executeCommandWithInstance(spy, startLocatorCommand);
ArgumentCaptor<Properties> gemfirePropertiesCaptor = ArgumentCaptor.forClass(Properties.class);
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandIntegrationTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandIntegrationTest.java
index 2a8807e..92f8749 100644
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandIntegrationTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandIntegrationTest.java
@@ -29,7 +29,7 @@ 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.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
@@ -46,7 +46,7 @@ public class StartServerCommandIntegrationTest {
public GfshParserRule commandRule = new GfshParserRule();
@Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ public ExpectedException thrown = ExpectedException.none();
private StartServerCommand spy;
@@ -58,6 +58,7 @@ public class StartServerCommandIntegrationTest {
@Test
public void startServerWorksWithNoOptions() throws Exception {
+ thrown.expect(NullPointerException.class);
commandRule.executeCommandWithInstance(spy, "start server");
ArgumentCaptor<Properties> gemfirePropertiesCaptor = ArgumentCaptor.forClass(Properties.class);
@@ -74,6 +75,7 @@ public class StartServerCommandIntegrationTest {
String startServerCommand = new CommandStringBuilder("start server")
.addOption(JMX_MANAGER_HOSTNAME_FOR_CLIENTS, FAKE_HOSTNAME).toString();
+ thrown.expect(NullPointerException.class);
commandRule.executeCommandWithInstance(spy, startServerCommand);
ArgumentCaptor<Properties> gemfirePropertiesCaptor = ArgumentCaptor.forClass(Properties.class);
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
index f56e591..cdb7d27 100644
--- 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
@@ -21,8 +21,6 @@ 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;
@@ -30,13 +28,12 @@ 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.exceptions.EntityNotFoundException;
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;
@@ -52,22 +49,9 @@ public class DescribeDiskStoreCommand implements GfshCommand {
@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())));
- }
+
+ return toCompositeResult(getDiskStoreDescription(memberName, diskStoreName));
+
}
DiskStoreDetails getDiskStoreDescription(final String memberName, final String diskStoreName) {
@@ -81,8 +65,8 @@ public class DescribeDiskStoreCommand implements GfshCommand {
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 if (result instanceof EntityNotFoundException) { // bad disk store name...
+ throw (EntityNotFoundException) result;
} else { // unknown and unexpected return type...
final Throwable cause = (result instanceof Throwable ? (Throwable) result : null);
@@ -117,9 +101,8 @@ public class DescribeDiskStoreCommand implements GfshCommand {
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"));
+ diskStoreDetails.isAllowForceCompaction() ? "Yes" : "No");
+ diskStoreSection.addData("Auto Compaction", diskStoreDetails.isAutoCompact() ? "Yes" : "No");
diskStoreSection.addData("Compaction Threshold", diskStoreDetails.getCompactionThreshold());
diskStoreSection.addData("Max Oplog Size", diskStoreDetails.getMaxOplogSize());
diskStoreSection.addData("Queue Size", diskStoreDetails.getQueueSize());
@@ -130,7 +113,7 @@ public class DescribeDiskStoreCommand implements GfshCommand {
diskStoreSection.addData("Disk Usage Critical Percentage",
diskStoreDetails.getDiskUsageCriticalPercentage());
diskStoreSection.addData("PDX Serialization Meta-Data Stored",
- toString(diskStoreDetails.isPdxSerializationMetaDataStored(), "Yes", "No"));
+ diskStoreDetails.isPdxSerializationMetaDataStored() ? "Yes" : "No");
final TabularResultData diskDirTable = diskStoreData.addSection().addTable();
@@ -144,9 +127,8 @@ public class DescribeDiskStoreCommand implements GfshCommand {
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"));
+ regionTable.accumulate("Persistent", regionDetails.isPersistent() ? "Yes" : "No");
+ regionTable.accumulate("Overflow To Disk", regionDetails.isOverflowToDisk() ? "Yes" : "No");
}
final TabularResultData cacheServerTable = diskStoreData.addSection().addTable();
@@ -162,7 +144,7 @@ public class DescribeDiskStoreCommand implements GfshCommand {
for (DiskStoreDetails.GatewayDetails gatewayDetails : diskStoreDetails.iterateGateways()) {
gatewayTable.accumulate("Gateway ID", gatewayDetails.getId());
- gatewayTable.accumulate("Persistent", toString(gatewayDetails.isPersistent(), "Yes", "No"));
+ gatewayTable.accumulate("Persistent", gatewayDetails.isPersistent() ? "Yes" : "No");
}
final TabularResultData asyncEventQueueTable = diskStoreData.addSection().addTable();
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
index 821eb64..13947ec 100644
--- 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
@@ -26,8 +26,6 @@ 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.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;
@@ -45,10 +43,10 @@ public class DestroyRegionCommand implements GfshCommand {
@CliOption(key = CliStrings.DESTROY_REGION__REGION, optionContext = ConverterHint.REGION_PATH,
mandatory = true, help = CliStrings.DESTROY_REGION__REGION__HELP) String regionPath,
@CliOption(key = CliStrings.IFEXISTS, help = CliStrings.IFEXISTS_HELP,
- specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") boolean ifExists) {
+ specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") boolean ifExists)
+ throws Throwable {
// regionPath should already be converted to have "/" in front of it.
- Result result;
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
Set<DistributedMember> regionMembersList = findMembersForRegion(getCache(), regionPath);
@@ -63,45 +61,40 @@ public class DestroyRegionCommand implements GfshCommand {
}
}
- CliFunctionResult destroyRegionResult;
-
ResultCollector<?, ?> resultCollector =
- CliUtil.executeFunction(RegionDestroyFunction.INSTANCE, regionPath, regionMembersList);
+ 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;
+ // destroy is called on each member, if any error happens in any one of the member, we should
+ // deem the destroy not successful.
+ String errorMessage = null;
+ for (CliFunctionResult functionResult : resultsList) {
+ if (functionResult.isSuccessful()) {
+ xmlEntity.set(functionResult.getXmlEntity());
} else {
- message = CliStrings.format(
- CliStrings.DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1,
- regionPath, destroyRegionResult.getMessage());
- isRegionDestroyed = false;
+ if (functionResult.getThrowable() != null) {
+ throw functionResult.getThrowable();
+ }
+ if (functionResult.getMessage() != null) {
+ errorMessage = functionResult.getMessage();
+ } else {
+ errorMessage = "Destroy failed on one member";
+ }
+ // if any error occurred, break out without looking further
+ break;
}
}
- if (isRegionDestroyed) {
- result = ResultBuilder.createInfoResult(message);
- } else {
- result = ResultBuilder.createUserErrorResult(message);
+
+ if (errorMessage != null) {
+ return ResultBuilder.createGemFireErrorResult(errorMessage);
}
+ Result result =
+ ResultBuilder.createInfoResult(String.format("\"%s\" destroyed successfully.", regionPath));
if (xmlEntity.get() != null) {
persistClusterConfiguration(result,
() -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null));
}
-
return result;
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportLogsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportLogsCommand.java
index 20cbeac..90b6fc6 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportLogsCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportLogsCommand.java
@@ -39,7 +39,6 @@ import org.apache.geode.management.ManagementException;
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.ExportLogsFunction;
import org.apache.geode.management.internal.cli.functions.SizeExportLogsFunction;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
@@ -97,17 +96,14 @@ public class ExportLogsCommand implements GfshCommand {
@CliOption(key = CliStrings.EXPORT_LOGS__FILESIZELIMIT,
unspecifiedDefaultValue = CliStrings.EXPORT_LOGS__FILESIZELIMIT__UNSPECIFIED_DEFAULT,
specifiedDefaultValue = CliStrings.EXPORT_LOGS__FILESIZELIMIT__SPECIFIED_DEFAULT,
- help = CliStrings.EXPORT_LOGS__FILESIZELIMIT__HELP) String fileSizeLimit) {
+ help = CliStrings.EXPORT_LOGS__FILESIZELIMIT__HELP) String fileSizeLimit)
+ throws Exception {
long totalEstimatedExportSize = 0;
Result result;
InternalCache cache = getCache();
try {
- Set<DistributedMember> targetMembers = getMembers(groups, memberIds);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
+ Set<DistributedMember> targetMembers = getMembersIncludingLocators(groups, memberIds);
long userSpecifiedLimit = parseFileSizeLimit(fileSizeLimit);
if (userSpecifiedLimit > 0) {
@@ -201,9 +197,6 @@ public class ExportLogsCommand implements GfshCommand {
FileUtils.deleteDirectory(tempDir.toFile());
result = new CommandResult(exportedLogsZipFile);
- } catch (Exception ex) {
- logger.error(ex.getMessage(), ex);
- result = ResultBuilder.createGemFireErrorResult(ex.getMessage());
} finally {
ExportLogsFunction.destroyExportLogsRegion(cache);
}
@@ -216,13 +209,6 @@ public class ExportLogsCommand implements GfshCommand {
/**
* Wrapper to enable stubbing of static method call for unit testing
*/
- Set<DistributedMember> getMembers(String[] groups, String[] memberIds) {
- return CliUtil.findMembersIncludingLocators(groups, memberIds);
- }
-
- /**
- * Wrapper to enable stubbing of static method call for unit testing
- */
ResultCollector estimateLogSize(SizeExportLogsFunction.Args args, DistributedMember member) {
return executeFunction(new SizeExportLogsFunction(), args, member);
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshCommand.java
index 449b42a..904001f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshCommand.java
@@ -14,12 +14,9 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import java.io.PrintWriter;
-import java.io.StringWriter;
import java.util.Collections;
import java.util.Set;
-import org.apache.commons.lang.StringUtils;
import org.springframework.shell.core.CommandMarker;
import org.apache.geode.cache.CacheFactory;
@@ -32,47 +29,22 @@ import org.apache.geode.distributed.internal.ClusterConfigurationService;
import org.apache.geode.distributed.internal.InternalLocator;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.security.SecurityService;
-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.exceptions.EntityNotFoundException;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.shell.Gfsh;
-import org.apache.geode.management.internal.cli.util.MemberNotFoundException;
/**
* Encapsulates common functionality for implementing command classes for the Geode shell (gfsh).
+ * this provides wrapper around the static methods in CliUtils for easy mock of the commands
*
- * @see org.apache.geode.cache.Cache
- * @see org.apache.geode.cache.execute.FunctionService
- * @see org.apache.geode.distributed.DistributedMember
- * @see org.apache.geode.management.internal.cli.shell.Gfsh
- * @see org.springframework.shell.core.CommandMarker
+ * this class should not have much implementation of its own other then those tested in
+ * GfshCommandJUnitTest
*/
@SuppressWarnings("unused")
public interface GfshCommand extends CommandMarker {
- default String convertDefaultValue(final String from, final String to) {
- return CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(from) ? to : from;
- }
-
- default String toString(final Boolean condition, final String trueValue,
- final String falseValue) {
- return Boolean.TRUE.equals(condition) ? StringUtils.defaultIfBlank(trueValue, "true")
- : StringUtils.defaultIfBlank(falseValue, "false");
- }
-
- default String toString(final Throwable t, final boolean printStackTrace) {
- String message = t.getMessage();
-
- if (printStackTrace) {
- StringWriter writer = new StringWriter();
- t.printStackTrace(new PrintWriter(writer));
- message = writer.toString();
- }
-
- return message;
- }
-
default boolean isConnectedAndReady() {
return getGfsh() != null && getGfsh().isConnectedAndReady();
}
@@ -103,7 +75,6 @@ public interface GfshCommand extends CommandMarker {
return getGfsh() != null;
}
-
default InternalCache getCache() {
return (InternalCache) CacheFactory.getAnyInstance();
}
@@ -120,16 +91,23 @@ public interface GfshCommand extends CommandMarker {
* this either returns a non-null member or throw an exception if member is not found.
*/
default DistributedMember getMember(final String memberName) {
- DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberName);
+ DistributedMember member = findMember(memberName);
if (member == null) {
- throw new MemberNotFoundException(
+ throw new EntityNotFoundException(
CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberName));
}
return member;
}
/**
+ * this will return the member found or null if no member with that name
+ */
+ default DistributedMember findMember(final String memberName) {
+ return CliUtil.getDistributedMemberByNameOrId(memberName);
+ }
+
+ /**
* Gets all members in the GemFire distributed system/cache, including locators
*/
default Set<DistributedMember> getAllMembers(final InternalCache cache) {
@@ -147,10 +125,42 @@ public interface GfshCommand extends CommandMarker {
return FunctionService.onMembers(members);
}
+ /**
+ * if no members matches these names, an empty set would return
+ */
default Set<DistributedMember> findMembers(String[] groups, String[] members) {
return CliUtil.findMembers(groups, members);
}
+ /**
+ * if no members matches these names, a UserErrorException will be thrown
+ */
+ default Set<DistributedMember> getMembers(String[] groups, String[] members) {
+ Set<DistributedMember> matchingMembers = findMembers(groups, members);
+ if (matchingMembers.size() == 0) {
+ throw new EntityNotFoundException(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+ return matchingMembers;
+ }
+
+ /**
+ * if no members matches these names, an empty set would return
+ */
+ default Set<DistributedMember> findMembersIncludingLocators(String[] groups, String[] members) {
+ return CliUtil.findMembersIncludingLocators(groups, members);
+ }
+
+ /**
+ * if no members matches these names, a UserErrorException will be thrown
+ */
+ default Set<DistributedMember> getMembersIncludingLocators(String[] groups, String[] members) {
+ Set<DistributedMember> matchingMembers = findMembersIncludingLocators(groups, members);
+ if (matchingMembers.size() == 0) {
+ throw new EntityNotFoundException(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+ return matchingMembers;
+ }
+
default Set<DistributedMember> findMembersForRegion(InternalCache cache, String regionPath) {
return CliUtil.getRegionAssociatedMembers(regionPath, cache, true);
}
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
index 5444c4d..e65d4fb 100644
--- 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
@@ -22,9 +22,7 @@ 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;
@@ -45,25 +43,12 @@ public class ListDiskStoresCommand implements GfshCommand {
@ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
operation = ResourcePermission.Operation.READ)
public Result listDiskStores() {
- try {
- Set<DistributedMember> dataMembers = DiskStoreCommandsUtils.getNormalMembers(getCache());
+ 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())));
+ if (dataMembers.isEmpty()) {
+ return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
}
+ return toTabularResult(getDiskStoreListing(dataMembers));
}
@SuppressWarnings("unchecked")
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
index c5010de..663d185 100644
--- 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
@@ -23,9 +23,7 @@ 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;
@@ -48,20 +46,8 @@ public class ListIndexCommand implements GfshCommand {
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())));
- }
+
+ return toTabularResult(getIndexListing(), showStats);
}
private Result toTabularResult(final List<IndexDetails> indexDetailsList,
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 6020eca..1e6f5da 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
@@ -28,13 +28,11 @@ import javax.net.ssl.SSLException;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
-import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.AbstractLauncher;
import org.apache.geode.distributed.ConfigurationProperties;
import org.apache.geode.distributed.LocatorLauncher;
import org.apache.geode.distributed.ServerLauncher;
import org.apache.geode.internal.OSProcess;
-import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.lang.StringUtils;
import org.apache.geode.internal.lang.SystemUtils;
import org.apache.geode.internal.process.ProcessStreamReader;
@@ -119,219 +117,193 @@ public class StartLocatorCommand implements GfshCommand {
@CliOption(key = CliStrings.START_LOCATOR__HTTP_SERVICE_PORT,
help = CliStrings.START_LOCATOR__HTTP_SERVICE_PORT__HELP) final Integer httpServicePort,
@CliOption(key = CliStrings.START_LOCATOR__HTTP_SERVICE_BIND_ADDRESS,
- help = CliStrings.START_LOCATOR__HTTP_SERVICE_BIND_ADDRESS__HELP) final String httpServiceBindAddress) {
- try {
- if (StringUtils.isBlank(memberName)) {
- // when the user doesn't give us a name, we make one up!
- memberName = StartMemberUtils.getNameGenerator().generate('-');
- }
+ help = CliStrings.START_LOCATOR__HTTP_SERVICE_BIND_ADDRESS__HELP) final String httpServiceBindAddress)
+ throws Exception {
+ if (StringUtils.isBlank(memberName)) {
+ // when the user doesn't give us a name, we make one up!
+ memberName = StartMemberUtils.getNameGenerator().generate('-');
+ }
- workingDirectory = StartMemberUtils.resolveWorkingDir(workingDirectory, memberName);
+ workingDirectory = StartMemberUtils.resolveWorkingDir(workingDirectory, memberName);
- if (gemfirePropertiesFile != null && !gemfirePropertiesFile.exists()) {
- return ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, StringUtils.EMPTY,
- gemfirePropertiesFile.getAbsolutePath()));
- }
+ if (gemfirePropertiesFile != null && !gemfirePropertiesFile.exists()) {
+ return ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, StringUtils.EMPTY,
+ gemfirePropertiesFile.getAbsolutePath()));
+ }
- if (gemfireSecurityPropertiesFile != null && !gemfireSecurityPropertiesFile.exists()) {
- return ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ",
- gemfireSecurityPropertiesFile.getAbsolutePath()));
- }
+ if (gemfireSecurityPropertiesFile != null && !gemfireSecurityPropertiesFile.exists()) {
+ return ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ",
+ gemfireSecurityPropertiesFile.getAbsolutePath()));
+ }
- File locatorPidFile = new File(workingDirectory, ProcessType.LOCATOR.getPidFileName());
-
- final int oldPid = StartMemberUtils.readPid(locatorPidFile);
-
- Properties gemfireProperties = new Properties();
-
- 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);
- 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
- // TODO: replace with new GFSH argument
- final boolean redirectOutput =
- Boolean.getBoolean(OSProcess.ENABLE_OUTPUT_REDIRECTION_PROPERTY);
- LocatorLauncher.Builder locatorLauncherBuilder =
- new LocatorLauncher.Builder().setBindAddress(bindAddress).setForce(force).setPort(port)
- .setRedirectOutput(redirectOutput).setWorkingDirectory(workingDirectory);
- if (hostnameForClients != null) {
- locatorLauncherBuilder.setHostnameForClients(hostnameForClients);
- }
- if (memberName != null) {
- locatorLauncherBuilder.setMemberName(memberName);
+ File locatorPidFile = new File(workingDirectory, ProcessType.LOCATOR.getPidFileName());
+
+ final int oldPid = StartMemberUtils.readPid(locatorPidFile);
+
+ Properties gemfireProperties = new Properties();
+
+ 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);
+ 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
+ // TODO: replace with new GFSH argument
+ final boolean redirectOutput = Boolean.getBoolean(OSProcess.ENABLE_OUTPUT_REDIRECTION_PROPERTY);
+ LocatorLauncher.Builder locatorLauncherBuilder =
+ new LocatorLauncher.Builder().setBindAddress(bindAddress).setForce(force).setPort(port)
+ .setRedirectOutput(redirectOutput).setWorkingDirectory(workingDirectory);
+ if (hostnameForClients != null) {
+ locatorLauncherBuilder.setHostnameForClients(hostnameForClients);
+ }
+ if (memberName != null) {
+ locatorLauncherBuilder.setMemberName(memberName);
+ }
+ LocatorLauncher locatorLauncher = locatorLauncherBuilder.build();
+
+ String[] locatorCommandLine = createStartLocatorCommandLine(locatorLauncher,
+ gemfirePropertiesFile, gemfireSecurityPropertiesFile, gemfireProperties, classpath,
+ includeSystemClasspath, jvmArgsOpts, initialHeap, maxHeap);
+
+ final Process locatorProcess = new ProcessBuilder(locatorCommandLine)
+ .directory(new File(locatorLauncher.getWorkingDirectory())).start();
+
+ locatorProcess.getInputStream().close();
+ locatorProcess.getOutputStream().close();
+
+ // fix TRAC bug #51967 by using NON_BLOCKING on Windows
+ final ProcessStreamReader.ReadingMode readingMode = SystemUtils.isWindows()
+ ? ProcessStreamReader.ReadingMode.NON_BLOCKING : ProcessStreamReader.ReadingMode.BLOCKING;
+
+ final StringBuffer message = new StringBuffer(); // need thread-safe StringBuffer
+ ProcessStreamReader.InputListener inputListener = line -> {
+ message.append(line);
+ if (readingMode == ProcessStreamReader.ReadingMode.BLOCKING) {
+ message.append(StringUtils.LINE_SEPARATOR);
}
- LocatorLauncher locatorLauncher = locatorLauncherBuilder.build();
+ };
- String[] locatorCommandLine = createStartLocatorCommandLine(locatorLauncher,
- gemfirePropertiesFile, gemfireSecurityPropertiesFile, gemfireProperties, classpath,
- includeSystemClasspath, jvmArgsOpts, initialHeap, maxHeap);
+ ProcessStreamReader stderrReader = new ProcessStreamReader.Builder(locatorProcess)
+ .inputStream(locatorProcess.getErrorStream()).inputListener(inputListener)
+ .readingMode(readingMode).continueReadingMillis(2 * 1000).build().start();
- final Process locatorProcess = new ProcessBuilder(locatorCommandLine)
- .directory(new File(locatorLauncher.getWorkingDirectory())).start();
+ LocatorLauncher.LocatorState locatorState;
- locatorProcess.getInputStream().close();
- locatorProcess.getOutputStream().close();
+ String previousLocatorStatusMessage = null;
- // fix TRAC bug #51967 by using NON_BLOCKING on Windows
- final ProcessStreamReader.ReadingMode readingMode = SystemUtils.isWindows()
- ? ProcessStreamReader.ReadingMode.NON_BLOCKING : ProcessStreamReader.ReadingMode.BLOCKING;
+ LauncherSignalListener locatorSignalListener = new LauncherSignalListener();
- final StringBuffer message = new StringBuffer(); // need thread-safe StringBuffer
- ProcessStreamReader.InputListener inputListener = line -> {
- message.append(line);
- if (readingMode == ProcessStreamReader.ReadingMode.BLOCKING) {
- message.append(StringUtils.LINE_SEPARATOR);
- }
- };
+ final boolean registeredLocatorSignalListener =
+ getGfsh().getSignalHandler().registerListener(locatorSignalListener);
- ProcessStreamReader stderrReader = new ProcessStreamReader.Builder(locatorProcess)
- .inputStream(locatorProcess.getErrorStream()).inputListener(inputListener)
- .readingMode(readingMode).continueReadingMillis(2 * 1000).build().start();
+ try {
+ getGfsh().logInfo(String.format(CliStrings.START_LOCATOR__RUN_MESSAGE, IOUtils
+ .tryGetCanonicalPathElseGetAbsolutePath(new File(locatorLauncher.getWorkingDirectory()))),
+ null);
- LocatorLauncher.LocatorState locatorState;
+ do {
+ if (locatorProcess.isAlive()) {
+ Gfsh.print(".");
- String previousLocatorStatusMessage = null;
+ synchronized (this) {
+ TimeUnit.MILLISECONDS.timedWait(this, 500);
+ }
- LauncherSignalListener locatorSignalListener = new LauncherSignalListener();
+ locatorState = LocatorLauncher.LocatorState.fromDirectory(workingDirectory, memberName);
- final boolean registeredLocatorSignalListener =
- getGfsh().getSignalHandler().registerListener(locatorSignalListener);
+ String currentLocatorStatusMessage = locatorState.getStatusMessage();
- try {
- getGfsh().logInfo(String.format(CliStrings.START_LOCATOR__RUN_MESSAGE,
- IOUtils.tryGetCanonicalPathElseGetAbsolutePath(
- new File(locatorLauncher.getWorkingDirectory()))),
- null);
-
- do {
- if (locatorProcess.isAlive()) {
- Gfsh.print(".");
-
- synchronized (this) {
- TimeUnit.MILLISECONDS.timedWait(this, 500);
- }
-
- locatorState = LocatorLauncher.LocatorState.fromDirectory(workingDirectory, memberName);
-
- String currentLocatorStatusMessage = locatorState.getStatusMessage();
-
- if (locatorState.isStartingOrNotResponding()
- && !(StringUtils.isBlank(currentLocatorStatusMessage)
- || currentLocatorStatusMessage.equalsIgnoreCase(previousLocatorStatusMessage)
- || currentLocatorStatusMessage.trim().toLowerCase().equals("null"))) {
- Gfsh.println();
- Gfsh.println(currentLocatorStatusMessage);
- previousLocatorStatusMessage = currentLocatorStatusMessage;
- }
- } else {
- final int exitValue = locatorProcess.exitValue();
-
- return ResultBuilder.createShellClientErrorResult(
- String.format(CliStrings.START_LOCATOR__PROCESS_TERMINATED_ABNORMALLY_ERROR_MESSAGE,
- exitValue, locatorLauncher.getWorkingDirectory(), message.toString()));
+ if (locatorState.isStartingOrNotResponding()
+ && !(StringUtils.isBlank(currentLocatorStatusMessage)
+ || currentLocatorStatusMessage.equalsIgnoreCase(previousLocatorStatusMessage)
+ || currentLocatorStatusMessage.trim().toLowerCase().equals("null"))) {
+ Gfsh.println();
+ Gfsh.println(currentLocatorStatusMessage);
+ previousLocatorStatusMessage = currentLocatorStatusMessage;
}
- } while (!(registeredLocatorSignalListener && locatorSignalListener.isSignaled())
- && locatorState.isStartingOrNotResponding());
- } finally {
- // stop will close
- stderrReader.stopAsync(StartMemberUtils.PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
-
- // ErrorStream
- getGfsh().getSignalHandler().unregisterListener(locatorSignalListener);
- }
+ } else {
+ final int exitValue = locatorProcess.exitValue();
- Gfsh.println();
+ return ResultBuilder.createShellClientErrorResult(
+ String.format(CliStrings.START_LOCATOR__PROCESS_TERMINATED_ABNORMALLY_ERROR_MESSAGE,
+ exitValue, locatorLauncher.getWorkingDirectory(), message.toString()));
+ }
+ } while (!(registeredLocatorSignalListener && locatorSignalListener.isSignaled())
+ && locatorState.isStartingOrNotResponding());
+ } finally {
+ // stop will close
+ stderrReader.stopAsync(StartMemberUtils.PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
- final boolean asyncStart =
- (registeredLocatorSignalListener && locatorSignalListener.isSignaled()
- && ServerLauncher.ServerState.isStartingNotRespondingOrNull(locatorState));
+ // ErrorStream
+ getGfsh().getSignalHandler().unregisterListener(locatorSignalListener);
+ }
- InfoResultData infoResultData = ResultBuilder.createInfoResultData();
+ Gfsh.println();
- if (asyncStart) {
- infoResultData.addLine(
- String.format(CliStrings.ASYNC_PROCESS_LAUNCH_MESSAGE, CliStrings.LOCATOR_TERM_NAME));
- return ResultBuilder.buildResult(infoResultData);
- }
+ final boolean asyncStart =
+ (registeredLocatorSignalListener && locatorSignalListener.isSignaled()
+ && ServerLauncher.ServerState.isStartingNotRespondingOrNull(locatorState));
- infoResultData.addLine(locatorState.toString());
- String locatorHostName;
- InetAddress bindAddr = locatorLauncher.getBindAddress();
- if (bindAddr != null) {
- locatorHostName = bindAddr.getCanonicalHostName();
- } else {
- locatorHostName = StringUtils.defaultIfBlank(locatorLauncher.getHostnameForClients(),
- HostUtils.getLocalHost());
- }
+ InfoResultData infoResultData = ResultBuilder.createInfoResultData();
+
+ if (asyncStart) {
+ infoResultData.addLine(
+ String.format(CliStrings.ASYNC_PROCESS_LAUNCH_MESSAGE, CliStrings.LOCATOR_TERM_NAME));
+ return ResultBuilder.buildResult(infoResultData);
+ }
- int locatorPort = Integer.parseInt(locatorState.getPort());
+ infoResultData.addLine(locatorState.toString());
+ String locatorHostName;
+ InetAddress bindAddr = locatorLauncher.getBindAddress();
+ if (bindAddr != null) {
+ locatorHostName = bindAddr.getCanonicalHostName();
+ } else {
+ locatorHostName = StringUtils.defaultIfBlank(locatorLauncher.getHostnameForClients(),
+ HostUtils.getLocalHost());
+ }
+ int locatorPort = Integer.parseInt(locatorState.getPort());
- ConnectCommand connectCommand = new ConnectCommand();
- Properties configProperties = connectCommand.resolveSslProperties(getGfsh(), false,
- gemfirePropertiesFile, gemfireSecurityPropertiesFile);
- // AUTO-CONNECT
- // If the connect succeeds add the connected message to the result,
- // Else, ask the user to use the "connect" command to connect to the Locator.
- if (shouldAutoConnect(connect)) {
- doAutoConnect(locatorHostName, locatorPort, configProperties, infoResultData);
- }
+ ConnectCommand connectCommand = new ConnectCommand();
+ Properties configProperties = connectCommand.resolveSslProperties(getGfsh(), false,
+ gemfirePropertiesFile, gemfireSecurityPropertiesFile);
- // Report on the state of the Shared Configuration service if enabled...
- if (enableSharedConfiguration) {
- infoResultData.addLine(ClusterConfigurationStatusRetriever.fromLocator(locatorHostName,
- locatorPort, configProperties));
- }
+ // AUTO-CONNECT
+ // If the connect succeeds add the connected message to the result,
+ // Else, ask the user to use the "connect" command to connect to the Locator.
+ if (shouldAutoConnect(connect)) {
+ doAutoConnect(locatorHostName, locatorPort, configProperties, infoResultData);
+ }
- return ResultBuilder.buildResult(infoResultData);
- } catch (IllegalArgumentException e) {
- String message = e.getMessage();
- if (message != null && message.matches(
- LocalizedStrings.Launcher_Builder_UNKNOWN_HOST_ERROR_MESSAGE.toLocalizedString(".+"))) {
- message =
- CliStrings.format(CliStrings.LAUNCHERLIFECYCLECOMMANDS__MSG__FAILED_TO_START_0_REASON_1,
- CliStrings.LOCATOR_TERM_NAME, message);
- }
- return ResultBuilder.createUserErrorResult(message);
- } catch (IllegalStateException e) {
- return ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- String errorMessage = String.format(CliStrings.START_LOCATOR__GENERAL_ERROR_MESSAGE,
- StringUtils.defaultIfBlank(workingDirectory, memberName),
- HostUtils.getLocatorId(bindAddress, port), this.toString(t, getGfsh().getDebug()));
- getGfsh().logToFile(errorMessage, t);
- return ResultBuilder.createShellClientErrorResult(errorMessage);
- } finally {
- Gfsh.redirectInternalJavaLoggers();
+ // Report on the state of the Shared Configuration service if enabled...
+ if (enableSharedConfiguration) {
+ infoResultData.addLine(ClusterConfigurationStatusRetriever.fromLocator(locatorHostName,
+ locatorPort, configProperties));
}
+
+ return ResultBuilder.buildResult(infoResultData);
+
}
// TODO should we connect implicitly when in non-interactive, headless mode (e.g. gfsh -e "start
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java
index 8080e3f..3522701 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java
@@ -26,13 +26,11 @@ import javax.management.MalformedObjectNameException;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
-import org.apache.geode.SystemFailure;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.distributed.AbstractLauncher;
import org.apache.geode.distributed.ConfigurationProperties;
import org.apache.geode.distributed.ServerLauncher;
import org.apache.geode.internal.OSProcess;
-import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.lang.StringUtils;
import org.apache.geode.internal.lang.SystemUtils;
import org.apache.geode.internal.process.ProcessStreamReader;
@@ -176,243 +174,221 @@ public class StartServerCommand implements GfshCommand {
help = CliStrings.START_SERVER__USERNAME__HELP) final String userName,
@CliOption(key = CliStrings.START_SERVER__PASSWORD, unspecifiedDefaultValue = "",
help = CliStrings.START_SERVER__PASSWORD__HELP) String passwordToUse)
+ throws Exception
// NOTICE: keep the parameters in alphabetical order based on their CliStrings.START_SERVER_* text
{
- try {
- if (StringUtils.isBlank(memberName)) {
- // when the user doesn't give us a name, we make one up!
- memberName = StartMemberUtils.getNameGenerator().generate('-');
- }
- // prompt for password is username is specified in the command
- if (StringUtils.isNotBlank(userName)) {
- if (StringUtils.isBlank(passwordToUse)) {
- passwordToUse = getGfsh().readPassword(CliStrings.START_SERVER__PASSWORD + ": ");
- }
- if (StringUtils.isBlank(passwordToUse)) {
- return ResultBuilder.createConnectionErrorResult(
- CliStrings.START_SERVER__MSG__PASSWORD_MUST_BE_SPECIFIED);
- }
+ if (StringUtils.isBlank(memberName)) {
+ // when the user doesn't give us a name, we make one up!
+ memberName = StartMemberUtils.getNameGenerator().generate('-');
+ }
+
+ // prompt for password is username is specified in the command
+ if (StringUtils.isNotBlank(userName)) {
+ if (StringUtils.isBlank(passwordToUse)) {
+ passwordToUse = getGfsh().readPassword(CliStrings.START_SERVER__PASSWORD + ": ");
+ }
+ if (StringUtils.isBlank(passwordToUse)) {
+ return ResultBuilder
+ .createConnectionErrorResult(CliStrings.START_SERVER__MSG__PASSWORD_MUST_BE_SPECIFIED);
}
+ }
- workingDirectory = StartMemberUtils.resolveWorkingDir(workingDirectory, memberName);
+ workingDirectory = StartMemberUtils.resolveWorkingDir(workingDirectory, memberName);
- cacheXmlPathname = CliUtil.resolvePathname(cacheXmlPathname);
+ cacheXmlPathname = CliUtil.resolvePathname(cacheXmlPathname);
- if (StringUtils.isNotBlank(cacheXmlPathname)
- && !IOUtils.isExistingPathname(cacheXmlPathname)) {
- return ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.CACHE_XML_NOT_FOUND_MESSAGE, cacheXmlPathname));
- }
+ if (StringUtils.isNotBlank(cacheXmlPathname) && !IOUtils.isExistingPathname(cacheXmlPathname)) {
+ return ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.CACHE_XML_NOT_FOUND_MESSAGE, cacheXmlPathname));
+ }
- if (gemfirePropertiesFile != null && !gemfirePropertiesFile.exists()) {
- return ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, StringUtils.EMPTY,
- gemfirePropertiesFile.getAbsolutePath()));
- }
+ if (gemfirePropertiesFile != null && !gemfirePropertiesFile.exists()) {
+ return ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, StringUtils.EMPTY,
+ gemfirePropertiesFile.getAbsolutePath()));
+ }
- if (gemfireSecurityPropertiesFile != null && !gemfireSecurityPropertiesFile.exists()) {
- return ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ",
- gemfireSecurityPropertiesFile.getAbsolutePath()));
- }
+ if (gemfireSecurityPropertiesFile != null && !gemfireSecurityPropertiesFile.exists()) {
+ return ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ",
+ gemfireSecurityPropertiesFile.getAbsolutePath()));
+ }
- File serverPidFile = new File(workingDirectory, ProcessType.SERVER.getPidFileName());
-
- final int oldPid = StartMemberUtils.readPid(serverPidFile);
-
- Properties gemfireProperties = new Properties();
-
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.BIND_ADDRESS,
- bindAddress);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.CACHE_XML_FILE, cacheXmlPathname);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.ENABLE_TIME_STATISTICS, enableTimeStatistics);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.GROUPS,
- group);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, jmxManagerHostnameForClients);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATORS,
- locators);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.LOCATOR_WAIT_TIME, locatorWaitTime);
- 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.MEMCACHED_PORT, memcachedPort);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.MEMCACHED_PROTOCOL, memcachedProtocol);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.MEMCACHED_BIND_ADDRESS, memcachedBindAddress);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.REDIS_PORT,
- redisPort);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.REDIS_BIND_ADDRESS, redisBindAddress);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.REDIS_PASSWORD, redisPassword);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.STATISTIC_ARCHIVE_FILE, statisticsArchivePathname);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.USE_CLUSTER_CONFIGURATION, requestSharedConfiguration);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCK_MEMORY,
- lockMemory);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.OFF_HEAP_MEMORY_SIZE, offHeapMemorySize);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.START_DEV_REST_API, startRestApi);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.HTTP_SERVICE_PORT, httpServicePort);
- StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
- ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS, httpServiceBindAddress);
- // if username is specified in the command line, it will overwrite what's set in the
- // properties file
- if (StringUtils.isNotBlank(userName)) {
- gemfireProperties.setProperty(ResourceConstants.USER_NAME, userName);
- gemfireProperties.setProperty(ResourceConstants.PASSWORD, passwordToUse);
- }
+ File serverPidFile = new File(workingDirectory, ProcessType.SERVER.getPidFileName());
+
+ final int oldPid = StartMemberUtils.readPid(serverPidFile);
+
+ Properties gemfireProperties = new Properties();
+
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.BIND_ADDRESS,
+ bindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.CACHE_XML_FILE,
+ cacheXmlPathname);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.ENABLE_TIME_STATISTICS, enableTimeStatistics);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.GROUPS, group);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, jmxManagerHostnameForClients);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATORS,
+ locators);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.LOCATOR_WAIT_TIME, locatorWaitTime);
+ 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.MEMCACHED_PORT,
+ memcachedPort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.MEMCACHED_PROTOCOL, memcachedProtocol);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.MEMCACHED_BIND_ADDRESS, memcachedBindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.REDIS_PORT,
+ redisPort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.REDIS_BIND_ADDRESS, redisBindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.REDIS_PASSWORD,
+ redisPassword);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.STATISTIC_ARCHIVE_FILE, statisticsArchivePathname);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.USE_CLUSTER_CONFIGURATION, requestSharedConfiguration);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCK_MEMORY,
+ lockMemory);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.OFF_HEAP_MEMORY_SIZE, offHeapMemorySize);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.START_DEV_REST_API, startRestApi);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.HTTP_SERVICE_PORT, httpServicePort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS, httpServiceBindAddress);
+ // if username is specified in the command line, it will overwrite what's set in the
+ // properties file
+ if (StringUtils.isNotBlank(userName)) {
+ gemfireProperties.setProperty(ResourceConstants.USER_NAME, userName);
+ gemfireProperties.setProperty(ResourceConstants.PASSWORD, passwordToUse);
+ }
- // read the OSProcess enable redirect system property here -- TODO: replace with new GFSH
- // argument
- final boolean redirectOutput =
- Boolean.getBoolean(OSProcess.ENABLE_OUTPUT_REDIRECTION_PROPERTY);
-
- ServerLauncher.Builder serverLauncherBuilder = new ServerLauncher.Builder()
- .setAssignBuckets(assignBuckets).setDisableDefaultServer(disableDefaultServer)
- .setForce(force).setRebalance(rebalance).setRedirectOutput(redirectOutput)
- .setServerBindAddress(serverBindAddress).setServerPort(serverPort)
- .setSpringXmlLocation(springXmlLocation).setWorkingDirectory(workingDirectory)
- .setCriticalHeapPercentage(criticalHeapPercentage)
- .setEvictionHeapPercentage(evictionHeapPercentage)
- .setCriticalOffHeapPercentage(criticalOffHeapPercentage)
- .setEvictionOffHeapPercentage(evictionOffHeapPercentage).setMaxConnections(maxConnections)
- .setMaxMessageCount(maxMessageCount).setMaxThreads(maxThreads)
- .setMessageTimeToLive(messageTimeToLive).setSocketBufferSize(socketBufferSize);
- if (hostNameForClients != null) {
- serverLauncherBuilder.setHostNameForClients(hostNameForClients);
- }
- if (memberName != null) {
- serverLauncherBuilder.setMemberName(memberName);
- }
- ServerLauncher serverLauncher = serverLauncherBuilder.build();
+ // read the OSProcess enable redirect system property here -- TODO: replace with new GFSH
+ // argument
+ final boolean redirectOutput = Boolean.getBoolean(OSProcess.ENABLE_OUTPUT_REDIRECTION_PROPERTY);
+
+ ServerLauncher.Builder serverLauncherBuilder = new ServerLauncher.Builder()
+ .setAssignBuckets(assignBuckets).setDisableDefaultServer(disableDefaultServer)
+ .setForce(force).setRebalance(rebalance).setRedirectOutput(redirectOutput)
+ .setServerBindAddress(serverBindAddress).setServerPort(serverPort)
+ .setSpringXmlLocation(springXmlLocation).setWorkingDirectory(workingDirectory)
+ .setCriticalHeapPercentage(criticalHeapPercentage)
+ .setEvictionHeapPercentage(evictionHeapPercentage)
+ .setCriticalOffHeapPercentage(criticalOffHeapPercentage)
+ .setEvictionOffHeapPercentage(evictionOffHeapPercentage).setMaxConnections(maxConnections)
+ .setMaxMessageCount(maxMessageCount).setMaxThreads(maxThreads)
+ .setMessageTimeToLive(messageTimeToLive).setSocketBufferSize(socketBufferSize);
+ if (hostNameForClients != null) {
+ serverLauncherBuilder.setHostNameForClients(hostNameForClients);
+ }
+ if (memberName != null) {
+ serverLauncherBuilder.setMemberName(memberName);
+ }
+ ServerLauncher serverLauncher = serverLauncherBuilder.build();
- String[] serverCommandLine = createStartServerCommandLine(serverLauncher,
- gemfirePropertiesFile, gemfireSecurityPropertiesFile, gemfireProperties, classpath,
- includeSystemClasspath, jvmArgsOpts, disableExitWhenOutOfMemory, initialHeap, maxHeap);
+ String[] serverCommandLine = createStartServerCommandLine(serverLauncher, gemfirePropertiesFile,
+ gemfireSecurityPropertiesFile, gemfireProperties, classpath, includeSystemClasspath,
+ jvmArgsOpts, disableExitWhenOutOfMemory, initialHeap, maxHeap);
- if (getGfsh().getDebug()) {
- getGfsh().logInfo(StringUtils.join(serverCommandLine, StringUtils.SPACE), null);
- }
+ if (getGfsh().getDebug()) {
+ getGfsh().logInfo(StringUtils.join(serverCommandLine, StringUtils.SPACE), null);
+ }
- Process serverProcess = new ProcessBuilder(serverCommandLine)
- .directory(new File(serverLauncher.getWorkingDirectory())).start();
+ Process serverProcess = new ProcessBuilder(serverCommandLine)
+ .directory(new File(serverLauncher.getWorkingDirectory())).start();
- serverProcess.getInputStream().close();
- serverProcess.getOutputStream().close();
+ serverProcess.getInputStream().close();
+ serverProcess.getOutputStream().close();
- // fix TRAC bug #51967 by using NON_BLOCKING on Windows
- final ProcessStreamReader.ReadingMode readingMode = SystemUtils.isWindows()
- ? ProcessStreamReader.ReadingMode.NON_BLOCKING : ProcessStreamReader.ReadingMode.BLOCKING;
+ // fix TRAC bug #51967 by using NON_BLOCKING on Windows
+ final ProcessStreamReader.ReadingMode readingMode = SystemUtils.isWindows()
+ ? ProcessStreamReader.ReadingMode.NON_BLOCKING : ProcessStreamReader.ReadingMode.BLOCKING;
- final StringBuffer message = new StringBuffer(); // need thread-safe StringBuffer
- ProcessStreamReader.InputListener inputListener = line -> {
- message.append(line);
- if (readingMode == ProcessStreamReader.ReadingMode.BLOCKING) {
- message.append(StringUtils.LINE_SEPARATOR);
- }
- };
+ final StringBuffer message = new StringBuffer(); // need thread-safe StringBuffer
+ ProcessStreamReader.InputListener inputListener = line -> {
+ message.append(line);
+ if (readingMode == ProcessStreamReader.ReadingMode.BLOCKING) {
+ message.append(StringUtils.LINE_SEPARATOR);
+ }
+ };
- ProcessStreamReader stderrReader = new ProcessStreamReader.Builder(serverProcess)
- .inputStream(serverProcess.getErrorStream()).inputListener(inputListener)
- .readingMode(readingMode).continueReadingMillis(2 * 1000).build().start();
+ ProcessStreamReader stderrReader = new ProcessStreamReader.Builder(serverProcess)
+ .inputStream(serverProcess.getErrorStream()).inputListener(inputListener)
+ .readingMode(readingMode).continueReadingMillis(2 * 1000).build().start();
- ServerLauncher.ServerState serverState;
+ ServerLauncher.ServerState serverState;
- String previousServerStatusMessage = null;
+ String previousServerStatusMessage = null;
- LauncherSignalListener serverSignalListener = new LauncherSignalListener();
+ LauncherSignalListener serverSignalListener = new LauncherSignalListener();
- final boolean registeredServerSignalListener =
- getGfsh().getSignalHandler().registerListener(serverSignalListener);
+ final boolean registeredServerSignalListener =
+ getGfsh().getSignalHandler().registerListener(serverSignalListener);
- try {
- getGfsh().logInfo(String.format(CliStrings.START_SERVER__RUN_MESSAGE,
- IOUtils.tryGetCanonicalPathElseGetAbsolutePath(
- new File(serverLauncher.getWorkingDirectory()))),
- null);
+ try {
+ getGfsh().logInfo(String.format(CliStrings.START_SERVER__RUN_MESSAGE, IOUtils
+ .tryGetCanonicalPathElseGetAbsolutePath(new File(serverLauncher.getWorkingDirectory()))),
+ null);
- serverState = ServerLauncher.ServerState.fromDirectory(workingDirectory, memberName);
- do {
- if (serverProcess.isAlive()) {
- Gfsh.print(".");
+ serverState = ServerLauncher.ServerState.fromDirectory(workingDirectory, memberName);
+ do {
+ if (serverProcess.isAlive()) {
+ Gfsh.print(".");
- synchronized (this) {
- TimeUnit.MILLISECONDS.timedWait(this, 500);
- }
+ synchronized (this) {
+ TimeUnit.MILLISECONDS.timedWait(this, 500);
+ }
- serverState = ServerLauncher.ServerState.fromDirectory(workingDirectory, memberName);
+ serverState = ServerLauncher.ServerState.fromDirectory(workingDirectory, memberName);
- String currentServerStatusMessage = serverState.getStatusMessage();
+ String currentServerStatusMessage = serverState.getStatusMessage();
- if (serverState.isStartingOrNotResponding()
- && !(StringUtils.isBlank(currentServerStatusMessage)
- || currentServerStatusMessage.equalsIgnoreCase(previousServerStatusMessage)
- || currentServerStatusMessage.trim().toLowerCase().equals("null"))) {
- Gfsh.println();
- Gfsh.println(currentServerStatusMessage);
- previousServerStatusMessage = currentServerStatusMessage;
- }
- } else {
- final int exitValue = serverProcess.exitValue();
+ if (serverState.isStartingOrNotResponding()
+ && !(StringUtils.isBlank(currentServerStatusMessage)
+ || currentServerStatusMessage.equalsIgnoreCase(previousServerStatusMessage)
+ || currentServerStatusMessage.trim().toLowerCase().equals("null"))) {
+ Gfsh.println();
+ Gfsh.println(currentServerStatusMessage);
+ previousServerStatusMessage = currentServerStatusMessage;
+ }
+ } else {
+ final int exitValue = serverProcess.exitValue();
- return ResultBuilder.createShellClientErrorResult(
- String.format(CliStrings.START_SERVER__PROCESS_TERMINATED_ABNORMALLY_ERROR_MESSAGE,
- exitValue, serverLauncher.getWorkingDirectory(), message.toString()));
+ return ResultBuilder.createShellClientErrorResult(
+ String.format(CliStrings.START_SERVER__PROCESS_TERMINATED_ABNORMALLY_ERROR_MESSAGE,
+ exitValue, serverLauncher.getWorkingDirectory(), message.toString()));
- }
- } while (!(registeredServerSignalListener && serverSignalListener.isSignaled())
- && serverState.isStartingOrNotResponding());
- } finally {
- stderrReader.stopAsync(StartMemberUtils.PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS); // stop
- // will
- // close
- // ErrorStream
- getGfsh().getSignalHandler().unregisterListener(serverSignalListener);
- }
+ }
+ } while (!(registeredServerSignalListener && serverSignalListener.isSignaled())
+ && serverState.isStartingOrNotResponding());
+ } finally {
+ stderrReader.stopAsync(StartMemberUtils.PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS); // stop
+ // will
+ // close
+ // ErrorStream
+ getGfsh().getSignalHandler().unregisterListener(serverSignalListener);
+ }
- Gfsh.println();
+ Gfsh.println();
- final boolean asyncStart =
- ServerLauncher.ServerState.isStartingNotRespondingOrNull(serverState);
+ final boolean asyncStart =
+ ServerLauncher.ServerState.isStartingNotRespondingOrNull(serverState);
- if (asyncStart) { // async start
- Gfsh.print(String.format(CliStrings.ASYNC_PROCESS_LAUNCH_MESSAGE, SERVER_TERM_NAME));
- return ResultBuilder.createInfoResult("");
- } else {
- return ResultBuilder.createInfoResult(serverState.toString());
- }
- } catch (IllegalArgumentException e) {
- String message = e.getMessage();
- if (message != null && message.matches(
- LocalizedStrings.Launcher_Builder_UNKNOWN_HOST_ERROR_MESSAGE.toLocalizedString(".+"))) {
- message =
- CliStrings.format(CliStrings.LAUNCHERLIFECYCLECOMMANDS__MSG__FAILED_TO_START_0_REASON_1,
- SERVER_TERM_NAME, message);
- }
- return ResultBuilder.createUserErrorResult(message);
- } catch (IllegalStateException e) {
- return ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder.createShellClientErrorResult(String.format(
- CliStrings.START_SERVER__GENERAL_ERROR_MESSAGE, this.toString(t, getGfsh().getDebug())));
+ if (asyncStart) { // async start
+ Gfsh.print(String.format(CliStrings.ASYNC_PROCESS_LAUNCH_MESSAGE, SERVER_TERM_NAME));
+ return ResultBuilder.createInfoResult("");
+ } else {
+ return ResultBuilder.createInfoResult(serverState.toString());
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartJConsoleCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartJConsoleCommand.java
index 1bcbbae..0e27bfd 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartJConsoleCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartJConsoleCommand.java
@@ -108,7 +108,7 @@ public class StartJConsoleCommand implements GfshCommand {
} catch (Throwable t) {
SystemFailure.checkFailure();
return ResultBuilder.createShellClientErrorResult(
- String.format(CliStrings.START_JCONSOLE__CATCH_ALL_ERROR_MESSAGE, toString(t, false)));
+ String.format(CliStrings.START_JCONSOLE__CATCH_ALL_ERROR_MESSAGE, t.getMessage()));
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartJVisualVMCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartJVisualVMCommand.java
index 699a482..48a711f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartJVisualVMCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartJVisualVMCommand.java
@@ -72,7 +72,7 @@ public class StartJVisualVMCommand implements GfshCommand {
} catch (Throwable t) {
SystemFailure.checkFailure();
return ResultBuilder.createShellClientErrorResult(
- String.format(CliStrings.START_JVISUALVM__ERROR_MESSAGE, toString(t, false)));
+ String.format(CliStrings.START_JVISUALVM__ERROR_MESSAGE, t.getMessage()));
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartPulseCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartPulseCommand.java
index fbf32d8..f07a90f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartPulseCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartPulseCommand.java
@@ -81,7 +81,7 @@ public class StartPulseCommand implements GfshCommand {
} catch (Throwable t) {
SystemFailure.checkFailure();
return ResultBuilder.createShellClientErrorResult(
- String.format(CliStrings.START_PULSE__ERROR, toString(t, false)));
+ String.format(CliStrings.START_PULSE__ERROR, t.getMessage()));
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartVsdCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartVsdCommand.java
index 7719611..36b5614 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartVsdCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartVsdCommand.java
@@ -85,7 +85,7 @@ public class StartVsdCommand implements GfshCommand {
} catch (Throwable t) {
SystemFailure.checkFailure();
return ResultBuilder.createShellClientErrorResult(
- String.format(CliStrings.START_VSD__ERROR_MESSAGE, toString(t, false)));
+ String.format(CliStrings.START_VSD__ERROR_MESSAGE, t.getMessage()));
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StatusLocatorCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StatusLocatorCommand.java
index 06f8350..fac8ad2 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StatusLocatorCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StatusLocatorCommand.java
@@ -16,18 +16,15 @@ package org.apache.geode.management.internal.cli.commands.lifecycle;
import static org.apache.geode.management.internal.cli.i18n.CliStrings.LOCATOR_TERM_NAME;
import static org.apache.geode.management.internal.cli.shell.MXBeanProvider.getMemberMXBean;
-import static org.apache.geode.management.internal.cli.util.HostUtils.getLocatorId;
import java.io.IOException;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
-import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.AbstractLauncher;
import org.apache.geode.distributed.LocatorLauncher;
import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.internal.lang.SystemUtils;
import org.apache.geode.management.MemberMXBean;
import org.apache.geode.management.cli.CliMetaData;
import org.apache.geode.management.cli.ConverterHint;
@@ -53,49 +50,39 @@ public class StatusLocatorCommand implements GfshCommand {
@CliOption(key = CliStrings.STATUS_LOCATOR__PID,
help = CliStrings.STATUS_LOCATOR__PID__HELP) final Integer pid,
@CliOption(key = CliStrings.STATUS_LOCATOR__DIR,
- help = CliStrings.STATUS_LOCATOR__DIR__HELP) final String workingDirectory) {
- try {
- if (StringUtils.isNotBlank(member)) {
- if (isConnectedAndReady()) {
- final MemberMXBean locatorProxy = getMemberMXBean(member);
+ help = CliStrings.STATUS_LOCATOR__DIR__HELP) final String workingDirectory)
+ throws Exception {
- if (locatorProxy != null) {
- LocatorLauncher.LocatorState state =
- LocatorLauncher.LocatorState.fromJson(locatorProxy.status());
- return createStatusLocatorResult(state);
- } else {
- return ResultBuilder.createUserErrorResult(CliStrings.format(
- CliStrings.STATUS_LOCATOR__NO_LOCATOR_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
- }
+ if (StringUtils.isNotBlank(member)) {
+ if (isConnectedAndReady()) {
+ final MemberMXBean locatorProxy = getMemberMXBean(member);
+
+ if (locatorProxy != null) {
+ LocatorLauncher.LocatorState state =
+ LocatorLauncher.LocatorState.fromJson(locatorProxy.status());
+ return createStatusLocatorResult(state);
} else {
return ResultBuilder.createUserErrorResult(CliStrings.format(
- CliStrings.STATUS_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, LOCATOR_TERM_NAME));
+ CliStrings.STATUS_LOCATOR__NO_LOCATOR_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
}
} else {
- final LocatorLauncher locatorLauncher =
- new LocatorLauncher.Builder().setCommand(LocatorLauncher.Command.STATUS)
- .setBindAddress(locatorHost).setDebug(isDebugging()).setPid(pid)
- .setPort(locatorPort).setWorkingDirectory(workingDirectory).build();
+ return ResultBuilder.createUserErrorResult(CliStrings.format(
+ CliStrings.STATUS_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, LOCATOR_TERM_NAME));
+ }
+ } else {
+ final LocatorLauncher locatorLauncher =
+ new LocatorLauncher.Builder().setCommand(LocatorLauncher.Command.STATUS)
+ .setBindAddress(locatorHost).setDebug(isDebugging()).setPid(pid).setPort(locatorPort)
+ .setWorkingDirectory(workingDirectory).build();
- final LocatorLauncher.LocatorState status = locatorLauncher.status();
- if (status.getStatus().equals(AbstractLauncher.Status.NOT_RESPONDING)
- || status.getStatus().equals(AbstractLauncher.Status.STOPPED)) {
- return ResultBuilder.createShellClientErrorResult(status.toString());
- }
- return createStatusLocatorResult(status);
+ final LocatorLauncher.LocatorState status = locatorLauncher.status();
+ if (status.getStatus().equals(AbstractLauncher.Status.NOT_RESPONDING)
+ || status.getStatus().equals(AbstractLauncher.Status.STOPPED)) {
+ return ResultBuilder.createShellClientErrorResult(status.toString());
}
- } catch (IllegalArgumentException | IllegalStateException e) {
- return ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder.createShellClientErrorResult(String.format(
- CliStrings.STATUS_LOCATOR__GENERAL_ERROR_MESSAGE, getLocatorId(locatorHost, locatorPort),
- StringUtils.defaultIfBlank(workingDirectory, SystemUtils.CURRENT_DIRECTORY),
- toString(t, getGfsh().getDebug())));
+ return createStatusLocatorResult(status);
}
+
}
protected Result createStatusLocatorResult(final LocatorLauncher.LocatorState state)
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StatusServerCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StatusServerCommand.java
index 43374ab..0a7fb8b 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StatusServerCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StatusServerCommand.java
@@ -16,10 +16,11 @@ package org.apache.geode.management.internal.cli.commands.lifecycle;
import static org.apache.geode.management.internal.cli.shell.MXBeanProvider.getMemberMXBean;
+import java.io.IOException;
+
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
-import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.AbstractLauncher;
import org.apache.geode.distributed.ServerLauncher;
import org.apache.geode.internal.lang.StringUtils;
@@ -42,52 +43,41 @@ public class StatusServerCommand implements GfshCommand {
@CliOption(key = CliStrings.STATUS_SERVER__PID,
help = CliStrings.STATUS_SERVER__PID__HELP) final Integer pid,
@CliOption(key = CliStrings.STATUS_SERVER__DIR,
- help = CliStrings.STATUS_SERVER__DIR__HELP) final String workingDirectory) {
- try {
- if (StringUtils.isNotBlank(member)) {
- if (isConnectedAndReady()) {
- final MemberMXBean serverProxy = getMemberMXBean(member);
+ help = CliStrings.STATUS_SERVER__DIR__HELP) final String workingDirectory)
+ throws IOException {
+
+ if (StringUtils.isNotBlank(member)) {
+ if (isConnectedAndReady()) {
+ final MemberMXBean serverProxy = getMemberMXBean(member);
- if (serverProxy != null) {
- return ResultBuilder.createInfoResult(
- ServerLauncher.ServerState.fromJson(serverProxy.status()).toString());
- } else {
- return ResultBuilder.createUserErrorResult(CliStrings.format(
- CliStrings.STATUS_SERVER__NO_SERVER_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
- }
+ if (serverProxy != null) {
+ return ResultBuilder.createInfoResult(
+ ServerLauncher.ServerState.fromJson(serverProxy.status()).toString());
} else {
return ResultBuilder.createUserErrorResult(CliStrings
- .format(CliStrings.STATUS_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Cache Server"));
+ .format(CliStrings.STATUS_SERVER__NO_SERVER_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
}
} else {
- final ServerLauncher serverLauncher = new ServerLauncher.Builder()
- .setCommand(ServerLauncher.Command.STATUS).setDebug(isDebugging())
- // NOTE since we do not know whether the "CacheServer" was enabled or not on the GemFire
- // server when it was started,
- // set the disableDefaultServer property in the ServerLauncher.Builder to default status
- // to the MemberMBean
- // TODO fix this hack! (how, the 'start server' loop needs it)
- .setDisableDefaultServer(true).setPid(pid).setWorkingDirectory(workingDirectory)
- .build();
+ return ResultBuilder.createUserErrorResult(CliStrings
+ .format(CliStrings.STATUS_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Cache Server"));
+ }
+ } else {
+ final ServerLauncher serverLauncher = new ServerLauncher.Builder()
+ .setCommand(ServerLauncher.Command.STATUS).setDebug(isDebugging())
+ // NOTE since we do not know whether the "CacheServer" was enabled or not on the GemFire
+ // server when it was started,
+ // set the disableDefaultServer property in the ServerLauncher.Builder to default status
+ // to the MemberMBean
+ // TODO fix this hack! (how, the 'start server' loop needs it)
+ .setDisableDefaultServer(true).setPid(pid).setWorkingDirectory(workingDirectory).build();
- final ServerLauncher.ServerState status = serverLauncher.status();
+ final ServerLauncher.ServerState status = serverLauncher.status();
- if (status.getStatus().equals(AbstractLauncher.Status.NOT_RESPONDING)
- || status.getStatus().equals(AbstractLauncher.Status.STOPPED)) {
- return ResultBuilder.createGemFireErrorResult(status.toString());
- }
- return ResultBuilder.createInfoResult(status.toString());
+ if (status.getStatus().equals(AbstractLauncher.Status.NOT_RESPONDING)
+ || status.getStatus().equals(AbstractLauncher.Status.STOPPED)) {
+ return ResultBuilder.createGemFireErrorResult(status.toString());
}
- } catch (IllegalArgumentException | IllegalStateException e) {
-
- return ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder.createShellClientErrorResult(String.format(
- CliStrings.STATUS_SERVER__GENERAL_ERROR_MESSAGE, toString(t, getGfsh().getDebug())));
+ return ResultBuilder.createInfoResult(status.toString());
}
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java
index ec3583c..e435b6e 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java
@@ -22,7 +22,6 @@ import java.util.concurrent.TimeUnit;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
-import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.AbstractLauncher;
import org.apache.geode.distributed.LocatorLauncher;
import org.apache.geode.internal.lang.StringUtils;
@@ -49,77 +48,65 @@ public class StopLocatorCommand implements GfshCommand {
@CliOption(key = CliStrings.STOP_LOCATOR__PID,
help = CliStrings.STOP_LOCATOR__PID__HELP) final Integer pid,
@CliOption(key = CliStrings.STOP_LOCATOR__DIR,
- help = CliStrings.STOP_LOCATOR__DIR__HELP) final String workingDirectory) {
- LocatorLauncher.LocatorState locatorState;
-
- try {
- if (StringUtils.isNotBlank(member)) {
- if (isConnectedAndReady()) {
- final MemberMXBean locatorProxy = getMemberMXBean(member);
+ help = CliStrings.STOP_LOCATOR__DIR__HELP) final String workingDirectory)
+ throws Exception {
- if (locatorProxy != null) {
- if (!locatorProxy.isLocator()) {
- throw new IllegalStateException(
- CliStrings.format(CliStrings.STOP_LOCATOR__NOT_LOCATOR_ERROR_MESSAGE, member));
- }
+ LocatorLauncher.LocatorState locatorState;
+ if (StringUtils.isNotBlank(member)) {
+ if (isConnectedAndReady()) {
+ final MemberMXBean locatorProxy = getMemberMXBean(member);
- if (locatorProxy.isServer()) {
- throw new IllegalStateException(CliStrings
- .format(CliStrings.STOP_LOCATOR__LOCATOR_IS_CACHE_SERVER_ERROR_MESSAGE, member));
- }
+ if (locatorProxy != null) {
+ if (!locatorProxy.isLocator()) {
+ throw new IllegalStateException(
+ CliStrings.format(CliStrings.STOP_LOCATOR__NOT_LOCATOR_ERROR_MESSAGE, member));
+ }
- locatorState = LocatorLauncher.LocatorState.fromJson(locatorProxy.status());
- locatorProxy.shutDownMember();
- } else {
- return ResultBuilder.createUserErrorResult(CliStrings.format(
- CliStrings.STOP_LOCATOR__NO_LOCATOR_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
+ if (locatorProxy.isServer()) {
+ throw new IllegalStateException(CliStrings
+ .format(CliStrings.STOP_LOCATOR__LOCATOR_IS_CACHE_SERVER_ERROR_MESSAGE, member));
}
+
+ locatorState = LocatorLauncher.LocatorState.fromJson(locatorProxy.status());
+ locatorProxy.shutDownMember();
} else {
- return ResultBuilder.createUserErrorResult(CliStrings.format(
- CliStrings.STOP_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, LOCATOR_TERM_NAME));
+ return ResultBuilder.createUserErrorResult(CliStrings
+ .format(CliStrings.STOP_LOCATOR__NO_LOCATOR_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
}
} else {
- final LocatorLauncher locatorLauncher =
- new LocatorLauncher.Builder().setCommand(LocatorLauncher.Command.STOP)
- .setDebug(isDebugging()).setPid(pid).setWorkingDirectory(workingDirectory).build();
-
- locatorState = locatorLauncher.status();
- locatorLauncher.stop();
+ return ResultBuilder.createUserErrorResult(CliStrings
+ .format(CliStrings.STOP_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, LOCATOR_TERM_NAME));
}
+ } else {
+ final LocatorLauncher locatorLauncher =
+ new LocatorLauncher.Builder().setCommand(LocatorLauncher.Command.STOP)
+ .setDebug(isDebugging()).setPid(pid).setWorkingDirectory(workingDirectory).build();
+
+ locatorState = locatorLauncher.status();
+ locatorLauncher.stop();
+ }
- if (AbstractLauncher.Status.ONLINE.equals(locatorState.getStatus())) {
- getGfsh().logInfo(
- String.format(CliStrings.STOP_LOCATOR__STOPPING_LOCATOR_MESSAGE,
- locatorState.getWorkingDirectory(), locatorState.getServiceLocation(),
- locatorState.getMemberName(), locatorState.getPid(), locatorState.getLogFile()),
- null);
+ if (AbstractLauncher.Status.ONLINE.equals(locatorState.getStatus())) {
+ getGfsh().logInfo(
+ String.format(CliStrings.STOP_LOCATOR__STOPPING_LOCATOR_MESSAGE,
+ locatorState.getWorkingDirectory(), locatorState.getServiceLocation(),
+ locatorState.getMemberName(), locatorState.getPid(), locatorState.getLogFile()),
+ null);
- StopWatch stopWatch = new StopWatch(true);
- while (locatorState.isVmWithProcessIdRunning()) {
- Gfsh.print(".");
- if (stopWatch.elapsedTimeMillis() > WAITING_FOR_STOP_TO_MAKE_PID_GO_AWAY_TIMEOUT_MILLIS) {
- break;
- }
- synchronized (this) {
- TimeUnit.MILLISECONDS.timedWait(this, 500);
- }
+ StopWatch stopWatch = new StopWatch(true);
+ while (locatorState.isVmWithProcessIdRunning()) {
+ Gfsh.print(".");
+ if (stopWatch.elapsedTimeMillis() > WAITING_FOR_STOP_TO_MAKE_PID_GO_AWAY_TIMEOUT_MILLIS) {
+ break;
+ }
+ synchronized (this) {
+ TimeUnit.MILLISECONDS.timedWait(this, 500);
}
-
- return ResultBuilder.createInfoResult(StringUtils.EMPTY);
- } else {
- return ResultBuilder.createUserErrorResult(locatorState.toString());
}
- } catch (IllegalArgumentException | IllegalStateException e) {
- return ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder.createShellClientErrorResult(String.format(
- CliStrings.STOP_LOCATOR__GENERAL_ERROR_MESSAGE, toString(t, getGfsh().getDebug())));
- } finally {
- Gfsh.redirectInternalJavaLoggers();
+
+ return ResultBuilder.createInfoResult(StringUtils.EMPTY);
+ } else {
+ return ResultBuilder.createUserErrorResult(locatorState.toString());
}
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopServerCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopServerCommand.java
index 526dcd8..ba05073 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopServerCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopServerCommand.java
@@ -21,7 +21,6 @@ import java.util.concurrent.TimeUnit;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
-import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.AbstractLauncher;
import org.apache.geode.distributed.ServerLauncher;
import org.apache.geode.internal.lang.StringUtils;
@@ -47,73 +46,61 @@ public class StopServerCommand implements GfshCommand {
@CliOption(key = CliStrings.STOP_SERVER__PID,
help = CliStrings.STOP_SERVER__PID__HELP) final Integer pid,
@CliOption(key = CliStrings.STOP_SERVER__DIR,
- help = CliStrings.STOP_SERVER__DIR__HELP) final String workingDirectory) {
+ help = CliStrings.STOP_SERVER__DIR__HELP) final String workingDirectory)
+ throws Exception {
ServerLauncher.ServerState serverState;
- try {
- if (StringUtils.isNotBlank(member)) {
- if (!isConnectedAndReady()) {
- return ResultBuilder.createUserErrorResult(CliStrings
- .format(CliStrings.STOP_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Cache Server"));
- }
-
- final MemberMXBean serverProxy = getMemberMXBean(member);
+ if (StringUtils.isNotBlank(member)) {
+ if (!isConnectedAndReady()) {
+ return ResultBuilder.createUserErrorResult(CliStrings
+ .format(CliStrings.STOP_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Cache Server"));
+ }
- if (serverProxy != null) {
- if (!serverProxy.isServer()) {
- throw new IllegalStateException(CliStrings
- .format(CliStrings.STOP_SERVER__MEMBER_IS_NOT_SERVER_ERROR_MESSAGE, member));
- }
+ final MemberMXBean serverProxy = getMemberMXBean(member);
- serverState = ServerLauncher.ServerState.fromJson(serverProxy.status());
- serverProxy.shutDownMember();
- } else {
- return ResultBuilder.createUserErrorResult(CliStrings
- .format(CliStrings.STOP_SERVER__NO_SERVER_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
+ if (serverProxy != null) {
+ if (!serverProxy.isServer()) {
+ throw new IllegalStateException(CliStrings
+ .format(CliStrings.STOP_SERVER__MEMBER_IS_NOT_SERVER_ERROR_MESSAGE, member));
}
+ serverState = ServerLauncher.ServerState.fromJson(serverProxy.status());
+ serverProxy.shutDownMember();
} else {
- final ServerLauncher serverLauncher =
- new ServerLauncher.Builder().setCommand(ServerLauncher.Command.STOP)
- .setDebug(isDebugging()).setPid(pid).setWorkingDirectory(workingDirectory).build();
-
- serverState = serverLauncher.status();
- serverLauncher.stop();
+ return ResultBuilder.createUserErrorResult(CliStrings
+ .format(CliStrings.STOP_SERVER__NO_SERVER_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
}
- if (AbstractLauncher.Status.ONLINE.equals(serverState.getStatus())) {
- getGfsh().logInfo(
- String.format(CliStrings.STOP_SERVER__STOPPING_SERVER_MESSAGE,
- serverState.getWorkingDirectory(), serverState.getServiceLocation(),
- serverState.getMemberName(), serverState.getPid(), serverState.getLogFile()),
- null);
-
- StopWatch stopWatch = new StopWatch(true);
- while (serverState.isVmWithProcessIdRunning()) {
- Gfsh.print(".");
- if (stopWatch.elapsedTimeMillis() > WAITING_FOR_STOP_TO_MAKE_PID_GO_AWAY_TIMEOUT_MILLIS) {
- break;
- }
- synchronized (this) {
- TimeUnit.MILLISECONDS.timedWait(this, 500);
- }
- }
+ } else {
+ final ServerLauncher serverLauncher =
+ new ServerLauncher.Builder().setCommand(ServerLauncher.Command.STOP)
+ .setDebug(isDebugging()).setPid(pid).setWorkingDirectory(workingDirectory).build();
- return ResultBuilder.createInfoResult(StringUtils.EMPTY);
- } else {
- return ResultBuilder.createUserErrorResult(serverState.toString());
+ serverState = serverLauncher.status();
+ serverLauncher.stop();
+ }
+
+ if (AbstractLauncher.Status.ONLINE.equals(serverState.getStatus())) {
+ getGfsh().logInfo(
+ String.format(CliStrings.STOP_SERVER__STOPPING_SERVER_MESSAGE,
+ serverState.getWorkingDirectory(), serverState.getServiceLocation(),
+ serverState.getMemberName(), serverState.getPid(), serverState.getLogFile()),
+ null);
+
+ StopWatch stopWatch = new StopWatch(true);
+ while (serverState.isVmWithProcessIdRunning()) {
+ Gfsh.print(".");
+ if (stopWatch.elapsedTimeMillis() > WAITING_FOR_STOP_TO_MAKE_PID_GO_AWAY_TIMEOUT_MILLIS) {
+ break;
+ }
+ synchronized (this) {
+ TimeUnit.MILLISECONDS.timedWait(this, 500);
+ }
}
- } catch (IllegalArgumentException | IllegalStateException e) {
- return ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder.createShellClientErrorResult(String.format(
- CliStrings.STOP_SERVER__GENERAL_ERROR_MESSAGE, toString(t, getGfsh().getDebug())));
- } finally {
- Gfsh.redirectInternalJavaLoggers();
+
+ return ResultBuilder.createInfoResult(StringUtils.EMPTY);
+ } else {
+ return ResultBuilder.createUserErrorResult(serverState.toString());
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/CreateSubregionException.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/EntityNotFoundException.java
similarity index 63%
rename from geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/CreateSubregionException.java
rename to geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/EntityNotFoundException.java
index 9aaf247..3f4f173 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/CreateSubregionException.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/EntityNotFoundException.java
@@ -12,27 +12,35 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.geode.management.internal.cli.exceptions;
-/**
- * Indicates inability to create a Subregion of a region.
- *
- * @since GemFire 8.0
- */
-// TODO - Abhishek - Include in GemFire Exception Enhancements
-public class CreateSubregionException extends RuntimeException {
+import org.apache.geode.GemFireException;
- private static final long serialVersionUID = 4387344870743824916L;
+public class EntityNotFoundException extends GemFireException {
- public CreateSubregionException(String message, Throwable cause) {
- super(message, cause);
+ private boolean statusOK;
+
+ public EntityNotFoundException() {}
+
+ public EntityNotFoundException(String message) {
+ super(message);
}
- public CreateSubregionException(String message) {
+ public EntityNotFoundException(String message, boolean statusOK) {
super(message);
+ this.statusOK = statusOK;
}
- public CreateSubregionException(Throwable cause) {
+ public EntityNotFoundException(Throwable cause) {
super(cause);
}
+
+ public EntityNotFoundException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public boolean isStatusOK() {
+ return statusOK;
+ }
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/IndexNotFoundException.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/IndexNotFoundException.java
deleted file mode 100644
index 402285b..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/exceptions/IndexNotFoundException.java
+++ /dev/null
@@ -1,33 +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.exceptions;
-
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-
-public class IndexNotFoundException extends Exception {
-
- private static final long serialVersionUID = 1L;
- final String indexName;
- final String message;
-
- public IndexNotFoundException(final String indexName) {
- this.indexName = indexName;
- this.message = CliStrings.format("Index \" {0} \" not found", indexName);
- }
-
- public String getMessage() {
- return this.message;
- }
-}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunction.java
index 1bbc3b5..f8668c0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunction.java
@@ -40,7 +40,7 @@ import org.apache.geode.internal.lang.ObjectUtils;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.util.ArrayUtils;
import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
-import org.apache.geode.management.internal.cli.util.DiskStoreNotFoundException;
+import org.apache.geode.management.internal.cli.exceptions.EntityNotFoundException;
/**
* The DescribeDiskStoreFunction class is an implementation of a GemFire Function used to collect
@@ -120,7 +120,7 @@ public class DescribeDiskStoreFunction extends FunctionAdapter implements Intern
context.getResultSender().lastResult(diskStoreDetails);
} else {
context.getResultSender()
- .sendException(new DiskStoreNotFoundException(
+ .sendException(new EntityNotFoundException(
String.format("A disk store with name (%1$s) was not found on member (%2$s).",
diskStoreName, memberName)));
}
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 e524c2d..55344d4 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
@@ -44,7 +44,6 @@ 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.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;
import org.apache.geode.management.internal.configuration.domain.XmlEntity;
@@ -105,7 +104,7 @@ public class RegionCreateFunction implements Function, InternalEntity {
new Object[] {String.valueOf(RegionCommandsUtils.PERSISTENT_OVERFLOW_SHORTCUTS)});
}
resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, null/* do not log */));
- } catch (IllegalArgumentException | CreateSubregionException e) {
+ } catch (IllegalArgumentException e) {
resultSender.lastResult(handleException(memberNameOrId, e.getMessage(), e));
} catch (RegionExistsException e) {
String exceptionMsg =
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionDestroyFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionDestroyFunction.java
index d7cf091..1aae338 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionDestroyFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionDestroyFunction.java
@@ -20,7 +20,6 @@ import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.internal.InternalEntity;
import org.apache.geode.internal.cache.xmlcache.CacheXml;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.configuration.domain.XmlEntity;
/**
@@ -44,29 +43,35 @@ public class RegionDestroyFunction implements Function, InternalEntity {
String regionPath = null;
try {
String functionId = context.getFunctionId();
- if (getId().equals(functionId)) {
- Object arguments = context.getArguments();
- if (arguments != null) {
- regionPath = (String) arguments;
- Cache cache = context.getCache();
- Region<?, ?> region = cache.getRegion(regionPath);
- region.destroyRegion();
- String regionName =
- regionPath.startsWith(Region.SEPARATOR) ? regionPath.substring(1) : regionPath;
- XmlEntity xmlEntity = new XmlEntity(CacheXml.REGION, "name", regionName);
- context.getResultSender().lastResult(new CliFunctionResult("", xmlEntity, regionPath));
- }
+ Object arguments = context.getArguments();
+
+ if (!getId().equals(functionId) || arguments == null) {
+ context.getResultSender().lastResult(new CliFunctionResult("", false,
+ "Function Id mismatch or arguments is not available."));
+ return;
+ }
+
+ regionPath = (String) arguments;
+ Cache cache = context.getCache();
+ Region<?, ?> region = cache.getRegion(regionPath);
+ // if the region is a distributed region, and is already destroyed by another member
+ if (region == null) {
+ context.getResultSender().lastResult(new CliFunctionResult("", true, "SUCCESS"));
+ return;
}
- context.getResultSender().lastResult(new CliFunctionResult("", false, "FAILURE"));
- } catch (IllegalStateException e) {
- context.getResultSender().lastResult(new CliFunctionResult("", e, null));
+
+ region.destroyRegion();
+ String regionName =
+ regionPath.startsWith(Region.SEPARATOR) ? regionPath.substring(1) : regionPath;
+ XmlEntity xmlEntity = new XmlEntity(CacheXml.REGION, "name", regionName);
+ context.getResultSender().lastResult(new CliFunctionResult("", xmlEntity, regionPath));
+
+ } catch (IllegalStateException ex) {
+ // user is trying to destroy something that can't destroyed.
+ context.getResultSender().lastResult(new CliFunctionResult("", false, ex.getMessage()));
} catch (Exception ex) {
context.getResultSender()
- .lastResult(new CliFunctionResult("",
- new RuntimeException(CliStrings.format(
- CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1,
- new Object[] {regionPath, ex.getMessage()})),
- null));
+ .lastResult(new CliFunctionResult("", ex, "failed to destroy " + regionPath));
}
}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutor.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutor.java
index c664a58..d4f5218 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutor.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandExecutor.java
@@ -18,7 +18,9 @@ import org.apache.logging.log4j.Logger;
import org.springframework.shell.event.ParseResult;
import org.springframework.util.ReflectionUtils;
+import org.apache.geode.SystemFailure;
import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.management.internal.cli.exceptions.EntityNotFoundException;
import org.apache.geode.management.internal.cli.exceptions.UserErrorException;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
import org.apache.geode.security.NotAuthorizedException;
@@ -40,16 +42,45 @@ public class CommandExecutor {
return ResultBuilder.createGemFireErrorResult("Command returned null: " + parseResult);
}
return result;
- } catch (NotAuthorizedException e) {
+ }
+
+ // for Authorization Exception, we need to throw them for higher level code to catch
+ catch (NotAuthorizedException e) {
logger.error("Not authorized to execute \"" + parseResult + "\".", e);
throw e;
- } catch (UserErrorException e) {
+ }
+
+ // for these exceptions, needs to create a UserErrorResult (still reported as error by gfsh)
+ // no need to log since this is a user error
+ catch (UserErrorException | IllegalStateException | IllegalArgumentException e) {
return ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (Exception e) {
+ }
+
+ // if entity not found, depending on the thrower's intention, report either as success or error
+ // no need to log since this is a user error
+ catch (EntityNotFoundException e) {
+ if (e.isStatusOK()) {
+ return ResultBuilder.createInfoResult("Skipping: " + e.getMessage());
+ } else {
+ return ResultBuilder.createUserErrorResult(e.getMessage());
+ }
+ }
+
+ // all other exceptions, log it and build an error result.
+ catch (Exception e) {
logger.error("Could not execute \"" + parseResult + "\".", e);
return ResultBuilder.createGemFireErrorResult(
"Error while processing command <" + parseResult + "> Reason : " + e.getMessage());
}
+
+ // for errors more lower-level than Exception, just throw them.
+ catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable t) {
+ SystemFailure.checkFailure();
+ throw t;
+ }
}
protected Object invokeCommand(ParseResult parseResult) {
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/DiskStoreNotFoundException.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/DiskStoreNotFoundException.java
deleted file mode 100644
index 1887f88..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/DiskStoreNotFoundException.java
+++ /dev/null
@@ -1,47 +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.util;
-
-import org.apache.geode.GemFireException;
-
-/**
- * The DiskStoreNotFoundException is a GemFireException class indicating that a disk store by name
- * could not be found on a member specified by name!
- * </p>
- *
- * @see org.apache.geode.GemFireException
- * @since GemFire 7.0
- */
-// TODO this GemFireException should be moved to a more appropriate package!
-@SuppressWarnings("unused")
-public class DiskStoreNotFoundException extends GemFireException {
- private static final long serialVersionUID = -5184836041554948093L;
-
- public DiskStoreNotFoundException() {}
-
- public DiskStoreNotFoundException(final String message) {
- super(message);
- }
-
- public DiskStoreNotFoundException(final Throwable cause) {
- super(cause);
- }
-
- public DiskStoreNotFoundException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/MemberNotFoundException.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/MemberNotFoundException.java
deleted file mode 100644
index 4a2ec4b..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/util/MemberNotFoundException.java
+++ /dev/null
@@ -1,47 +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.util;
-
-import org.apache.geode.management.internal.cli.exceptions.UserErrorException;
-
-/**
- * The MemberNotFoundException is a GemFirException indicating that a member by name could not be
- * found in the GemFire distributed system.
- * </p>
- *
- * @see org.apache.geode.GemFireException
- * @since GemFire 7.0
- */
-// TODO this GemFireException should be moved to a more appropriate package!
-@SuppressWarnings("unused")
-public class MemberNotFoundException extends UserErrorException {
- private static final long serialVersionUID = 5686788909239181174L;
-
- public MemberNotFoundException() {}
-
- public MemberNotFoundException(final String message) {
- super(message);
- }
-
- public MemberNotFoundException(final Throwable cause) {
- super(cause);
- }
-
- public MemberNotFoundException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
-}
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 c5c3ee0..cf85a8a 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
@@ -19,7 +19,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
-import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
@@ -63,15 +62,6 @@ public class DestroyRegionCommandDUnitTest {
gfsh.connectAndVerify(locator);
}
- @After
- public void after() throws Exception {
- // destroy regions
- gfsh.execute("destroy region --name=/Customer --if-exists");
- gfsh.execute("destroy region --name=/Order --if-exists");
- gfsh.execute("destroy region --name=/Customer_2 --if-exists");
- gfsh.execute("destroy region --name=/Customer_3 --if-exists");
- }
-
@Test
public void testDestroyDistributedRegion() {
MemberVM.invokeInEveryMember(() -> {
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandTest.java
index 7cfe126..f4352b2 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandTest.java
@@ -15,23 +15,31 @@
package org.apache.geode.management.internal.cli.commands;
-import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import java.util.ArrayList;
import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
+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.Result;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
import org.apache.geode.management.internal.cli.result.CommandResult;
-import org.apache.geode.test.junit.assertions.CommandResultAssert;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
import org.apache.geode.test.junit.categories.UnitTest;
import org.apache.geode.test.junit.rules.GfshParserRule;
@@ -43,36 +51,82 @@ public class DestroyRegionCommandTest {
private DestroyRegionCommand command;
private CommandResult result;
+ private CliFunctionResult result1, result2;
@Before
public void before() throws Exception {
command = spy(DestroyRegionCommand.class);
doReturn(mock(InternalCache.class)).when(command).getCache();
+
+ ResultCollector collector = mock(ResultCollector.class);
+ doReturn(collector).when(command).executeFunction(any(), any(), any(Set.class));
+
+ List<CliFunctionResult> functionResults = new ArrayList<>();
+ doReturn(functionResults).when(collector).getResult();
+ result1 = mock(CliFunctionResult.class);
+ result2 = mock(CliFunctionResult.class);
+ functionResults.add(result1);
+ functionResults.add(result2);
}
@Test
public void invalidRegion() throws Exception {
- result = parser.executeCommandWithInstance(command, "destroy region");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.getContent().toString()).contains("Invalid command");
+ parser.executeAndAssertThat(command, "destroy region").statusIsError()
+ .containsOutput("Invalid command");
- result = parser.executeCommandWithInstance(command, "destroy region --name=");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.getContent().toString()).contains("Invalid command");
+ parser.executeAndAssertThat(command, "destroy region --name=").statusIsError()
+ .containsOutput("Invalid command");
- result = parser.executeCommandWithInstance(command, "destroy region --name=/");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.getContent().toString()).contains("Invalid command");
+ parser.executeAndAssertThat(command, "destroy region --name=/").statusIsError()
+ .containsOutput("Invalid command");
}
@Test
public void whenNoRegionIsFoundOnAnyMembers() throws Exception {
doReturn(Collections.emptySet()).when(command).findMembersForRegion(any(), any());
- result = parser.executeCommandWithInstance(command, "destroy region --name=test");
- new CommandResultAssert(result).statusIsError()
+ parser.executeAndAssertThat(command, "destroy region --name=test").statusIsError()
.containsOutput("Could not find a Region with Region path");
- result = parser.executeCommandWithInstance(command, "destroy region --name=test --if-exists");
- new CommandResultAssert(result).statusIsSuccess();
+ parser.executeAndAssertThat(command, "destroy region --name=test --if-exists")
+ .statusIsSuccess();
+ }
+
+ @Test
+ public void multipleResultReturnedWithOneError() throws Exception {
+ // mock this to pass the member search call
+ doReturn(Collections.singleton(DistributedMember.class)).when(command)
+ .findMembersForRegion(any(), any());
+ when(result1.isSuccessful()).thenReturn(true);
+ when(result1.getMessage()).thenReturn("result1 message");
+ when(result1.getXmlEntity()).thenReturn(mock(XmlEntity.class));
+
+ when(result2.isSuccessful()).thenReturn(false);
+ when(result2.getMessage()).thenReturn("result2 message");
+
+ parser.executeAndAssertThat(command, "destroy region --name=test").statusIsError()
+ .containsOutput("result2 message");
+
+ // verify that xmlEntiry returned by the result1 is not saved to Cluster config
+ verify(command, never()).persistClusterConfiguration(any(), any());
+ }
+
+ @Test
+ public void multipleResultReturnedWithOneException() throws Exception {
+ // mock this to pass the member search call
+ doReturn(Collections.singleton(DistributedMember.class)).when(command)
+ .findMembersForRegion(any(), any());
+ when(result1.isSuccessful()).thenReturn(true);
+ when(result1.getMessage()).thenReturn("result1 message");
+ when(result1.getXmlEntity()).thenReturn(mock(XmlEntity.class));
+
+ when(result2.isSuccessful()).thenReturn(false);
+ when(result2.getThrowable()).thenReturn(new IllegalArgumentException("something happened"));
+
+ assertThatThrownBy(
+ () -> parser.executeCommandWithInstance(command, "destroy region --name=test"))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ // verify that xmlEntiry returned by the result1 is not saved to Cluster config
+ verify(command, never()).persistClusterConfiguration(any(), any());
}
}
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 f5eb780..eb15d05 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
@@ -43,10 +43,10 @@ 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.DiskStoreDetails;
+import org.apache.geode.management.internal.cli.exceptions.EntityNotFoundException;
import org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction;
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.util.DiskStoreNotFoundException;
import org.apache.geode.test.junit.categories.UnitTest;
/**
@@ -142,8 +142,8 @@ public class DiskStoreCommandsJUnitTest {
assertEquals(expectedDiskStoredDetails, actualDiskStoreDetails);
}
- @Test(expected = DiskStoreNotFoundException.class)
- public void testGetDiskStoreDescriptionThrowsDiskStoreNotFoundException() {
+ @Test(expected = EntityNotFoundException.class)
+ public void testGetDiskStoreDescriptionThrowsEntityNotFoundException() {
final String diskStoreName = "mockDiskStore";
final String memberId = "mockMember";
@@ -159,7 +159,7 @@ public class DiskStoreCommandsJUnitTest {
oneOf(mockFunctionExecutor).setArguments(with(equal(diskStoreName)));
will(returnValue(mockFunctionExecutor));
oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
- will(throwException(new DiskStoreNotFoundException("expected")));
+ will(throwException(new EntityNotFoundException("expected")));
}
});
@@ -168,7 +168,7 @@ public class DiskStoreCommandsJUnitTest {
try {
describeCommand.getDiskStoreDescription(memberId, diskStoreName);
- } catch (DiskStoreNotFoundException expected) {
+ } catch (EntityNotFoundException expected) {
assertEquals("expected", expected.getMessage());
throw expected;
}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ExportLogsCommandTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ExportLogsCommandTest.java
index 9c5d030..03a05a7 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ExportLogsCommandTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ExportLogsCommandTest.java
@@ -14,7 +14,10 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import static org.apache.geode.management.internal.cli.commands.ExportLogsCommand.*;
+import static org.apache.geode.management.internal.cli.commands.ExportLogsCommand.GIGABYTE;
+import static org.apache.geode.management.internal.cli.commands.ExportLogsCommand.KILOBYTE;
+import static org.apache.geode.management.internal.cli.commands.ExportLogsCommand.MEGABYTE;
+import static org.apache.geode.management.internal.cli.commands.ExportLogsCommand.TERABYTE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Matchers.eq;
@@ -179,7 +182,7 @@ public class ExportLogsCommandTest {
testResults2.addResult(member2, 60 * MEGABYTE);
doReturn(mockCache).when(spyCmd).getCache();
- doReturn(testMembers).when(spyCmd).getMembers(null, null);
+ doReturn(testMembers).when(spyCmd).getMembersIncludingLocators(null, null);
doReturn(testResults1).when(spyCmd)
.estimateLogSize(Matchers.any(SizeExportLogsFunction.Args.class), eq(member1));
doReturn(testResults2).when(spyCmd)
@@ -220,7 +223,7 @@ public class ExportLogsCommandTest {
testResults2.addResult(member2, 60 * MEGABYTE);
doReturn(mockCache).when(spyCmd).getCache();
- doReturn(testMembers).when(spyCmd).getMembers(null, null);
+ doReturn(testMembers).when(spyCmd).getMembersIncludingLocators(null, null);
doReturn(testResults1).when(spyCmd)
.estimateLogSize(Matchers.any(SizeExportLogsFunction.Args.class), eq(member1));
doReturn(testResults2).when(spyCmd)
@@ -261,7 +264,7 @@ public class ExportLogsCommandTest {
testResults1.addResult(member1, new ManagementException(sb.toString()));
doReturn(mockCache).when(spyCmd).getCache();
- doReturn(testMembers).when(spyCmd).getMembers(null, null);
+ doReturn(testMembers).when(spyCmd).getMembersIncludingLocators(null, null);
doReturn(testResults1).when(spyCmd)
.estimateLogSize(Matchers.any(SizeExportLogsFunction.Args.class), eq(member1));
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java
index 27c4142..a2ee67e 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java
@@ -14,441 +14,87 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS;
-import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
-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.MCAST_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.NAME;
-import static org.apache.geode.distributed.ConfigurationProperties.START_DEV_REST_API;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+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 static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
-import java.io.File;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
+import java.util.Collections;
-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.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
-import org.apache.geode.cache.execute.Function;
-import org.apache.geode.cache.execute.FunctionService;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.DistributionConfig;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.distributed.internal.ClusterConfigurationService;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.exceptions.EntityNotFoundException;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
import org.apache.geode.test.junit.categories.UnitTest;
-/**
- * The GfshCommandJUnitTest class is a test suite of test cases testing the contract and
- * functionality of the GfshCommand class for implementing GemFire shell (Gfsh) commands.
- *
- * @see GfshCommand
- * @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 GfshCommandJUnitTest {
- private Mockery mockContext;
-
- private static <T extends Function> T register(T function) {
- if (FunctionService.isRegistered(function.getId())) {
- function = (T) FunctionService.getFunction(function.getId());
- } else {
- FunctionService.registerFunction(function);
- }
-
- return function;
- }
-
- private static class DefaultGfshCommand implements GfshCommand {
- }
-
- private DefaultGfshCommand defaultGfshCommand;
+ private GfshCommand command;
+ private Gfsh gfsh;
+ private ClusterConfigurationService clusterConfigurationService;
@Before
- public void setup() {
- mockContext = new Mockery();
- mockContext.setImposteriser(ClassImposteriser.INSTANCE);
- mockContext.setThreadingPolicy(new Synchroniser());
-
- defaultGfshCommand = new DefaultGfshCommand();
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
-
- private GfshCommand createAbstractCommandsSupport(final InternalCache cache) {
- return new TestCommands(cache);
- }
-
- private DistributedMember createMockMember(final String memberId, final String memberName) {
- final DistributedMember mockMember =
- mockContext.mock(DistributedMember.class, "DistributedMember " + memberId);
-
- mockContext.checking(new Expectations() {
- {
- allowing(mockMember).getName();
- will(returnValue(memberName));
- allowing(mockMember).getId();
- will(returnValue(memberId));
- }
- });
-
- return mockMember;
- }
-
- @Test
- public void testConvertDefaultValue() {
- assertNull(defaultGfshCommand.convertDefaultValue(null, StringUtils.EMPTY));
- assertEquals(StringUtils.EMPTY,
- defaultGfshCommand.convertDefaultValue(StringUtils.EMPTY, "test"));
- assertEquals(StringUtils.SPACE,
- defaultGfshCommand.convertDefaultValue(StringUtils.SPACE, "testing"));
- assertEquals("tested",
- defaultGfshCommand.convertDefaultValue(CliMetaData.ANNOTATION_DEFAULT_VALUE, "tested"));
+ public void before() throws Exception {
+ command = spy(GfshCommand.class);
+ gfsh = mock(Gfsh.class);
+ clusterConfigurationService = mock(ClusterConfigurationService.class);
}
@Test
- public void testRegister() {
- try {
- final Function mockFunction = mockContext.mock(Function.class, "Function");
-
- mockContext.checking(new Expectations() {
- {
- exactly(3).of(mockFunction).getId();
- will(returnValue("testRegister"));
- oneOf(mockFunction).isHA();
- will(returnValue(true));
- oneOf(mockFunction).hasResult();
- will(returnValue(true));
- }
- });
+ public void isConnectedAndReady() throws Exception {
+ when(command.getGfsh()).thenReturn(null);
+ assertThat(command.isConnectedAndReady()).isFalse();
- final GfshCommand commands =
- createAbstractCommandsSupport(mockContext.mock(InternalCache.class));
+ when(command.getGfsh()).thenReturn(gfsh);
+ when(gfsh.isConnectedAndReady()).thenReturn(false);
+ assertThat(command.isConnectedAndReady()).isFalse();
- assertFalse(FunctionService.isRegistered("testRegister"));
- assertSame(mockFunction, register(mockFunction));
- assertTrue(FunctionService.isRegistered("testRegister"));
- } finally {
- FunctionService.unregisterFunction("testRegister");
- }
+ when(command.getGfsh()).thenReturn(gfsh);
+ when(gfsh.isConnectedAndReady()).thenReturn(true);
+ assertThat(command.isConnectedAndReady()).isTrue();
}
@Test
- public void testRegisteredAlready() {
- try {
- final Function registeredFunction = mockContext.mock(Function.class, "Registered Function");
- final Function unregisteredFunction =
- mockContext.mock(Function.class, "Unregistered Function");
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(registeredFunction).getId();
- will(returnValue("testRegisteredAlready"));
- oneOf(registeredFunction).isHA();
- will(returnValue(false));
- exactly(2).of(unregisteredFunction).getId();
- will(returnValue("testRegisteredAlready"));
- }
- });
-
- final GfshCommand commands =
- createAbstractCommandsSupport(mockContext.mock(InternalCache.class));
-
- FunctionService.registerFunction(registeredFunction);
+ public void persistClusterConfiguration() throws Exception {
+ when(command.getSharedConfiguration()).thenReturn(null);
+ Result result = ResultBuilder.createInfoResult("info");
+ Runnable runnable = mock(Runnable.class);
- assertTrue(FunctionService.isRegistered("testRegisteredAlready"));
- assertSame(registeredFunction, register(unregisteredFunction));
- assertTrue(FunctionService.isRegistered("testRegisteredAlready"));
- } finally {
- FunctionService.unregisterFunction("testRegisteredAlready");
- }
- }
+ command.persistClusterConfiguration(result, runnable);
+ assertThat(result.failedToPersist()).isTrue();
- @Test
- public void testToStringOnBoolean() {
- assertEquals("false", defaultGfshCommand.toString(null, null, null));
- assertEquals("true", defaultGfshCommand.toString(true, null, null));
- assertEquals("true", defaultGfshCommand.toString(Boolean.TRUE, null, null));
- assertEquals("false", defaultGfshCommand.toString(false, null, null));
- assertEquals("false", defaultGfshCommand.toString(Boolean.FALSE, null, null));
- assertEquals("false", defaultGfshCommand.toString(true, "false", "true"));
- assertEquals("true", defaultGfshCommand.toString(false, "false", "true"));
- assertEquals("Yes", defaultGfshCommand.toString(true, "Yes", "No"));
- assertEquals("Yes", defaultGfshCommand.toString(false, "No", "Yes"));
- assertEquals("TRUE", defaultGfshCommand.toString(Boolean.TRUE, "TRUE", "FALSE"));
- assertEquals("FALSE", defaultGfshCommand.toString(Boolean.FALSE, "TRUE", "FALSE"));
+ when(command.getSharedConfiguration()).thenReturn(clusterConfigurationService);
+ command.persistClusterConfiguration(result, runnable);
+ assertThat(result.failedToPersist()).isFalse();
}
@Test
- public void testToStringOnThrowable() {
- assertEquals("test", defaultGfshCommand.toString(new Throwable("test"), false));
+ public void getMember() throws Exception {
+ doReturn(null).when(command).findMember("test");
+ assertThatThrownBy(() -> command.getMember("test")).isInstanceOf(EntityNotFoundException.class);
}
@Test
- public void testToStringOnThrowablePrintingStackTrace() {
- final StringWriter writer = new StringWriter();
- final Throwable t = new Throwable("test");
-
- t.printStackTrace(new PrintWriter(writer));
-
- assertEquals(writer.toString(), defaultGfshCommand.toString(t, true));
- }
-
- private static class TestCommands implements GfshCommand {
-
- private final InternalCache cache;
-
- protected TestCommands(final InternalCache cache) {
- assert cache != null : "The InternalCache cannot be null!";
- this.cache = cache;
- }
-
- @Override
- public InternalCache getCache() {
- return this.cache;
- }
- }
-
- @Test
- public void testAddGemFirePropertyFileToCommandLine() {
- List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
-
- StartMemberUtils.addGemFirePropertyFile(commandLine, null);
- assertTrue(commandLine.isEmpty());
-
- File file = new File("/path/to/gemfire.properties");
- StartMemberUtils.addGemFirePropertyFile(commandLine, file);
- assertFalse(commandLine.isEmpty());
- assertTrue(commandLine.contains("-DgemfirePropertyFile=" + file.getAbsolutePath()));
+ public void getMembers() throws Exception {
+ String[] members = {"member"};
+ doReturn(Collections.emptySet()).when(command).findMembers(members, null);
+ assertThatThrownBy(() -> command.getMembers(members, null))
+ .isInstanceOf(EntityNotFoundException.class);
}
@Test
- public void testAddGemFireSystemPropertiesToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addGemFireSystemProperties(commandLine, new Properties());
- assertTrue(commandLine.isEmpty());
-
- final Properties gemfireProperties = new Properties();
- gemfireProperties.setProperty(LOCATORS, "localhost[11235]");
- gemfireProperties.setProperty(LOG_LEVEL, "config");
- gemfireProperties.setProperty(LOG_FILE, org.apache.commons.lang.StringUtils.EMPTY);
- gemfireProperties.setProperty(MCAST_PORT, "0");
- gemfireProperties.setProperty(NAME, "machine");
- StartMemberUtils.addGemFireSystemProperties(commandLine, gemfireProperties);
-
- assertFalse(commandLine.isEmpty());
- assertEquals(4, commandLine.size());
-
- for (final String propertyName : gemfireProperties.stringPropertyNames()) {
- final String propertyValue = gemfireProperties.getProperty(propertyName);
- if (org.apache.commons.lang.StringUtils.isBlank(propertyValue)) {
- for (final String systemProperty : commandLine) {
- assertFalse(systemProperty.startsWith(
- "-D" + DistributionConfig.GEMFIRE_PREFIX + "".concat(propertyName).concat("=")));
- }
- } else {
- assertTrue(commandLine.contains("-D" + DistributionConfig.GEMFIRE_PREFIX
- + "".concat(propertyName).concat("=").concat(propertyValue)));
- }
- }
- }
-
- @Test
- public void testAddGemFireSystemPropertiesToCommandLineWithRestAPI() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addGemFireSystemProperties(commandLine, new Properties());
- assertTrue(commandLine.isEmpty());
- final Properties gemfireProperties = new Properties();
- gemfireProperties.setProperty(LOCATORS, "localhost[11235]");
- gemfireProperties.setProperty(LOG_LEVEL, "config");
- gemfireProperties.setProperty(LOG_FILE, StringUtils.EMPTY);
- gemfireProperties.setProperty(MCAST_PORT, "0");
- gemfireProperties.setProperty(NAME, "machine");
- gemfireProperties.setProperty(START_DEV_REST_API, "true");
- gemfireProperties.setProperty(HTTP_SERVICE_PORT, "8080");
- gemfireProperties.setProperty(HTTP_SERVICE_BIND_ADDRESS, "localhost");
-
- StartMemberUtils.addGemFireSystemProperties(commandLine, gemfireProperties);
-
- assertFalse(commandLine.isEmpty());
- assertEquals(7, commandLine.size());
-
- for (final String propertyName : gemfireProperties.stringPropertyNames()) {
- final String propertyValue = gemfireProperties.getProperty(propertyName);
- if (StringUtils.isBlank(propertyValue)) {
- for (final String systemProperty : commandLine) {
- assertFalse(systemProperty.startsWith(
- "-D" + DistributionConfig.GEMFIRE_PREFIX + "".concat(propertyName).concat("=")));
- }
- } else {
- assertTrue(commandLine.contains("-D" + DistributionConfig.GEMFIRE_PREFIX
- + "".concat(propertyName).concat("=").concat(propertyValue)));
- }
- }
- }
-
- @Test
- public void testAddInitialHeapToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addInitialHeap(commandLine, null);
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addInitialHeap(commandLine, org.apache.commons.lang.StringUtils.EMPTY);
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addInitialHeap(commandLine, " ");
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addInitialHeap(commandLine, "512M");
- assertFalse(commandLine.isEmpty());
- assertEquals("-Xms512M", commandLine.get(0));
- }
-
- @Test
- public void testAddJvmArgumentsAndOptionsToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addJvmArgumentsAndOptions(commandLine, null);
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addJvmArgumentsAndOptions(commandLine, new String[] {});
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addJvmArgumentsAndOptions(commandLine,
- new String[] {"-DmyProp=myVal", "-d64", "-server", "-Xprof"});
- assertFalse(commandLine.isEmpty());
- assertEquals(4, commandLine.size());
- assertEquals("-DmyProp=myVal", commandLine.get(0));
- assertEquals("-d64", commandLine.get(1));
- assertEquals("-server", commandLine.get(2));
- assertEquals("-Xprof", commandLine.get(3));
- }
-
- @Test
- public void testAddMaxHeapToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addMaxHeap(commandLine, null);
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addMaxHeap(commandLine, org.apache.commons.lang.StringUtils.EMPTY);
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addMaxHeap(commandLine, " ");
- assertTrue(commandLine.isEmpty());
- StartMemberUtils.addMaxHeap(commandLine, "1024M");
- assertFalse(commandLine.isEmpty());
- assertEquals(3, commandLine.size());
- assertEquals("-Xmx1024M", commandLine.get(0));
- assertEquals("-XX:+UseConcMarkSweepGC", commandLine.get(1));
- assertEquals(
- "-XX:CMSInitiatingOccupancyFraction=" + StartMemberUtils.CMS_INITIAL_OCCUPANCY_FRACTION,
- commandLine.get(2));
- }
-
- @Test(expected = AssertionError.class)
- public void testReadPidWithNull() {
- try {
- StartMemberUtils.readPid(null);
- } catch (AssertionError expected) {
- assertEquals("The file from which to read the process ID (pid) cannot be null!",
- expected.getMessage());
- throw expected;
- }
- }
-
- @Test
- public void testReadPidWithNonExistingFile() {
- assertEquals(StartMemberUtils.INVALID_PID,
- StartMemberUtils.readPid(new File("/path/to/non_existing/pid.file")));
- }
-
- @Test
- public void testGetSystemClasspath() {
- assertEquals(System.getProperty("java.class.path"), StartMemberUtils.getSystemClasspath());
- }
-
- @Test
- public void testToClasspath() {
- final boolean EXCLUDE_SYSTEM_CLASSPATH = false;
- final boolean INCLUDE_SYSTEM_CLASSPATH = true;
- String[] jarFilePathnames =
- {"/path/to/user/libs/A.jar", "/path/to/user/libs/B.jar", "/path/to/user/libs/C.jar"};
- String[] userClasspaths = {"/path/to/classes:/path/to/libs/1.jar:/path/to/libs/2.jar",
- "/path/to/ext/libs/1.jar:/path/to/ext/classes:/path/to/ext/lib/10.jar"};
- String expectedClasspath = StartMemberUtils.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
- .concat(toClasspath(userClasspaths)).concat(File.pathSeparator)
- .concat(toClasspath(jarFilePathnames));
- assertEquals(expectedClasspath,
- StartMemberUtils.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, jarFilePathnames, userClasspaths));
- expectedClasspath = StartMemberUtils.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
- .concat(toClasspath(userClasspaths)).concat(File.pathSeparator)
- .concat(System.getProperty("java.class.path")).concat(File.pathSeparator)
- .concat(toClasspath(jarFilePathnames));
- assertEquals(expectedClasspath,
- StartMemberUtils.toClasspath(INCLUDE_SYSTEM_CLASSPATH, jarFilePathnames, userClasspaths));
- expectedClasspath = StartMemberUtils.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
- .concat(System.getProperty("java.class.path"));
- assertEquals(expectedClasspath,
- StartMemberUtils.toClasspath(INCLUDE_SYSTEM_CLASSPATH, null, (String[]) null));
- assertEquals(StartMemberUtils.GEODE_JAR_PATHNAME,
- StartMemberUtils.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, null, (String[]) null));
- assertEquals(StartMemberUtils.GEODE_JAR_PATHNAME,
- StartMemberUtils.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, new String[0], ""));
- }
-
- @Test
- public void testToClassPathOrder() {
- String userClasspathOne = "/path/to/user/lib/a.jar:/path/to/user/classes";
- String userClasspathTwo =
- "/path/to/user/lib/x.jar:/path/to/user/lib/y.jar:/path/to/user/lib/z.jar";
-
- String expectedClasspath = StartMemberUtils.getGemFireJarPath().concat(File.pathSeparator)
- .concat(userClasspathOne).concat(File.pathSeparator).concat(userClasspathTwo)
- .concat(File.pathSeparator).concat(System.getProperty("java.class.path"))
- .concat(File.pathSeparator).concat(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME)
- .concat(File.pathSeparator).concat(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME);
-
- String actualClasspath =
- StartMemberUtils.toClasspath(true,
- new String[] {StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME,
- StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME},
- userClasspathOne, userClasspathTwo);
-
- assertEquals(expectedClasspath, actualClasspath);
- }
-
- private String toClasspath(final String... jarFilePathnames) {
- String classpath = org.apache.commons.lang.StringUtils.EMPTY;
- if (jarFilePathnames != null) {
- for (final String jarFilePathname : jarFilePathnames) {
- classpath +=
- (classpath.isEmpty() ? org.apache.commons.lang.StringUtils.EMPTY : File.pathSeparator);
- classpath += jarFilePathname;
- }
- }
- return classpath;
+ public void getMembersIncludingLocators() throws Exception {
+ String[] members = {"member"};
+ doReturn(Collections.emptySet()).when(command).findMembersIncludingLocators(members, null);
+ assertThatThrownBy(() -> command.getMembersIncludingLocators(members, null))
+ .isInstanceOf(EntityNotFoundException.class);
}
}
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 bbd0b6c..0e9468c 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
@@ -20,6 +20,7 @@ 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.assertj.core.api.Assertions.assertThat;
import java.io.Serializable;
import java.util.Properties;
@@ -100,9 +101,8 @@ public class ListAndDescribeDiskStoreCommandsDUnitTest extends CliCommandTestBas
assertNotNull(commandResult);
assertEquals(Result.Status.ERROR, commandResult.getStatus());
- assertEquals(
- "A disk store with name (badDiskStoreName) was not found on member (producerServer).",
- toString(commandResult));
+ assertThat(toString(commandResult)).contains(
+ "A disk store with name (badDiskStoreName) was not found on member (producerServer).");
}
private static String toString(final Result result) {
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunctionJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunctionJUnitTest.java
index 2339838..cd65dbb 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunctionJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunctionJUnitTest.java
@@ -14,8 +14,12 @@
*/
package org.apache.geode.management.internal.cli.functions;
-import static org.assertj.core.api.Assertions.*;
-import static org.junit.Assert.*;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+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 java.io.File;
import java.util.Arrays;
@@ -55,7 +59,7 @@ import org.apache.geode.internal.lang.ObjectUtils;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.util.CollectionUtils;
import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
-import org.apache.geode.management.internal.cli.util.DiskStoreNotFoundException;
+import org.apache.geode.management.internal.cli.exceptions.EntityNotFoundException;
import org.apache.geode.test.dunit.IgnoredException;
import org.apache.geode.test.junit.categories.UnitTest;
@@ -610,7 +614,7 @@ public class DescribeDiskStoreFunctionJUnitTest {
}
@Test
- public void testExecuteThrowingDiskStoreNotFoundException() throws Exception {
+ public void testExecuteThrowingEntityNotFoundException() throws Exception {
final String diskStoreName = "testDiskStore";
final String memberId = "mockMemberId";
final String memberName = "mockMemberName";
@@ -649,7 +653,7 @@ public class DescribeDiskStoreFunctionJUnitTest {
String expected = String.format("A disk store with name (%1$s) was not found on member (%2$s).",
diskStoreName, memberName);
assertThatThrownBy(() -> testResultSender.getResults())
- .isInstanceOf(DiskStoreNotFoundException.class).hasMessage(expected);
+ .isInstanceOf(EntityNotFoundException.class).hasMessage(expected);
}
@Test
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/RegionDestroyFunctionTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/RegionDestroyFunctionTest.java
new file mode 100644
index 0000000..6088509
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/RegionDestroyFunctionTest.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.cli.functions;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.mockito.ArgumentCaptor;
+
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.FunctionContext;
+import org.apache.geode.cache.execute.ResultSender;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.test.junit.categories.UnitTest;
+
+
+@Category(UnitTest.class)
+public class RegionDestroyFunctionTest {
+
+ private RegionDestroyFunction function;
+ private FunctionContext context;
+ private InternalCache cache;
+ private ResultSender resultSender;
+ private ArgumentCaptor<CliFunctionResult> resultCaptor;
+
+ @Before
+ public void before() {
+ function = spy(RegionDestroyFunction.class);
+ context = mock(FunctionContext.class);
+ cache = mock(InternalCache.class);
+ resultSender = mock(ResultSender.class);
+ when(context.getCache()).thenReturn(cache);
+ when(context.getResultSender()).thenReturn(resultSender);
+ when(context.getArguments()).thenReturn("testRegion");
+ resultCaptor = ArgumentCaptor.forClass(CliFunctionResult.class);
+ }
+
+ @Test
+ public void functionContextIsWrong() throws Exception {
+ function.execute(context);
+ verify(resultSender).lastResult(resultCaptor.capture());
+ CliFunctionResult result = resultCaptor.getValue();
+
+ assertThat(result.isSuccessful()).isFalse();
+ assertThat(result.getMessage()).contains("Function Id mismatch or arguments is not available");
+ }
+
+ @Test
+ public void regionAlreadyDestroyed() throws Exception {
+ when(context.getFunctionId()).thenReturn(RegionDestroyFunction.class.getName());
+ when(cache.getRegion(any())).thenReturn(null);
+ function.execute(context);
+
+ verify(resultSender).lastResult(resultCaptor.capture());
+ CliFunctionResult result = resultCaptor.getValue();
+
+ assertThat(result.isSuccessful()).isTrue();
+ assertThat(result.getMessage()).contains("SUCCESS");
+ }
+
+ @Test
+ public void illegalStateExceptionWillNotThrowExceptionToCommand() throws Exception {
+ when(context.getFunctionId()).thenReturn(RegionDestroyFunction.class.getName());
+ Region region = mock(Region.class);
+ when(cache.getRegion(any())).thenReturn(region);
+ doThrow(new IllegalStateException("message")).when(region).destroyRegion();
+
+ function.execute(context);
+ verify(resultSender).lastResult(resultCaptor.capture());
+ CliFunctionResult result = resultCaptor.getValue();
+ assertThat(result.isSuccessful()).isFalse();
+ // will not populate the exception in the result, but only preserve the message
+ assertThat(result.getThrowable()).isNull();
+ assertThat(result.getMessage()).isEqualTo("message");
+ }
+}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/remote/CommandExecutorTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/remote/CommandExecutorTest.java
index 3020bc2..4f51f25 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/remote/CommandExecutorTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/remote/CommandExecutorTest.java
@@ -17,7 +17,11 @@ package org.apache.geode.management.internal.cli.remote;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import org.junit.Before;
import org.junit.Test;
@@ -25,6 +29,8 @@ import org.junit.experimental.categories.Category;
import org.springframework.shell.event.ParseResult;
import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.exceptions.EntityNotFoundException;
+import org.apache.geode.management.internal.cli.exceptions.UserErrorException;
import org.apache.geode.management.internal.cli.result.CommandResult;
import org.apache.geode.security.NotAuthorizedException;
import org.apache.geode.test.junit.categories.UnitTest;
@@ -39,7 +45,7 @@ public class CommandExecutorTest {
public void before() {
parseResult = mock(ParseResult.class);
result = mock(Result.class);
- executor = new CommandExecutor();
+ executor = spy(CommandExecutor.class);
}
@@ -52,46 +58,77 @@ public class CommandExecutorTest {
@Test
public void returnsResultAsExpected() throws Exception {
- executor = new CommandExecutor() {
- protected Object invokeCommand(ParseResult parseResult) {
- return result;
- }
- };
+ doReturn(result).when(executor).invokeCommand(any());
Object thisResult = executor.execute(parseResult);
assertThat(thisResult).isSameAs(result);
}
@Test
public void testNullResult() throws Exception {
- executor = new CommandExecutor() {
- protected Object invokeCommand(ParseResult parseResult) {
- return null;
- }
- };
+ doReturn(null).when(executor).invokeCommand(any());
Object thisResult = executor.execute(parseResult);
assertThat(thisResult.toString()).contains("Command returned null");
}
@Test
public void anyRuntimeExceptionGetsCaught() throws Exception {
- executor = new CommandExecutor() {
- protected Object invokeCommand(ParseResult parseResult) {
- throw new RuntimeException("my message here");
- }
- };
+ ;
+ doThrow(new RuntimeException("my message here")).when(executor).invokeCommand(any());
Object thisResult = executor.execute(parseResult);
+ assertThat(((CommandResult) thisResult).getStatus()).isEqualTo(Result.Status.ERROR);
assertThat(thisResult.toString()).contains("my message here");
}
@Test
public void notAuthorizedExceptionGetsThrown() throws Exception {
- executor = new CommandExecutor() {
- protected Object invokeCommand(ParseResult parseResult) {
- throw new NotAuthorizedException("Not Authorized");
- }
- };
+ doThrow(new NotAuthorizedException("Not Authorized")).when(executor).invokeCommand(any());
assertThatThrownBy(() -> executor.execute(parseResult))
.isInstanceOf(NotAuthorizedException.class);
+ }
+
+ @Test
+ public void anyIllegalArgumentExceptionGetsCaught() throws Exception {
+ ;
+ doThrow(new IllegalArgumentException("my message here")).when(executor).invokeCommand(any());
+ Object thisResult = executor.execute(parseResult);
+ assertThat(((CommandResult) thisResult).getStatus()).isEqualTo(Result.Status.ERROR);
+ assertThat(thisResult.toString()).contains("my message here");
+ }
+ @Test
+ public void anyIllegalStateExceptionGetsCaught() throws Exception {
+ ;
+ doThrow(new IllegalStateException("my message here")).when(executor).invokeCommand(any());
+ Object thisResult = executor.execute(parseResult);
+ assertThat(((CommandResult) thisResult).getStatus()).isEqualTo(Result.Status.ERROR);
+ assertThat(thisResult.toString()).contains("my message here");
+ }
+
+ @Test
+ public void anyUserErrorExceptionGetsCaught() throws Exception {
+ ;
+ doThrow(new UserErrorException("my message here")).when(executor).invokeCommand(any());
+ Object thisResult = executor.execute(parseResult);
+ assertThat(((CommandResult) thisResult).getStatus()).isEqualTo(Result.Status.ERROR);
+ assertThat(thisResult.toString()).contains("my message here");
+ }
+
+ @Test
+ public void anyEntityNotFoundException_statusOK() throws Exception {
+ ;
+ doThrow(new EntityNotFoundException("my message here", true)).when(executor)
+ .invokeCommand(any());
+ Object thisResult = executor.execute(parseResult);
+ assertThat(((CommandResult) thisResult).getStatus()).isEqualTo(Result.Status.OK);
+ assertThat(thisResult.toString()).contains("Skipping: my message here");
+ }
+
+ @Test
+ public void anyEntityNotFoundException_statusERROR() throws Exception {
+ ;
+ doThrow(new EntityNotFoundException("my message here")).when(executor).invokeCommand(any());
+ Object thisResult = executor.execute(parseResult);
+ assertThat(((CommandResult) thisResult).getStatus()).isEqualTo(Result.Status.ERROR);
+ assertThat(thisResult.toString()).contains("my message here");
}
}
diff --git a/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt b/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
index 37a4224..f6b4302 100755
--- a/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
+++ b/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
@@ -490,8 +490,7 @@ org/apache/geode/management/internal/cli/domain/RegionDescriptionPerMember,true,
org/apache/geode/management/internal/cli/domain/RegionInformation,true,1,dataPolicy:org/apache/geode/cache/DataPolicy,isRoot:boolean,name:java/lang/String,parentRegion:java/lang/String,path:java/lang/String,scope:org/apache/geode/cache/Scope,subRegionInformationSet:java/util/Set
org/apache/geode/management/internal/cli/domain/StackTracesPerMember,true,1,memberNameOrId:java/lang/String,stackTraces:byte[]
org/apache/geode/management/internal/cli/domain/SubscriptionQueueSizeResult,true,1,subscriptionQueueSize:long
-org/apache/geode/management/internal/cli/exceptions/CliException,true,-7603040667204839200
-org/apache/geode/management/internal/cli/exceptions/CreateSubregionException,true,4387344870743824916
+org/apache/geode/management/internal/cli/exceptions/EntityNotFoundException,false,statusOK:boolean
org/apache/geode/management/internal/cli/exceptions/IndexNotFoundException,true,1,indexName:java/lang/String,message:java/lang/String
org/apache/geode/management/internal/cli/functions/AlterRuntimeConfigFunction,true,1
org/apache/geode/management/internal/cli/functions/AsyncEventQueueFunctionArgs,true,-6524494645663740872,asyncEventQueueId:java/lang/String,batchSize:int,batchTimeInterval:int,diskStoreName:java/lang/String,diskSynchronous:boolean,dispatcherThreads:int,enableBatchConflation:boolean,forwardExpirationDestroy:boolean,gatewayEventFilters:java/lang/String[],gatewaySubstitutionFilter:java/lang/String,isParallel:boolean,listenerClassName:java/lang/String,listenerProperties:java/util/Properties, [...]
@@ -563,14 +562,12 @@ org/apache/geode/management/internal/cli/result/TableBuilderHelper$TooManyColumn
org/apache/geode/management/internal/cli/shell/JMXConnectionException,true,3872374016604940917,exceptionType:int
org/apache/geode/management/internal/cli/shell/JMXInvocationException,true,-4265451314790394366
org/apache/geode/management/internal/cli/shell/jline/ANSIHandler$ANSIStyle,false
-org/apache/geode/management/internal/cli/util/DiskStoreNotFoundException,true,-5184836041554948093
org/apache/geode/management/internal/cli/util/EvictionAttributesInfo,true,1,evictionAction:java/lang/String,evictionAlgorithm:java/lang/String,evictionMaxValue:int
org/apache/geode/management/internal/cli/util/ExportLogsCacheWriter,false,currentFile:java/nio/file/Path,currentOutputStream:java/io/BufferedOutputStream,isEmpty:boolean
org/apache/geode/management/internal/cli/util/FixedPartitionAttributesInfo,false,isPrimary:boolean,numBuckets:int,partitionName:java/lang/String
org/apache/geode/management/internal/cli/util/JConsoleNotFoundException,true,-1485615321440327206
org/apache/geode/management/internal/cli/util/LogFilter$LineFilterResult,false
org/apache/geode/management/internal/cli/util/MemberInformation,true,1,cacheXmlFilePath:java/lang/String,cpuUsage:java/lang/String,groups:java/lang/String,heapUsage:java/lang/String,host:java/lang/String,id:java/lang/String,initHeapSize:java/lang/String,locatorBindAddress:java/lang/String,locatorPort:int,locators:java/lang/String,logFilePath:java/lang/String,maxHeapSize:java/lang/String,name:java/lang/String,processId:java/lang/String,serverBindAddress:java/lang/String,statArchiveFilePat [...]
-org/apache/geode/management/internal/cli/util/MemberNotFoundException,true,5686788909239181174
org/apache/geode/management/internal/cli/util/VisualVmNotFoundException,true,-8491645604829510102
org/apache/geode/management/internal/configuration/domain/SharedConfigurationStatus,false
org/apache/geode/management/internal/configuration/functions/GetRegionNamesFunction,false
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommands.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommands.java
index 971293b..926b2d0 100755
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommands.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommands.java
@@ -29,10 +29,8 @@ import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
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.Function;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.cache.lucene.internal.cli.functions.LuceneCreateIndexFunction;
import org.apache.geode.cache.lucene.internal.cli.functions.LuceneDescribeIndexFunction;
@@ -48,6 +46,7 @@ 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.commands.GfshCommand;
+import org.apache.geode.management.internal.cli.exceptions.UserErrorException;
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.CommandResult;
@@ -56,7 +55,6 @@ 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.security.GemFireSecurityException;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
@@ -88,21 +86,7 @@ public class LuceneIndexCommands implements GfshCommand {
help = LuceneCliStrings.LUCENE_LIST_INDEX__STATS__HELP) final boolean stats) {
getSecurityService().authorize(Resource.CLUSTER, Operation.READ, LucenePermission.TARGET);
-
- try {
- return toTabularResult(getIndexListing(), stats);
- } catch (FunctionInvocationTargetException ignore) {
- return ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, LuceneCliStrings.LUCENE_LIST_INDEX));
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- getCache().getLogger().info(t);
- return ResultBuilder.createGemFireErrorResult(String
- .format(LuceneCliStrings.LUCENE_LIST_INDEX__ERROR_MESSAGE, toString(t, isDebugging())));
- }
+ return toTabularResult(getIndexListing(), stats);
}
@SuppressWarnings("unchecked")
@@ -230,27 +214,12 @@ public class LuceneIndexCommands implements GfshCommand {
@CliOption(key = LuceneCliStrings.LUCENE__REGION_PATH, mandatory = true,
optionContext = ConverterHint.REGION_PATH,
- help = LuceneCliStrings.LUCENE_DESCRIBE_INDEX__REGION_HELP) final String regionPath) {
+ help = LuceneCliStrings.LUCENE_DESCRIBE_INDEX__REGION_HELP) final String regionPath)
+ throws Exception {
getSecurityService().authorize(Resource.CLUSTER, Operation.READ, LucenePermission.TARGET);
-
- try {
- LuceneIndexInfo indexInfo = new LuceneIndexInfo(indexName, regionPath);
- return toTabularResult(getIndexDetails(indexInfo), true);
- } catch (FunctionInvocationTargetException ignore) {
- return ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, LuceneCliStrings.LUCENE_DESCRIBE_INDEX));
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (IllegalArgumentException e) {
- return ResultBuilder.createInfoResult(e.getMessage());
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- getCache().getLogger().info(t);
- return ResultBuilder.createGemFireErrorResult(String.format(
- LuceneCliStrings.LUCENE_DESCRIBE_INDEX__ERROR_MESSAGE, toString(t, isDebugging())));
- }
+ LuceneIndexInfo indexInfo = new LuceneIndexInfo(indexName, regionPath);
+ return toTabularResult(getIndexDetails(indexInfo), true);
}
@SuppressWarnings("unchecked")
@@ -288,32 +257,15 @@ public class LuceneIndexCommands implements GfshCommand {
@CliOption(key = LuceneCliStrings.LUCENE_SEARCH_INDEX__KEYSONLY,
unspecifiedDefaultValue = "false",
- help = LuceneCliStrings.LUCENE_SEARCH_INDEX__KEYSONLY__HELP) boolean keysOnly) {
-
+ help = LuceneCliStrings.LUCENE_SEARCH_INDEX__KEYSONLY__HELP) boolean keysOnly)
+ throws Exception {
getSecurityService().authorize(Resource.DATA, Operation.READ, regionPath);
+ LuceneQueryInfo queryInfo =
+ new LuceneQueryInfo(indexName, regionPath, queryString, defaultField, limit, keysOnly);
+ int pageSize = Integer.MAX_VALUE;
+ searchResults = getSearchResults(queryInfo);
+ return displayResults(pageSize, keysOnly);
- try {
- LuceneQueryInfo queryInfo =
- new LuceneQueryInfo(indexName, regionPath, queryString, defaultField, limit, keysOnly);
- int pageSize = Integer.MAX_VALUE;
- searchResults = getSearchResults(queryInfo);
- return displayResults(pageSize, keysOnly);
- } catch (FunctionInvocationTargetException ignore) {
- return ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, LuceneCliStrings.LUCENE_SEARCH_INDEX));
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (IllegalArgumentException e) {
- return ResultBuilder.createInfoResult(e.getMessage());
- } catch (GemFireSecurityException e) {
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- getCache().getLogger().info(t);
- return ResultBuilder.createGemFireErrorResult(String
- .format(LuceneCliStrings.LUCENE_SEARCH_INDEX__ERROR_MESSAGE, toString(t, isDebugging())));
- }
}
@CliCommand(value = LuceneCliStrings.LUCENE_DESTROY_INDEX,
@@ -526,7 +478,7 @@ public class LuceneIndexCommands implements GfshCommand {
data.accumulate("score", searchResults.get(i).getScore());
}
} else {
- throw new Exception(searchResults.get(i).getExceptionMessage());
+ throw new UserErrorException(searchResults.get(i).getExceptionMessage());
}
}
return ResultBuilder.buildResult(data);
@@ -548,7 +500,7 @@ public class LuceneIndexCommands implements GfshCommand {
Set<DistributedMember> targetMembers = CliUtil.getRegionAssociatedMembers(
functionArguments.getRegionPath(), getCache(), returnAllMembers);
if (targetMembers.isEmpty()) {
- throw new IllegalArgumentException(CliStrings.format(
+ throw new UserErrorException(CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__COULDNOT_FIND_MEMBERS_FOR_REGION_0,
new Object[] {functionArguments.getRegionPath()}));
}
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 e87ed02..4f2f61f 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
@@ -416,7 +416,7 @@ public class LuceneIndexCommandsDUnitTest implements Serializable {
CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_DESCRIBE_INDEX);
csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, "notAnIndex");
csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME);
- gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess().containsOutput(REGION_NAME);
+ gfsh.executeAndAssertThat(csb.toString()).statusIsError().containsOutput(REGION_NAME);
}
@Test
@@ -553,7 +553,7 @@ public class LuceneIndexCommandsDUnitTest implements Serializable {
csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "EFG");
csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field2");
- gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess()
+ gfsh.executeAndAssertThat(csb.toString()).statusIsError()
.containsOutput(getRegionNotFoundErrorMessage("/region"));
}
--
To stop receiving notification emails like this one, please contact
['"commits@geode.apache.org" <co...@geode.apache.org>'].