You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by js...@apache.org on 2017/06/23 22:48:58 UTC
[1/6] geode git commit: GEODE-2919: Provide finer grained security
Repository: geode
Updated Branches:
refs/heads/develop 3ee585c58 -> 451d12e83
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index 7ce0438..abe5d21 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -15,9 +15,11 @@
package org.apache.geode.management.internal.security;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
+import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.Permission;
import org.apache.geode.security.ResourcePermission;
@@ -46,10 +48,22 @@ public class TestCommand {
public static ResourcePermission clusterRead =
new ResourcePermission(Resource.CLUSTER, Operation.READ);
+ public static ResourcePermission clusterReadQuery =
+ new ResourcePermission(Resource.CLUSTER, Operation.READ, Target.QUERY);
public static ResourcePermission clusterWrite =
new ResourcePermission(Resource.CLUSTER, Operation.WRITE);
+ public static ResourcePermission clusterWriteDisk =
+ new ResourcePermission(Resource.CLUSTER, Operation.WRITE, Target.DISK);
public static ResourcePermission clusterManage =
new ResourcePermission(Resource.CLUSTER, Operation.MANAGE);
+ public static ResourcePermission clusterManageDisk =
+ new ResourcePermission(Resource.CLUSTER, Operation.MANAGE, Target.DISK);
+ public static ResourcePermission clusterManageGateway =
+ new ResourcePermission(Resource.CLUSTER, Operation.MANAGE, Target.GATEWAY);
+ public static ResourcePermission clusterManageJar =
+ new ResourcePermission(Resource.CLUSTER, Operation.MANAGE, Target.JAR);
+ public static ResourcePermission clusterManageQuery =
+ new ResourcePermission(Resource.CLUSTER, Operation.MANAGE, Target.QUERY);
private static List<TestCommand> testCommands = new ArrayList<>();
@@ -58,15 +72,15 @@ public class TestCommand {
}
private final String command;
- private final ResourcePermission permission;
+ private final ResourcePermission[] permissions;
- public TestCommand(String command, ResourcePermission permission) {
+ public TestCommand(String command, ResourcePermission... permissions) {
this.command = command;
- this.permission = permission;
+ this.permissions = permissions;
}
- private static void createTestCommand(String command, ResourcePermission permission) {
- TestCommand instance = new TestCommand(command, permission);
+ private static void createTestCommand(String command, ResourcePermission... permissions) {
+ TestCommand instance = new TestCommand(command, permissions);
testCommands.add(instance);
}
@@ -74,8 +88,8 @@ public class TestCommand {
return this.command;
}
- public ResourcePermission getPermission() {
- return this.permission;
+ public ResourcePermission[] getPermissions() {
+ return this.permissions;
}
public static List<TestCommand> getCommands() {
@@ -83,11 +97,21 @@ public class TestCommand {
return testCommands.stream().collect(Collectors.toList());
}
+ public static List<TestCommand> getOnlineCommands() {
+ return testCommands.stream().filter((x) -> ArrayUtils.isNotEmpty(x.getPermissions()))
+ .collect(Collectors.toList());
+ }
+
public static List<TestCommand> getPermittedCommands(Permission permission) {
List<TestCommand> result = new ArrayList<>();
for (TestCommand testCommand : testCommands) {
- ResourcePermission cPerm = testCommand.getPermission();
- if (cPerm != null && permission.implies(cPerm)) {
+ ResourcePermission[] cPerms = testCommand.getPermissions();
+ if (cPerms == null || cPerms.length == 0) {
+ // Skip offline commands.
+ continue;
+ }
+ boolean allPermissionsAreImplied = Arrays.stream(cPerms).allMatch(permission::implies);
+ if (allPermissionsAreImplied) {
result.add(testCommand);
}
}
@@ -107,6 +131,11 @@ public class TestCommand {
// CreateAlterDestroyRegionCommands
createTestCommand("alter region --name=RegionA --eviction-max=5000", regionAManage);
createTestCommand("create region --name=region12 --type=REPLICATE", dataManage);
+ createTestCommand("create region --name=region123 --type=PARTITION_PERSISTENT", dataManage,
+ clusterWriteDisk);
+ // This command requires an existing persistent region named "persistentRegion"
+ createTestCommand("create region --name=region1234 --template-region=/persistentRegion",
+ dataManage, clusterWriteDisk);
createTestCommand("destroy region --name=value", dataManage);
// Data Commands
@@ -124,28 +153,28 @@ public class TestCommand {
// Deploy commands
// createTestCommand("deploy --jar=group1_functions.jar --group=Group1", dataManage); // TODO:
// this command will fail in GfshCommandsSecurityTest at interceptor for jar file checking
- createTestCommand("undeploy --group=Group1", dataManage);
+ createTestCommand("undeploy --group=Group1", clusterManageJar);
// Diskstore Commands
- createTestCommand("backup disk-store --dir=foo", dataRead);
+ createTestCommand("backup disk-store --dir=foo", dataRead, clusterWriteDisk);
createTestCommand("list disk-stores", clusterRead);
- createTestCommand("create disk-store --name=foo --dir=bar", dataManage);
- createTestCommand("compact disk-store --name=foo", diskManage);
- createTestCommand("compact offline-disk-store --name=foo --disk-dirs=bar", null);
- createTestCommand("upgrade offline-disk-store --name=foo --disk-dirs=bar", null);
+ createTestCommand("create disk-store --name=foo --dir=bar", clusterManageDisk);
+ createTestCommand("compact disk-store --name=foo", clusterManageDisk);
+ createTestCommand("compact offline-disk-store --name=foo --disk-dirs=bar");
+ createTestCommand("upgrade offline-disk-store --name=foo --disk-dirs=bar");
createTestCommand("describe disk-store --name=foo --member=baz", clusterRead);
- createTestCommand("revoke missing-disk-store --id=foo", dataManage);
+ createTestCommand("revoke missing-disk-store --id=foo", clusterManageDisk);
createTestCommand("show missing-disk-stores", clusterRead);
- createTestCommand("describe offline-disk-store --name=foo --disk-dirs=bar", null);
- createTestCommand("export offline-disk-store --name=foo --disk-dirs=bar --dir=baz", null);
- createTestCommand("validate offline-disk-store --name=foo --disk-dirs=bar", null);
- createTestCommand("alter disk-store --name=foo --region=xyz --disk-dirs=bar", null);
- createTestCommand("destroy disk-store --name=foo", dataManage);
+ createTestCommand("describe offline-disk-store --name=foo --disk-dirs=bar");
+ createTestCommand("export offline-disk-store --name=foo --disk-dirs=bar --dir=baz");
+ createTestCommand("validate offline-disk-store --name=foo --disk-dirs=bar");
+ createTestCommand("alter disk-store --name=foo --region=xyz --disk-dirs=bar");
+ createTestCommand("destroy disk-store --name=foo", clusterManageDisk);
// DurableClientCommands
- createTestCommand("close durable-client --durable-client-id=client1", dataManage);
+ createTestCommand("close durable-client --durable-client-id=client1", clusterManageQuery);
createTestCommand("close durable-cq --durable-client-id=client1 --durable-cq-name=cq1",
- dataManage);
+ clusterManageQuery);
createTestCommand("show subscription-queue-size --durable-client-id=client1", clusterRead);
createTestCommand("list durable-cqs --durable-client-id=client1", clusterRead);
@@ -160,30 +189,30 @@ public class TestCommand {
createTestCommand("list functions", clusterRead);
// GfshHelpCommands
- createTestCommand("hint", null);
- createTestCommand("help", null);
+ createTestCommand("hint");
+ createTestCommand("help");
// IndexCommands
- createTestCommand("clear defined indexes", dataManage);
- createTestCommand("create defined indexes", dataManage);
+ createTestCommand("clear defined indexes", clusterManageQuery);
+ createTestCommand("create defined indexes", clusterManageQuery);
createTestCommand(
"create index --name=myKeyIndex --expression=region1.Id --region=RegionA --type=key",
- regionAManage);
+ clusterManageQuery);
createTestCommand("define index --name=myIndex1 --expression=exp1 --region=/RegionA",
- regionAManage);
- createTestCommand("destroy index --member=server2", dataManage);
- createTestCommand("destroy index --region=RegionA --member=server2", regionAManage);
- createTestCommand("list indexes", clusterRead);
+ clusterManageQuery);
+ createTestCommand("destroy index --member=server2", clusterManageQuery);
+ createTestCommand("destroy index --region=RegionA --member=server2", clusterManageQuery);
+ createTestCommand("list indexes", clusterReadQuery);
// LauncherLifecycleCommands
- createTestCommand("start jconsole", null);
- createTestCommand("start jvisualvm", null);
- createTestCommand("start locator --name=locator1", null);
- createTestCommand("start pulse", null);
- createTestCommand("start server --name=server1", null);
- createTestCommand("start vsd", null);
- createTestCommand("status locator", null);
- createTestCommand("status server", null);
+ createTestCommand("start jconsole");
+ createTestCommand("start jvisualvm");
+ createTestCommand("start locator --name=locator1");
+ createTestCommand("start pulse");
+ createTestCommand("start server --name=server1");
+ createTestCommand("start vsd");
+ createTestCommand("status locator");
+ createTestCommand("status server");
// createTestCommand("stop locator --name=locator1", clusterManage);
// createTestCommand("stop server --name=server1", clusterManage);
@@ -203,48 +232,52 @@ public class TestCommand {
// PDX Commands
- createTestCommand("configure pdx --read-serialized=true", dataManage);
- // createTestCommand("pdx rename --old=org.apache --new=com.pivotal --disk-store=ds1
- // --disk-dirs=/diskDir1", dataManage);
+ createTestCommand("configure pdx --read-serialized=true", clusterManage);
+ createTestCommand(
+ "pdx rename --old=org.apache --new=com.pivotal --disk-store=ds1 --disk-dirs=/diskDir1");
// Queue Commands
createTestCommand("create async-event-queue --id=myAEQ --listener=myApp.myListener",
- dataManage);
+ clusterManageJar);
+ createTestCommand(
+ "create async-event-queue --id=myAEQ --listener=myApp.myListener --persistent",
+ clusterManageJar, clusterWriteDisk);
+
createTestCommand("list async-event-queues", clusterRead);
// RegionCommands
createTestCommand("describe region --name=value", clusterRead);
- createTestCommand("list regions", dataRead);
+ createTestCommand("list regions", clusterRead);
// StatusCommands
createTestCommand("status cluster-config-service", clusterRead);
// Shell Commands
- createTestCommand("connect", null);
- createTestCommand("debug --state=on", null);
- createTestCommand("describe connection", null);
- createTestCommand("echo --string=\"Hello World!\"", null);
- createTestCommand("version", null);
- createTestCommand("sleep", null);
- createTestCommand("sh ls", null);
+ createTestCommand("connect");
+ createTestCommand("debug --state=on");
+ createTestCommand("describe connection");
+ createTestCommand("echo --string=\"Hello World!\"");
+ createTestCommand("version");
+ createTestCommand("sleep");
+ createTestCommand("sh ls");
// WAN Commands
createTestCommand("create gateway-sender --id=sender1 --remote-distributed-system-id=2",
- dataManage);
- createTestCommand("start gateway-sender --id=sender1", dataManage);
- createTestCommand("pause gateway-sender --id=sender1", dataManage);
- createTestCommand("resume gateway-sender --id=sender1", dataManage);
- createTestCommand("stop gateway-sender --id=sender1", dataManage);
- createTestCommand("load-balance gateway-sender --id=sender1", dataManage);
+ clusterManageGateway);
+ createTestCommand("start gateway-sender --id=sender1", clusterManageGateway);
+ createTestCommand("pause gateway-sender --id=sender1", clusterManageGateway);
+ createTestCommand("resume gateway-sender --id=sender1", clusterManageGateway);
+ createTestCommand("stop gateway-sender --id=sender1", clusterManageGateway);
+ createTestCommand("load-balance gateway-sender --id=sender1", clusterManageGateway);
createTestCommand("list gateways", clusterRead);
- createTestCommand("create gateway-receiver", dataManage);
- createTestCommand("start gateway-receiver", dataManage);
- createTestCommand("stop gateway-receiver", dataManage);
+ createTestCommand("create gateway-receiver", clusterManageGateway);
+ createTestCommand("start gateway-receiver", clusterManageGateway);
+ createTestCommand("stop gateway-receiver", clusterManageGateway);
createTestCommand("status gateway-receiver", clusterRead);
createTestCommand("status gateway-sender --id=sender1", clusterRead);
// ShellCommand
- createTestCommand("disconnect", null);
+ createTestCommand("disconnect");
// Misc commands
// createTestCommand("shutdown", clusterManage);
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java
index dcdc5c4..62ae2e2 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/LocatorServerStartupRule.java
@@ -20,13 +20,6 @@ import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_P
import static org.apache.geode.distributed.ConfigurationProperties.NAME;
import static org.apache.geode.test.dunit.Host.getHost;
-import org.apache.geode.internal.AvailablePortHelper;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.standalone.DUnitLauncher;
-import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
-import org.junit.rules.ExternalResource;
-import org.junit.rules.TemporaryFolder;
-
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
@@ -34,6 +27,14 @@ import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;
+import org.junit.rules.ExternalResource;
+import org.junit.rules.TemporaryFolder;
+
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.standalone.DUnitLauncher;
+import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
+
/**
* A rule to help you start locators and servers inside of a
@@ -118,6 +119,10 @@ public class LocatorServerStartupRule extends ExternalResource implements Serial
public MemberVM startServerAsJmxManager(int index) throws IOException {
Properties properties = new Properties();
+ return startServerAsJmxManager(index, properties);
+ }
+
+ public MemberVM startServerAsJmxManager(int index, Properties properties) throws IOException {
properties.setProperty(JMX_MANAGER_PORT, AvailablePortHelper.getRandomAvailableTCPPort() + "");
return startServerVM(index, properties, -1);
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/test/dunit/rules/MemberStarterRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/MemberStarterRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/MemberStarterRule.java
index 008ced7..5b4f2c1 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/MemberStarterRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/MemberStarterRule.java
@@ -38,6 +38,12 @@ import java.io.File;
import java.io.IOException;
import java.util.Properties;
+import org.junit.rules.ExternalResource;
+import org.junit.rules.TemporaryFolder;
+
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.security.SecurityManager;
+
/**
* the abstract class that's used by LocatorStarterRule and ServerStarterRule to avoid code
* duplication.
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/resources/org/apache/geode/codeAnalysis/sanctionedSerializables.txt
----------------------------------------------------------------------
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 28c6c8a..135f509 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
@@ -533,8 +533,8 @@ org/apache/geode/management/internal/cli/functions/AsyncEventQueueFunctionArgs,t
org/apache/geode/management/internal/cli/functions/ChangeLogLevelFunction,true,1
org/apache/geode/management/internal/cli/functions/CloseDurableClientFunction,true,1
org/apache/geode/management/internal/cli/functions/CloseDurableCqFunction,true,1
-org/apache/geode/management/internal/cli/functions/ContunuousQueryFunction,true,1
-org/apache/geode/management/internal/cli/functions/ContunuousQueryFunction$ClientInfo,true,1,isDurable:java/lang/String,primaryServer:java/lang/String,secondaryServer:java/lang/String,this$0:org/apache/geode/management/internal/cli/functions/ContunuousQueryFunction
+org/apache/geode/management/internal/cli/functions/ContinuousQueryFunction,true,1
+org/apache/geode/management/internal/cli/functions/ContinuousQueryFunction$ClientInfo,true,1,isDurable:java/lang/String,primaryServer:java/lang/String,secondaryServer:java/lang/String,this$0:org/apache/geode/management/internal/cli/functions/ContinuousQueryFunction
org/apache/geode/management/internal/cli/functions/CreateAsyncEventQueueFunction,true,1
org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction,true,1
org/apache/geode/management/internal/cli/functions/CreateDiskStoreFunction,true,1
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsDUnitTest.java b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsDUnitTest.java
index 7dd92bf..b0552ad 100644
--- a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsDUnitTest.java
+++ b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/ClientCommandsDUnitTest.java
@@ -14,8 +14,45 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import org.apache.geode.cache.*;
-import org.apache.geode.cache.client.*;
+import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_NETWORK_PARTITION_DETECTION;
+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.STATISTIC_ARCHIVE_FILE;
+import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLING_ENABLED;
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertNotNull;
+import static org.apache.geode.test.dunit.Assert.assertTrue;
+import static org.apache.geode.test.dunit.DistributedTestUtils.getDUnitLocatorPort;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
+import javax.management.ObjectName;
+
+import org.awaitility.Awaitility;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.AttributesFactory;
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.Scope;
+import org.apache.geode.cache.client.ClientCache;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.cache.client.ClientRegionFactory;
+import org.apache.geode.cache.client.ClientRegionShortcut;
+import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache.query.CqAttributesFactory;
import org.apache.geode.cache.query.QueryService;
@@ -40,27 +77,10 @@ import org.apache.geode.management.internal.cli.result.CompositeResultData.Secti
import org.apache.geode.management.internal.cli.result.TabularResultData;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.SerializableCallable;
+import org.apache.geode.test.dunit.SerializableRunnableIF;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.FlakyTest;
-import org.awaitility.Awaitility;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import javax.management.ObjectName;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.DistributedTestUtils.getDUnitLocatorPort;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
/**
* Dunit class for testing gemfire Client commands : list client , describe client
@@ -88,35 +108,34 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
assertNotNull(serverMember);
- manager.invoke(() -> {
- Awaitility.waitAtMost(2 * 60, TimeUnit.SECONDS).pollDelay(2, TimeUnit.SECONDS).until(() -> {
- final SystemManagementService service =
- (SystemManagementService) ManagementService.getManagementService(getCache());
- if (service == null) {
- getLogWriter().info("waitForListClientMbean Still probing for service");
- return false;
- } else {
- final ObjectName cacheServerMBeanName =
- service.getCacheServerMBeanName(port0, serverMember);
- CacheServerMXBean bean =
- service.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
- try {
- if (bean != null) {
- if (bean.getClientIds().length > 1) {
- return true;
+ manager.invoke(() -> Awaitility.waitAtMost(2 * 60, TimeUnit.SECONDS)
+ .pollDelay(2, TimeUnit.SECONDS).until(() -> {
+ final SystemManagementService service =
+ (SystemManagementService) ManagementService.getManagementService(getCache());
+ if (service == null) {
+ getLogWriter().info("waitForListClientMbean Still probing for service");
+ return false;
+ } else {
+ final ObjectName cacheServerMBeanName =
+ service.getCacheServerMBeanName(port0, serverMember);
+ CacheServerMXBean bean =
+ service.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
+ try {
+ if (bean != null) {
+ if (bean.getClientIds().length > 1) {
+ return true;
+ }
}
+ return false;
+
+ } catch (Exception e) {
+ LogWrapper.getInstance()
+ .warning("waitForListClientMbean Exception in waitForListClientMbean ::: "
+ + CliUtil.stackTraceAsString(e));
}
return false;
-
- } catch (Exception e) {
- LogWrapper.getInstance()
- .warning("waitForListClientMbean Exception in waitForListClientMbean ::: "
- + CliUtil.stackTraceAsString(e));
}
- return false;
- }
- });
- });
+ }));
}
public void waitForMbean() {
@@ -128,44 +147,41 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
assertNotNull(serverMember);
- manager.invoke(() -> {
- Awaitility.waitAtMost(2 * 60, TimeUnit.SECONDS).pollDelay(2, TimeUnit.SECONDS).until(() -> {
- final SystemManagementService service =
- (SystemManagementService) ManagementService.getManagementService(getCache());
- if (service == null) {
- getLogWriter().info("waitForMbean Still probing for service");
- return false;
- } else {
- final ObjectName cacheServerMBeanName =
- service.getCacheServerMBeanName(port0, serverMember);
- CacheServerMXBean bean =
- service.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
- try {
- ClientHealthStatus stats = bean.showClientStats(bean.getClientIds()[0]);
- Map<String, String> poolStats = stats.getPoolStats();
- if (poolStats.size() > 0) {
- Iterator<Entry<String, String>> it = poolStats.entrySet().iterator();
- while (it.hasNext()) {
- Entry<String, String> entry = it.next();
- String poolStatsStr = entry.getValue();
- String str[] = poolStatsStr.split(";");
- int numCqs = Integer.parseInt(str[3].substring(str[3].indexOf("=") + 1));
- if (numCqs == 3) {
- return true;
+ manager.invoke(() -> Awaitility.waitAtMost(2 * 60, TimeUnit.SECONDS)
+ .pollDelay(2, TimeUnit.SECONDS).until(() -> {
+ final SystemManagementService service =
+ (SystemManagementService) ManagementService.getManagementService(getCache());
+ if (service == null) {
+ getLogWriter().info("waitForMbean Still probing for service");
+ return false;
+ } else {
+ final ObjectName cacheServerMBeanName =
+ service.getCacheServerMBeanName(port0, serverMember);
+ CacheServerMXBean bean =
+ service.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
+ try {
+ ClientHealthStatus stats = bean.showClientStats(bean.getClientIds()[0]);
+ Map<String, String> poolStats = stats.getPoolStats();
+ if (poolStats.size() > 0) {
+ for (Entry<String, String> entry : poolStats.entrySet()) {
+ String poolStatsStr = entry.getValue();
+ String str[] = poolStatsStr.split(";");
+ int numCqs = Integer.parseInt(str[3].substring(str[3].indexOf("=") + 1));
+ if (numCqs == 3) {
+ return true;
+ }
}
}
+ return false;
+
+ } catch (Exception e) {
+ LogWrapper.getInstance().warning(
+ "waitForMbean Exception in waitForMbean ::: " + CliUtil.stackTraceAsString(e));
}
return false;
- } catch (Exception e) {
- LogWrapper.getInstance().warning(
- "waitForMbean Exception in waitForMbean ::: " + CliUtil.stackTraceAsString(e));
}
- return false;
-
- }
- });
- });
+ }));
}
public void waitForListClientMbean3() {
@@ -179,59 +195,56 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
assertNotNull(serverMember1);
- manager.invoke(() -> {
- Awaitility.waitAtMost(2 * 60, TimeUnit.SECONDS).pollDelay(2, TimeUnit.SECONDS).until(() -> {
- final SystemManagementService service =
- (SystemManagementService) ManagementService.getManagementService(getCache());
- if (service == null) {
- getLogWriter().info("waitForListClientMbean3 Still probing for service");
- return false;
- } else {
- final ObjectName cacheServerMBeanName1 =
- service.getCacheServerMBeanName(port0, serverMember1);
- final ObjectName cacheServerMBeanName2 =
- service.getCacheServerMBeanName(port1, serverMember2);
- CacheServerMXBean bean1 =
- service.getMBeanProxy(cacheServerMBeanName1, CacheServerMXBean.class);
- CacheServerMXBean bean2 =
- service.getMBeanProxy(cacheServerMBeanName2, CacheServerMXBean.class);
- try {
- if (bean1 != null && bean2 != null) {
- if (bean1.getClientIds().length > 0 && bean2.getClientIds().length > 0) {
- return true;
+ manager.invoke(() -> Awaitility.waitAtMost(2 * 60, TimeUnit.SECONDS)
+ .pollDelay(2, TimeUnit.SECONDS).until(() -> {
+ final SystemManagementService service =
+ (SystemManagementService) ManagementService.getManagementService(getCache());
+ if (service == null) {
+ getLogWriter().info("waitForListClientMbean3 Still probing for service");
+ return false;
+ } else {
+ final ObjectName cacheServerMBeanName1 =
+ service.getCacheServerMBeanName(port0, serverMember1);
+ final ObjectName cacheServerMBeanName2 =
+ service.getCacheServerMBeanName(port1, serverMember2);
+ CacheServerMXBean bean1 =
+ service.getMBeanProxy(cacheServerMBeanName1, CacheServerMXBean.class);
+ CacheServerMXBean bean2 =
+ service.getMBeanProxy(cacheServerMBeanName2, CacheServerMXBean.class);
+ try {
+ if (bean1 != null && bean2 != null) {
+ if (bean1.getClientIds().length > 0 && bean2.getClientIds().length > 0) {
+ return true;
+ }
}
+ return false;
+
+ } catch (Exception e) {
+ LogWrapper.getInstance()
+ .warning("waitForListClientMbean3 Exception in waitForListClientMbean ::: "
+ + CliUtil.stackTraceAsString(e));
}
return false;
-
- } catch (Exception e) {
- LogWrapper.getInstance()
- .warning("waitForListClientMbean3 Exception in waitForListClientMbean ::: "
- + CliUtil.stackTraceAsString(e));
}
- return false;
- }
- });
- });
+ }));
}
@Ignore("disabled for unknown reason")
@Test
public void testDescribeClientWithServers3() throws Exception {
setupSystem3();
- String commandString = CliStrings.DESCRIBE_CLIENT + " --" + CliStrings.DESCRIBE_CLIENT__ID
- + "=\"" + clientId + "\"";
+ String commandString;
final VM server1 = Host.getHost(0).getVM(1);
final VM server2 = Host.getHost(0).getVM(3);
final VM manager = Host.getHost(0).getVM(0);
String serverName1 =
- (String) server1.invoke("get DistributedMemberID ", () -> getDistributedMemberId());
+ (String) server1.invoke("get DistributedMemberID ", this::getDistributedMemberId);
- String serverName2 =
- (String) server2.invoke("get DistributedMemberID ", () -> getDistributedMemberId());
+ String serverName2 = server2.invoke("get DistributedMemberID ", this::getDistributedMemberId);
final DistributedMember serverMember1 = getMember(server1);
- String[] clientIds = (String[]) manager.invoke("get Client Ids", () -> {
+ String[] clientIds = manager.invoke("get Client Ids", () -> {
final SystemManagementService service =
(SystemManagementService) ManagementService.getManagementService(getCache());
@@ -250,7 +263,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
final DistributedMember serverMember2 = getMember(server2);
- String[] clientIds2 = (String[]) manager.invoke("get Client Ids", () -> {
+ String[] clientIds2 = manager.invoke("get Client Ids", () -> {
final SystemManagementService service =
(SystemManagementService) ManagementService.getManagementService(getCache());
@@ -307,21 +320,21 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
SectionResultData section = resultData.retrieveSection("InfoSection");
assertNotNull(section);
for (int i = 0; i < 1; i++) {
- TabularResultData tableRsultData = section.retrieveTableByIndex(i);
- getLogWriter().info("testDescribeClientWithServers getHeader=" + tableRsultData.getHeader());
- assertNotNull(tableRsultData);
+ TabularResultData tableResultData = section.retrieveTableByIndex(i);
+ getLogWriter().info("testDescribeClientWithServers getHeader=" + tableResultData.getHeader());
+ assertNotNull(tableResultData);
- List<String> minConn = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
- List<String> maxConn = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
- List<String> redudancy =
- tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUDANCY);
- List<String> numCqs = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_CQs);
+ List<String> minConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
+ List<String> maxConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
+ List<String> redundancy =
+ tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUNDANCY);
+ List<String> numCqs = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_CQs);
getLogWriter().info("testDescribeClientWithServers getHeader numCqs =" + numCqs);
assertTrue(minConn.contains("1"));
assertTrue(maxConn.contains("-1"));
- assertTrue(redudancy.contains("1"));
+ assertTrue(redundancy.contains("1"));
assertTrue(numCqs.contains("3"));
String puts = section.retrieveString(CliStrings.DESCRIBE_CLIENT_COLUMN_PUTS);
assertTrue(puts.equals("2"));
@@ -358,8 +371,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
getLogWriter().info("testDescribeClient commandStr=" + commandString);
final VM server1 = Host.getHost(0).getVM(1);
- String serverName =
- (String) server1.invoke("get distributed member Id", () -> getDistributedMemberId());
+ String serverName = server1.invoke("get distributed member Id", this::getDistributedMemberId);
CommandResult commandResult = executeCommand(commandString);
getLogWriter().info("testDescribeClient commandResult=" + commandResult);
@@ -371,17 +383,18 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
CompositeResultData resultData = (CompositeResultData) commandResult.getResultData();
SectionResultData section = resultData.retrieveSection("InfoSection");
assertNotNull(section);
- TabularResultData tableRsultData = section.retrieveTable("Pool Stats For Pool Name = DEFAULT");
- assertNotNull(tableRsultData);
+ TabularResultData tableResultData = section.retrieveTable("Pool Stats For Pool Name = DEFAULT");
+ assertNotNull(tableResultData);
- List<String> minConn = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
- List<String> maxConn = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
- List<String> redudancy = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUDANCY);
- List<String> numCqs = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_CQs);
+ List<String> minConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
+ List<String> maxConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
+ List<String> redundancy =
+ tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUNDANCY);
+ List<String> numCqs = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_CQs);
assertTrue(minConn.contains("1"));
assertTrue(maxConn.contains("-1"));
- assertTrue(redudancy.contains("1"));
+ assertTrue(redundancy.contains("1"));
assertTrue(numCqs.contains("3"));
String puts = section.retrieveString(CliStrings.DESCRIBE_CLIENT_COLUMN_PUTS);
assertTrue(puts.equals("2"));
@@ -417,8 +430,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
getLogWriter().info("testDescribeClientWithServers commandStr=" + commandString);
final VM server1 = Host.getHost(0).getVM(1);
- String serverName =
- (String) server1.invoke("get Distributed Member Id", () -> getDistributedMemberId());
+ String serverName = server1.invoke("get Distributed Member Id", this::getDistributedMemberId);
CommandResult commandResult = executeCommand(commandString);
getLogWriter().info("testDescribeClientWithServers commandResult=" + commandResult);
@@ -430,17 +442,18 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
CompositeResultData resultData = (CompositeResultData) commandResult.getResultData();
SectionResultData section = resultData.retrieveSection("InfoSection");
assertNotNull(section);
- TabularResultData tableRsultData = section.retrieveTable("Pool Stats For Pool Name = DEFAULT");
- assertNotNull(tableRsultData);
+ TabularResultData tableResultData = section.retrieveTable("Pool Stats For Pool Name = DEFAULT");
+ assertNotNull(tableResultData);
- List<String> minConn = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
- List<String> maxConn = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
- List<String> redudancy = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUDANCY);
- List<String> numCqs = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_CQs);
+ List<String> minConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
+ List<String> maxConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
+ List<String> redundancy =
+ tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUNDANCY);
+ List<String> numCqs = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_CQs);
assertTrue(minConn.contains("1"));
assertTrue(maxConn.contains("-1"));
- assertTrue(redudancy.contains("1"));
+ assertTrue(redundancy.contains("1"));
assertTrue(numCqs.contains("3"));
String puts = section.retrieveString(CliStrings.DESCRIBE_CLIENT_COLUMN_PUTS);
assertTrue(puts.equals("2"));
@@ -483,7 +496,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
final DistributedMember serverMember = getMember(server1);
- String[] clientIds = (String[]) manager.invoke("get client Ids", () -> {
+ String[] clientIds = manager.invoke("get client Ids", () -> {
final SystemManagementService service =
(SystemManagementService) ManagementService.getManagementService(getCache());
final ObjectName cacheServerMBeanName = service.getCacheServerMBeanName(port0, serverMember);
@@ -491,8 +504,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
return bean.getClientIds();
});
- String serverName =
- (String) server1.invoke("get distributed member Id", () -> getDistributedMemberId());
+ String serverName = server1.invoke("get distributed member Id", this::getDistributedMemberId);
CommandResult commandResult = executeCommand(commandString);
getLogWriter().info("testListClient commandResult=" + commandResult);
@@ -504,13 +516,13 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
CompositeResultData resultData = (CompositeResultData) commandResult.getResultData();
SectionResultData section = resultData.retrieveSection("section1");
assertNotNull(section);
- TabularResultData tableRsultData = section.retrieveTable("TableForClientList");
- assertNotNull(tableRsultData);
+ TabularResultData tableResultData = section.retrieveTable("TableForClientList");
+ assertNotNull(tableResultData);
List<String> serverNames =
- tableRsultData.retrieveAllValues(CliStrings.LIST_CLIENT_COLUMN_SERVERS);
+ tableResultData.retrieveAllValues(CliStrings.LIST_CLIENT_COLUMN_SERVERS);
List<String> clientNames =
- tableRsultData.retrieveAllValues(CliStrings.LIST_CLIENT_COLUMN_Clients);
+ tableResultData.retrieveAllValues(CliStrings.LIST_CLIENT_COLUMN_Clients);
getLogWriter().info("testListClients serverNames : " + serverNames);
getLogWriter().info("testListClients clientNames : " + clientNames);
@@ -543,7 +555,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
final DistributedMember serverMember = getMember(server1);
- String[] clientIds = (String[]) manager.invoke("get client Ids", () -> {
+ String[] clientIds = manager.invoke("get client Ids", () -> {
final SystemManagementService service =
(SystemManagementService) ManagementService.getManagementService(getCache());
final ObjectName cacheServerMBeanName = service.getCacheServerMBeanName(port0, serverMember);
@@ -551,11 +563,9 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
return bean.getClientIds();
});
- String serverName1 =
- (String) server1.invoke("get distributed member Id", () -> getDistributedMemberId());
+ String serverName1 = server1.invoke("get distributed member Id", this::getDistributedMemberId);
- String serverName2 =
- (String) server2.invoke("get distributed member Id", () -> getDistributedMemberId());
+ String serverName2 = server2.invoke("get distributed member Id", this::getDistributedMemberId);
CommandResult commandResult = executeCommand(commandString);
System.out.println("testListClientForServers commandResult=" + commandResult);
@@ -567,13 +577,13 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
CompositeResultData resultData = (CompositeResultData) commandResult.getResultData();
SectionResultData section = resultData.retrieveSection("section1");
assertNotNull(section);
- TabularResultData tableRsultData = section.retrieveTable("TableForClientList");
- assertNotNull(tableRsultData);
+ TabularResultData tableResultData = section.retrieveTable("TableForClientList");
+ assertNotNull(tableResultData);
List<String> serverNames =
- tableRsultData.retrieveAllValues(CliStrings.LIST_CLIENT_COLUMN_SERVERS);
+ tableResultData.retrieveAllValues(CliStrings.LIST_CLIENT_COLUMN_SERVERS);
List<String> clientNames =
- tableRsultData.retrieveAllValues(CliStrings.LIST_CLIENT_COLUMN_Clients);
+ tableResultData.retrieveAllValues(CliStrings.LIST_CLIENT_COLUMN_Clients);
serverName1 = serverName1.replace(":", "-");
serverName2 = serverName2.replace(":", "-");
@@ -602,7 +612,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
}
public DistributedMember getMember(final VM vm) {
- return (DistributedMember) vm.invoke("Get Member",
+ return vm.invoke("Get Member",
() -> GemFireCacheImpl.getInstance().getDistributedSystem().getDistributedMember());
}
@@ -635,7 +645,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
setupCqsOnVM(client1);
waitForMbean();
- clientId = (String) manager.invoke("get client Id", () -> {
+ clientId = manager.invoke("get client Id", () -> {
Cache cache = GemFireCacheImpl.getInstance();
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
@@ -664,7 +674,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
waitForMbean();
- clientId = (String) manager.invoke("get client Id", () -> {
+ clientId = manager.invoke("get client Id", () -> {
Cache cache = GemFireCacheImpl.getInstance();
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
@@ -692,7 +702,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
setupCqsOnVM(client1);
waitForListClientMbean3();
- clientId = (String) manager.invoke("get client Id", () -> {
+ clientId = manager.invoke("get client Id", () -> {
Cache cache = GemFireCacheImpl.getInstance();
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
@@ -725,7 +735,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
}
private int startCacheServer(VM server, final int port, final boolean createPR,
- final String regionName) throws Exception {
+ final String regionName) {
return server.invoke("setup CacheServer", () -> {
getSystem(getServerProperties());
@@ -775,7 +785,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
ccf.setPoolSubscriptionRedundancy(1);
ccf.setPoolMinConnections(1);
- ClientCache clientCache = (ClientCache) getClientCache(ccf);
+ ClientCache clientCache = getClientCache(ccf);
// Create region
if (clientCache.getRegion(Region.SEPARATOR + regionName) == null
&& clientCache.getRegion(regionName) == null) {
@@ -813,9 +823,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
private void closeCacheServer(final VM vm) {
vm.invoke("Stop client", () -> {
- Iterator<CacheServer> it = CacheFactory.getAnyInstance().getCacheServers().iterator();
- while (it.hasNext()) {
- CacheServer cacheServer = it.next();
+ for (CacheServer cacheServer : CacheFactory.getAnyInstance().getCacheServers()) {
cacheServer.stop();
}
});
@@ -841,35 +849,34 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
final DistributedMember serverMember = getMember(server1);
assertNotNull(serverMember);
- manager.invoke(() -> {
- Awaitility.waitAtMost(5 * 60, TimeUnit.SECONDS).pollDelay(2, TimeUnit.SECONDS).until(() -> {
- try {
- final SystemManagementService service =
- (SystemManagementService) ManagementService.getManagementService(getCache());
- if (service == null) {
- getLogWriter().info("waitForNonSubScribedClientMBean Still probing for service");
- return false;
- } else {
- getLogWriter().info("waitForNonSubScribedClientMBean 1");
- final ObjectName cacheServerMBeanName =
- service.getCacheServerMBeanName(port0, serverMember);
- getLogWriter().info(
- "waitForNonSubScribedClientMBean 2 cacheServerMBeanName " + cacheServerMBeanName);
- CacheServerMXBean bean =
- service.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
- getLogWriter().info("waitForNonSubScribedClientMBean 2 bean " + bean);
- if (bean.getClientIds().length > 0) {
- return true;
+ manager.invoke(() -> Awaitility.waitAtMost(5 * 60, TimeUnit.SECONDS)
+ .pollDelay(2, TimeUnit.SECONDS).until(() -> {
+ try {
+ final SystemManagementService service =
+ (SystemManagementService) ManagementService.getManagementService(getCache());
+ if (service == null) {
+ getLogWriter().info("waitForNonSubScribedClientMBean Still probing for service");
+ return false;
+ } else {
+ getLogWriter().info("waitForNonSubScribedClientMBean 1");
+ final ObjectName cacheServerMBeanName =
+ service.getCacheServerMBeanName(port0, serverMember);
+ getLogWriter().info(
+ "waitForNonSubScribedClientMBean 2 cacheServerMBeanName " + cacheServerMBeanName);
+ CacheServerMXBean bean =
+ service.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
+ getLogWriter().info("waitForNonSubScribedClientMBean 2 bean " + bean);
+ if (bean.getClientIds().length > 0) {
+ return true;
+ }
}
+ } catch (Exception e) {
+ LogWrapper.getInstance()
+ .warning("waitForNonSubScribedClientMBean Exception in waitForMbean ::: "
+ + CliUtil.stackTraceAsString(e));
}
- } catch (Exception e) {
- LogWrapper.getInstance()
- .warning("waitForNonSubScribedClientMBean Exception in waitForMbean ::: "
- + CliUtil.stackTraceAsString(e));
- }
- return false;
- });
- });
+ return false;
+ }));
}
public void waitForMixedClients() {
@@ -881,34 +888,33 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
assertNotNull(serverMember);
- manager.invoke(() -> {
- Awaitility.waitAtMost(5 * 60, TimeUnit.SECONDS).pollDelay(2, TimeUnit.SECONDS).until(() -> {
- try {
- final SystemManagementService service =
- (SystemManagementService) ManagementService.getManagementService(getCache());
- if (service == null) {
- getLogWriter().info("waitForMixedClients Still probing for service");
- return false;
- } else {
- getLogWriter().info("waitForMixedClients 1");
- final ObjectName cacheServerMBeanName =
- service.getCacheServerMBeanName(port0, serverMember);
- getLogWriter()
- .info("waitForMixedClients 2 cacheServerMBeanName " + cacheServerMBeanName);
- CacheServerMXBean bean =
- service.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
- getLogWriter().info("waitForMixedClients 2 bean " + bean);
- if (bean.getClientIds().length > 1) {
- return true;
+ manager.invoke(() -> Awaitility.waitAtMost(5 * 60, TimeUnit.SECONDS)
+ .pollDelay(2, TimeUnit.SECONDS).until(() -> {
+ try {
+ final SystemManagementService service =
+ (SystemManagementService) ManagementService.getManagementService(getCache());
+ if (service == null) {
+ getLogWriter().info("waitForMixedClients Still probing for service");
+ return false;
+ } else {
+ getLogWriter().info("waitForMixedClients 1");
+ final ObjectName cacheServerMBeanName =
+ service.getCacheServerMBeanName(port0, serverMember);
+ getLogWriter()
+ .info("waitForMixedClients 2 cacheServerMBeanName " + cacheServerMBeanName);
+ CacheServerMXBean bean =
+ service.getMBeanProxy(cacheServerMBeanName, CacheServerMXBean.class);
+ getLogWriter().info("waitForMixedClients 2 bean " + bean);
+ if (bean.getClientIds().length > 1) {
+ return true;
+ }
}
+ } catch (Exception e) {
+ LogWrapper.getInstance().warning("waitForMixedClients Exception in waitForMbean ::: "
+ + CliUtil.stackTraceAsString(e));
}
- } catch (Exception e) {
- LogWrapper.getInstance().warning(
- "waitForMixedClients Exception in waitForMbean ::: " + CliUtil.stackTraceAsString(e));
- }
- return false;
- });
- });
+ return false;
+ }));
}
@Category(FlakyTest.class) // GEODE-910: random ports, HeadlessGfsh
@@ -934,16 +940,17 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
CompositeResultData resultData = (CompositeResultData) commandResult.getResultData();
SectionResultData section = resultData.retrieveSection("InfoSection");
assertNotNull(section);
- TabularResultData tableRsultData = section.retrieveTable("Pool Stats For Pool Name = DEFAULT");
- assertNotNull(tableRsultData);
+ TabularResultData tableResultData = section.retrieveTable("Pool Stats For Pool Name = DEFAULT");
+ assertNotNull(tableResultData);
- List<String> minConn = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
- List<String> maxConn = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
- List<String> redudancy = tableRsultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUDANCY);
+ List<String> minConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
+ List<String> maxConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
+ List<String> redundancy =
+ tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUNDANCY);
assertTrue(minConn.contains("1"));
assertTrue(maxConn.contains("-1"));
- assertTrue(redudancy.contains("1"));
+ assertTrue(redundancy.contains("1"));
String puts = section.retrieveString(CliStrings.DESCRIBE_CLIENT_COLUMN_PUTS);
assertTrue(puts.equals("2"));
@@ -980,8 +987,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
String[] clientIds = setupSystemWithSubAndNonSubClient();
final VM server1 = Host.getHost(0).getVM(1);
- String serverName =
- (String) server1.invoke("Get DistributedMember Id", () -> getDistributedMemberId());
+ String serverName = server1.invoke("Get DistributedMember Id", this::getDistributedMemberId);
String commandString = CliStrings.DESCRIBE_CLIENT + " --" + CliStrings.DESCRIBE_CLIENT__ID
+ "=\"" + clientIds[0] + "\"";
@@ -1018,12 +1024,12 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
List<String> minConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MIN_CONN);
List<String> maxConn = tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_MAX_CONN);
- List<String> redudancy =
- tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUDANCY);
+ List<String> redundancy =
+ tableResultData.retrieveAllValues(CliStrings.DESCRIBE_CLIENT_REDUNDANCY);
assertTrue(minConn.contains("1"));
assertTrue(maxConn.contains("-1"));
- assertTrue(redudancy.contains("1"));
+ assertTrue(redundancy.contains("1"));
String puts = section.retrieveString(CliStrings.DESCRIBE_CLIENT_COLUMN_PUTS);
assertTrue(puts.equals("2"));
@@ -1098,7 +1104,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
waitForMixedClients();
- String[] cliendIds = (String[]) manager.invoke("get client Ids", () -> {
+ String[] clientIds = manager.invoke("get client Ids", () -> {
Cache cache = GemFireCacheImpl.getInstance();
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
@@ -1108,7 +1114,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
return bean.getClientIds();
});
- return cliendIds;
+ return clientIds;
}
private void startNonSubscribedClient(VM client, final VM server, final int port) {
@@ -1132,7 +1138,7 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
ccf.setPoolSubscriptionRedundancy(1);
ccf.setPoolMinConnections(1);
- ClientCache clientCache = (ClientCache) getClientCache(ccf);
+ ClientCache clientCache = getClientCache(ccf);
// Create region
if (clientCache.getRegion(Region.SEPARATOR + regionName) == null
&& clientCache.getRegion(regionName) == null) {
@@ -1165,9 +1171,9 @@ public class ClientCommandsDUnitTest extends CliCommandTestBase {
@Override
public final void postTearDownCacheTestCase() throws Exception {
- Host.getHost(0).getVM(0).invoke(() -> CacheServerTestUtil.closeCache());
- Host.getHost(0).getVM(1).invoke(() -> CacheServerTestUtil.closeCache());
- Host.getHost(0).getVM(2).invoke(() -> CacheServerTestUtil.closeCache());
- Host.getHost(0).getVM(3).invoke(() -> CacheServerTestUtil.closeCache());
+ Host.getHost(0).getVM(0).invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
+ Host.getHost(0).getVM(1).invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
+ Host.getHost(0).getVM(2).invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
+ Host.getHost(0).getVM(3).invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommands.java
----------------------------------------------------------------------
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 00440e5..6ddacf1 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
@@ -14,7 +14,21 @@
*/
package org.apache.geode.cache.lucene.internal.cli;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
import org.apache.commons.lang.StringUtils;
+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.Region;
import org.apache.geode.cache.execute.Execution;
@@ -44,19 +58,10 @@ import org.apache.geode.management.internal.cli.result.TabularResultData;
import org.apache.geode.management.internal.cli.shell.Gfsh;
import org.apache.geode.management.internal.configuration.domain.XmlEntity;
import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.GemFireSecurityException;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* The LuceneIndexCommands class encapsulates all Geode shell (Gfsh) commands related to Lucene
@@ -81,7 +86,7 @@ public class LuceneIndexCommands implements GfshCommand {
@CliCommand(value = LuceneCliStrings.LUCENE_LIST_INDEX,
help = LuceneCliStrings.LUCENE_LIST_INDEX__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ, target = Target.QUERY)
public Result listIndex(@CliOption(key = LuceneCliStrings.LUCENE_LIST_INDEX__STATS,
specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
help = LuceneCliStrings.LUCENE_LIST_INDEX__STATS__HELP) final boolean stats) {
@@ -116,7 +121,7 @@ public class LuceneIndexCommands implements GfshCommand {
(List<Set<LuceneIndexDetails>>) resultsCollector.getResult();
List<LuceneIndexDetails> sortedResults =
- results.stream().flatMap(set -> set.stream()).sorted().collect(Collectors.toList());
+ results.stream().flatMap(Collection::stream).sorted().collect(Collectors.toList());
LinkedHashSet<LuceneIndexDetails> uniqResults = new LinkedHashSet<>();
uniqResults.addAll(sortedResults);
sortedResults.clear();
@@ -158,10 +163,15 @@ public class LuceneIndexCommands implements GfshCommand {
}
}
+ /**
+ * On the server, we also verify the resource operation permissions CLUSTER:WRITE:DISK
+ */
@CliCommand(value = LuceneCliStrings.LUCENE_CREATE_INDEX,
help = LuceneCliStrings.LUCENE_CREATE_INDEX__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
// TODO : Add optionContext for indexName
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
public Result createIndex(@CliOption(key = LuceneCliStrings.LUCENE__INDEX_NAME, mandatory = true,
help = LuceneCliStrings.LUCENE_CREATE_INDEX__NAME__HELP) final String indexName,
@@ -178,12 +188,10 @@ public class LuceneIndexCommands implements GfshCommand {
Result result;
XmlEntity xmlEntity = null;
- getCache().getSecurityService().authorizeRegionManage(regionPath);
try {
final InternalCache cache = getCache();
// trim fields for any leading trailing spaces.
- String[] trimmedFields =
- Arrays.stream(fields).map(field -> field.trim()).toArray(size -> new String[size]);
+ String[] trimmedFields = Arrays.stream(fields).map(String::trim).toArray(String[]::new);
LuceneIndexInfo indexInfo =
new LuceneIndexInfo(indexName, regionPath, trimmedFields, analyzers);
final ResultCollector<?, ?> rc =
@@ -224,7 +232,7 @@ public class LuceneIndexCommands implements GfshCommand {
@CliCommand(value = LuceneCliStrings.LUCENE_DESCRIBE_INDEX,
help = LuceneCliStrings.LUCENE_DESCRIBE_INDEX__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ, target = Target.QUERY)
public Result describeIndex(
@CliOption(key = LuceneCliStrings.LUCENE__INDEX_NAME, mandatory = true,
help = LuceneCliStrings.LUCENE_DESCRIBE_INDEX__NAME__HELP) final String indexName,
@@ -256,14 +264,15 @@ public class LuceneIndexCommands implements GfshCommand {
final ResultCollector<?, ?> rc =
executeFunctionOnRegion(describeIndexFunction, indexInfo, true);
final List<LuceneIndexDetails> funcResults = (List<LuceneIndexDetails>) rc.getResult();
- return funcResults.stream().filter(indexDetails -> indexDetails != null)
- .collect(Collectors.toList());
+ return funcResults.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
+ /**
+ * Internally, we verify the resource operation permissions DATA:READ:[RegionName]
+ */
@CliCommand(value = LuceneCliStrings.LUCENE_SEARCH_INDEX,
help = LuceneCliStrings.LUCENE_SEARCH_INDEX__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = Resource.DATA, operation = Operation.WRITE)
public Result searchIndex(@CliOption(key = LuceneCliStrings.LUCENE__INDEX_NAME, mandatory = true,
help = LuceneCliStrings.LUCENE_SEARCH_INDEX__NAME__HELP) final String indexName,
@@ -284,6 +293,7 @@ public class LuceneIndexCommands implements GfshCommand {
unspecifiedDefaultValue = "false",
help = LuceneCliStrings.LUCENE_SEARCH_INDEX__KEYSONLY__HELP) boolean keysOnly) {
try {
+ getSecurityService().authorizeRegionRead(regionPath);
LuceneQueryInfo queryInfo =
new LuceneQueryInfo(indexName, regionPath, queryString, defaultField, limit, keysOnly);
int pageSize = Integer.MAX_VALUE;
@@ -297,6 +307,8 @@ public class LuceneIndexCommands implements GfshCommand {
throw e;
} catch (IllegalArgumentException e) {
return ResultBuilder.createInfoResult(e.getMessage());
+ } catch (GemFireSecurityException e) {
+ throw e;
} catch (Throwable t) {
SystemFailure.checkFailure();
getCache().getLogger().info(t);
@@ -308,6 +320,8 @@ public class LuceneIndexCommands implements GfshCommand {
@CliCommand(value = LuceneCliStrings.LUCENE_DESTROY_INDEX,
help = LuceneCliStrings.LUCENE_DESTROY_INDEX__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
public Result destroyIndex(@CliOption(key = LuceneCliStrings.LUCENE__INDEX_NAME,
help = LuceneCliStrings.LUCENE_DESTROY_INDEX__NAME__HELP) final String indexName,
@@ -324,8 +338,6 @@ public class LuceneIndexCommands implements GfshCommand {
CliStrings.format(LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__INDEX_CANNOT_BE_EMPTY));
}
- getCache().getSecurityService().authorizeRegionManage(regionPath);
-
Result result;
try {
List<CliFunctionResult> accumulatedResults = new ArrayList<>();
@@ -528,7 +540,7 @@ public class LuceneIndexCommands implements GfshCommand {
final List<Set<LuceneSearchResults>> functionResults =
(List<Set<LuceneSearchResults>>) rc.getResult();
- return functionResults.stream().flatMap(set -> set.stream()).sorted()
+ return functionResults.stream().flatMap(Collection::stream).sorted()
.collect(Collectors.toList());
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexInfo.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexInfo.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexInfo.java
index 41b066e..ad59f0f 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexInfo.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexInfo.java
@@ -14,16 +14,6 @@
*/
package org.apache.geode.cache.lucene.internal.cli;
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.apache.geode.cache.lucene.internal.LuceneIndexImpl;
-
-import org.apache.lucene.analysis.Analyzer;
-
public class LuceneIndexInfo extends LuceneFunctionSerializable {
private static final long serialVersionUID = 1L;
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java
index 5e36efa..2d3f8d2 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java
@@ -19,6 +19,9 @@ import static org.apache.geode.cache.lucene.internal.LuceneServiceImpl.validateC
import static org.apache.geode.cache.lucene.internal.LuceneServiceImpl.validateCommandParameters.REGION_PATH;
import org.apache.commons.lang.StringUtils;
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.execute.FunctionAdapter;
@@ -30,12 +33,14 @@ import org.apache.geode.cache.lucene.internal.cli.LuceneCliStrings;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexDetails;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexInfo;
import org.apache.geode.internal.InternalEntity;
+import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.management.internal.cli.CliUtil;
import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.lucene.analysis.Analyzer;
-import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
@@ -88,6 +93,11 @@ public class LuceneCreateIndexFunction extends FunctionAdapter implements Intern
}
REGION_PATH.validateName(indexInfo.getRegionPath());
+
+ // Every lucene index potentially writes to disk.
+ ((InternalCache) cache).getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE,
+ Target.DISK);
+
indexFactory.create(indexInfo.getIndexName(), indexInfo.getRegionPath());
// TODO - update cluster configuration by returning a valid XmlEntity
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-lucene/src/test/java/org/apache/geode/cache/lucene/LuceneCommandsSecurityDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/LuceneCommandsSecurityDUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/LuceneCommandsSecurityDUnitTest.java
index 423fc59..7cc6709 100644
--- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/LuceneCommandsSecurityDUnitTest.java
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/LuceneCommandsSecurityDUnitTest.java
@@ -20,6 +20,17 @@ import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANA
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import java.io.Serializable;
+import java.util.Properties;
+
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.lucene.internal.cli.LuceneCliStrings;
import org.apache.geode.management.cli.Result;
@@ -34,16 +45,6 @@ import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.runner.RunWith;
-
-import java.io.Serializable;
-import java.util.Properties;
-import junitparams.JUnitParamsRunner;
-import junitparams.Parameters;
@Category({DistributedTest.class, SecurityTest.class})
@RunWith(JUnitParamsRunner.class)
@@ -57,25 +58,26 @@ public class LuceneCommandsSecurityDUnitTest {
private MemberVM locator;
- private MemberVM server;
-
@Before
public void before() throws Exception {
- startLocator();
- startServer();
- }
-
- private void startLocator() throws Exception {
+ // start the locator
Properties props = new Properties();
props.setProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName());
this.locator = this.locatorServer.startLocatorVM(0, props);
+
+ // start the server
+ props = new Properties();
+ props.setProperty("security-username", "clusterManage");
+ props.setProperty("security-password", "clusterManage");
+ this.locatorServer.startServerVM(1, props, this.locator.getPort());
}
- private void startServer() throws Exception {
- Properties props = new Properties();
- props.setProperty("security-username", "clustermanage");
- props.setProperty("security-password", "clustermanage");
- this.server = this.locatorServer.startServerVM(1, props, this.locator.getPort());
+ protected UserNameAndExpectedResponse[] getCreateIndexUserNameAndExpectedResponses() {
+ return new UserNameAndExpectedResponse[] {
+ new UserNameAndExpectedResponse("noPermissions", true,
+ "Unauthorized. Reason : noPermissions not authorized for CLUSTER:MANAGE:QUERY"),
+ new UserNameAndExpectedResponse("clusterManageQuery", false,
+ "Successfully created lucene index")};
}
@Test
@@ -92,6 +94,13 @@ public class LuceneCommandsSecurityDUnitTest {
verifyResult(user, result);
}
+ protected UserNameAndExpectedResponse[] getSearchIndexUserNameAndExpectedResponses() {
+ return new UserNameAndExpectedResponse[] {
+ new UserNameAndExpectedResponse("noPermissions", true,
+ "Unauthorized. Reason : noPermissions not authorized for DATA:READ:region"),
+ new UserNameAndExpectedResponse("dataRead", false, "No results")};
+ }
+
@Test
@Parameters(method = "getSearchIndexUserNameAndExpectedResponses")
public void verifySearchIndexPermissions(UserNameAndExpectedResponse user) throws Exception {
@@ -109,6 +118,13 @@ public class LuceneCommandsSecurityDUnitTest {
verifyResult(user, result);
}
+ protected UserNameAndExpectedResponse[] getListIndexesUserNameAndExpectedResponses() {
+ return new UserNameAndExpectedResponse[] {
+ new UserNameAndExpectedResponse("noPermissions", true,
+ "Unauthorized. Reason : noPermissions not authorized for CLUSTER:READ:QUERY"),
+ new UserNameAndExpectedResponse("clusterReadQuery", false, "Index Name")};
+ }
+
@Test
@Parameters(method = "getListIndexesUserNameAndExpectedResponses")
public void verifyListIndexesPermissions(UserNameAndExpectedResponse user) throws Exception {
@@ -126,6 +142,13 @@ public class LuceneCommandsSecurityDUnitTest {
verifyResult(user, result);
}
+ protected UserNameAndExpectedResponse[] getDescribeIndexUserNameAndExpectedResponses() {
+ return new UserNameAndExpectedResponse[] {
+ new UserNameAndExpectedResponse("noPermissions", true,
+ "Unauthorized. Reason : noPermissions not authorized for CLUSTER:READ:QUERY"),
+ new UserNameAndExpectedResponse("clusterReadQuery", false, "Index Name")};
+ }
+
@Test
@Parameters(method = "getDescribeIndexUserNameAndExpectedResponses")
public void verifyDescribeIndexPermissions(UserNameAndExpectedResponse user) throws Exception {
@@ -143,6 +166,14 @@ public class LuceneCommandsSecurityDUnitTest {
verifyResult(user, result);
}
+ protected UserNameAndExpectedResponse[] getDestroyIndexUserNameAndExpectedResponses() {
+ return new UserNameAndExpectedResponse[] {
+ new UserNameAndExpectedResponse("noPermissions", true,
+ "Unauthorized. Reason : noPermissions not authorized for CLUSTER:MANAGE:QUERY"),
+ new UserNameAndExpectedResponse("clusterManageQuery", false,
+ "Successfully destroyed lucene index")};
+ }
+
@Test
@Parameters(method = "getDestroyIndexUserNameAndExpectedResponses")
public void verifyDestroyIndexPermissions(UserNameAndExpectedResponse user) throws Exception {
@@ -163,7 +194,7 @@ public class LuceneCommandsSecurityDUnitTest {
private void createIndexAndRegion() throws Exception {
// Connect gfsh to locator with permissions necessary to create an index and region
this.gfshShell.secureConnectAndVerify(this.locator.getPort(),
- GfshShellConnectionRule.PortType.locator, "datamanage", "datamanage");
+ GfshShellConnectionRule.PortType.locator, "cluster,data", "cluster,data");
// Create lucene index
this.gfshShell.executeAndVerifyCommand(getCreateIndexCommand());
@@ -186,7 +217,7 @@ public class LuceneCommandsSecurityDUnitTest {
assertTrue(this.gfshShell.getGfshOutput().contains(user.getExpectedResponse()));
}
- private String getCreateIndexCommand() throws Exception {
+ private String getCreateIndexCommand() {
CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX);
csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME);
csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME);
@@ -194,7 +225,7 @@ public class LuceneCommandsSecurityDUnitTest {
return csb.toString();
}
- private String getCreateRegionCommand() throws Exception {
+ private String getCreateRegionCommand() {
CommandStringBuilder csb = new CommandStringBuilder(CliStrings.CREATE_REGION);
csb.addOption(CliStrings.CREATE_REGION__REGION, REGION_NAME);
csb.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT,
@@ -202,7 +233,7 @@ public class LuceneCommandsSecurityDUnitTest {
return csb.toString();
}
- private String getSearchIndexCommand() throws Exception {
+ private String getSearchIndexCommand() {
CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX);
csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME);
csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME);
@@ -211,62 +242,25 @@ public class LuceneCommandsSecurityDUnitTest {
return csb.toString();
}
- private String getListIndexesCommand() throws Exception {
+ private String getListIndexesCommand() {
CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_LIST_INDEX);
return csb.toString();
}
- private String getDescribeIndexCommand() throws Exception {
+ private String getDescribeIndexCommand() {
CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_DESCRIBE_INDEX);
csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME);
csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME);
return csb.toString();
}
- private String getDestroyIndexCommand() throws Exception {
+ private String getDestroyIndexCommand() {
CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_DESTROY_INDEX);
csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME);
csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME);
return csb.toString();
}
- protected UserNameAndExpectedResponse[] getCreateIndexUserNameAndExpectedResponses() {
- return new UserNameAndExpectedResponse[] {
- new UserNameAndExpectedResponse("nopermissions", true,
- "Unauthorized. Reason : nopermissions not authorized for DATA:MANAGE:region"),
- new UserNameAndExpectedResponse("datamanageregion", false,
- "Successfully created lucene index")};
- }
-
- protected UserNameAndExpectedResponse[] getSearchIndexUserNameAndExpectedResponses() {
- return new UserNameAndExpectedResponse[] {
- new UserNameAndExpectedResponse("nopermissions", true,
- "Unauthorized. Reason : nopermissions not authorized for DATA:WRITE"),
- new UserNameAndExpectedResponse("datawrite", false, "No results")};
- }
-
- protected UserNameAndExpectedResponse[] getListIndexesUserNameAndExpectedResponses() {
- return new UserNameAndExpectedResponse[] {
- new UserNameAndExpectedResponse("nopermissions", true,
- "Unauthorized. Reason : nopermissions not authorized for CLUSTER:READ"),
- new UserNameAndExpectedResponse("clusterread", false, "Index Name")};
- }
-
- protected UserNameAndExpectedResponse[] getDescribeIndexUserNameAndExpectedResponses() {
- return new UserNameAndExpectedResponse[] {
- new UserNameAndExpectedResponse("nopermissions", true,
- "Unauthorized. Reason : nopermissions not authorized for CLUSTER:READ"),
- new UserNameAndExpectedResponse("clusterread", false, "Index Name")};
- }
-
- protected UserNameAndExpectedResponse[] getDestroyIndexUserNameAndExpectedResponses() {
- return new UserNameAndExpectedResponse[] {
- new UserNameAndExpectedResponse("nopermissions", true,
- "Unauthorized. Reason : nopermissions not authorized for DATA:MANAGE:region"),
- new UserNameAndExpectedResponse("datamanageregion", false,
- "Successfully destroyed lucene index")};
- }
-
public static class UserNameAndExpectedResponse implements Serializable {
private final String userName;
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java
index 25068bc..0410e7f 100644
--- a/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java
+++ b/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java
@@ -15,11 +15,11 @@
package org.apache.geode.management.internal.security;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.test.dunit.rules.GfshShellConnectionRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
-
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.experimental.categories.Category;
@Category({IntegrationTest.class, SecurityTest.class})
public class GfshCommandsOverHttpSecurityTest extends GfshCommandsSecurityTest {
[5/6] geode git commit: GEODE-2919: Provide finer grained security
Posted by js...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemMBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemMBean.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemMBean.java
index c45da73..28edbf6 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemMBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/DistributedSystemMBean.java
@@ -14,6 +14,12 @@
*/
package org.apache.geode.management.internal.beans;
+import java.util.Map;
+
+import javax.management.NotificationBroadcasterSupport;
+import javax.management.ObjectName;
+
+import org.apache.geode.internal.security.SecurityServiceFactory;
import org.apache.geode.management.DiskBackupStatus;
import org.apache.geode.management.DiskMetrics;
import org.apache.geode.management.DistributedSystemMXBean;
@@ -22,10 +28,9 @@ import org.apache.geode.management.JVMMetrics;
import org.apache.geode.management.NetworkMetrics;
import org.apache.geode.management.OSMetrics;
import org.apache.geode.management.PersistentMemberDetails;
-
-import java.util.Map;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.ObjectName;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* Distributed System MBean
@@ -48,8 +53,9 @@ public class DistributedSystemMBean extends NotificationBroadcasterSupport
@Override
public DiskBackupStatus backupAllMembers(String targetDirPath, String baselineDirPath)
throws Exception {
+ SecurityServiceFactory.findSecurityService().authorize(Resource.CLUSTER, Operation.WRITE,
+ Target.DISK);
return bridge.backupAllMembers(targetDirPath, baselineDirPath);
-
}
@Override
@@ -60,7 +66,6 @@ public class DistributedSystemMBean extends NotificationBroadcasterSupport
@Override
public String[] listCacheServers() {
return bridge.listCacheServers();
-
}
@@ -243,7 +248,7 @@ public class DistributedSystemMBean extends NotificationBroadcasterSupport
}
@Override
- public boolean revokeMissingDiskStores(final String diskStoreId) throws Exception {
+ public boolean revokeMissingDiskStores(final String diskStoreId) {
return bridge.revokeMissingDiskStores(diskStoreId);
}
@@ -433,6 +438,6 @@ public class DistributedSystemMBean extends NotificationBroadcasterSupport
@Override
public void setQueryCollectionsDepth(int queryCollectionsDepth) {
- bridge.setQueryCollectionsDepth(queryCollectionsDepth);;
+ bridge.setQueryCollectionsDepth(queryCollectionsDepth);
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBean.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBean.java
index 9d717d0..271dce1 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBean.java
@@ -148,7 +148,12 @@ public class MemberMBean extends NotificationBroadcasterSupport implements Membe
@Override
public int getInitialImagesInProgres() {
- return bridge.getInitialImagesInProgres();
+ return getInitialImagesInProgress();
+ }
+
+ @Override
+ public int getInitialImagesInProgress() {
+ return bridge.getInitialImagesInProgress();
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java b/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java
index 516b97d..dd905eb 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/beans/MemberMBeanBridge.java
@@ -14,7 +14,7 @@
*/
package org.apache.geode.management.internal.beans;
-import static org.apache.geode.internal.lang.SystemUtils.*;
+import static org.apache.geode.internal.lang.SystemUtils.getLineSeparator;
import java.io.File;
import java.io.IOException;
@@ -1341,7 +1341,7 @@ public class MemberMBeanBridge {
return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue();
}
- public int getInitialImagesInProgres() {
+ public int getInitialImagesInProgress() {
return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS).intValue();
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClientCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClientCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClientCommands.java
index fe27b60..dac12fa 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClientCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClientCommands.java
@@ -14,7 +14,19 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import org.apache.geode.cache.CacheFactory;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import javax.management.ObjectName;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.internal.cache.InternalCache;
@@ -25,30 +37,16 @@ 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.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.ContunuousQueryFunction;
-import org.apache.geode.management.internal.cli.functions.ContunuousQueryFunction.ClientInfo;
+import org.apache.geode.management.internal.cli.functions.ContinuousQueryFunction;
+import org.apache.geode.management.internal.cli.functions.ContinuousQueryFunction.ClientInfo;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.result.CompositeResultData;
import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.CommandMarker;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.management.ObjectName;
/**
* @since GemFire 8.0
@@ -59,7 +57,7 @@ public class ClientCommands implements GfshCommand {
@CliMetaData(relatedTopic = {CliStrings.TOPIC_CLIENT})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result listClient() {
- Result result = null;
+ Result result;
try {
CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
@@ -78,7 +76,7 @@ public class ClientCommands implements GfshCommand {
CliStrings.format(CliStrings.LIST_CLIENT_COULD_NOT_RETRIEVE_SERVER_LIST));
}
- Map<String, List<String>> clientServerMap = new HashMap<String, List<String>>();
+ Map<String, List<String>> clientServerMap = new HashMap<>();
for (ObjectName objName : cacheServers) {
CacheServerMXBean serverMbean = service.getMBeanInstance(objName, CacheServerMXBean.class);
@@ -89,16 +87,16 @@ public class ClientCommands implements GfshCommand {
}
- for (String clietName : listOfClient) {
+ for (String clientName : listOfClient) {
String serverDetails = "member=" + objName.getKeyProperty("member") + ",port="
+ objName.getKeyProperty("port");
- if (clientServerMap.containsKey(clietName)) {
- List<String> listServers = clientServerMap.get(clietName);
+ if (clientServerMap.containsKey(clientName)) {
+ List<String> listServers = clientServerMap.get(clientName);
listServers.add(serverDetails);
} else {
- List<String> listServer = new ArrayList<String>();
+ List<String> listServer = new ArrayList<>();
listServer.add(serverDetails);
- clientServerMap.put(clietName, listServer);
+ clientServerMap.put(clientName, listServer);
}
}
}
@@ -109,12 +107,10 @@ public class ClientCommands implements GfshCommand {
}
String memberSeparator = "; ";
- Iterator<Entry<String, List<String>>> it = clientServerMap.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<String, List<String>> pairs = (Map.Entry<String, List<String>>) it.next();
- String client = (String) pairs.getKey();
- List<String> servers = (List<String>) pairs.getValue();
+ for (Entry<String, List<String>> pairs : clientServerMap.entrySet()) {
+ String client = pairs.getKey();
+ List<String> servers = pairs.getValue();
StringBuilder serverListForClient = new StringBuilder();
int serversSize = servers.size();
int i = 0;
@@ -148,7 +144,7 @@ public class ClientCommands implements GfshCommand {
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result describeClient(@CliOption(key = CliStrings.DESCRIBE_CLIENT__ID, mandatory = true,
help = CliStrings.DESCRIBE_CLIENT__ID__HELP) String clientId) {
- Result result = null;
+ Result result;
if (clientId.startsWith("\"")) {
clientId = clientId.substring(1);
@@ -179,7 +175,7 @@ public class ClientCommands implements GfshCommand {
for (ObjectName objName : cacheServers) {
CacheServerMXBean serverMbean = service.getMBeanInstance(objName, CacheServerMXBean.class);
List<String> listOfClient =
- new ArrayList<String>(Arrays.asList((String[]) serverMbean.getClientIds()));
+ new ArrayList<>(Arrays.asList((String[]) serverMbean.getClientIds()));
if (listOfClient.contains(clientId)) {
if (clientHealthStatus == null) {
try {
@@ -204,17 +200,17 @@ public class ClientCommands implements GfshCommand {
Set<DistributedMember> dsMembers = CliUtil.getAllMembers(cache);
String isDurable = null;
- List<String> primaryServers = new ArrayList<String>();
- List<String> secondaryServers = new ArrayList<String>();
+ List<String> primaryServers = new ArrayList<>();
+ List<String> secondaryServers = new ArrayList<>();
if (dsMembers.size() > 0) {
- ContunuousQueryFunction contunuousQueryFunction = new ContunuousQueryFunction();
- FunctionService.registerFunction(contunuousQueryFunction);
+ ContinuousQueryFunction continuousQueryFunction = new ContinuousQueryFunction();
+ FunctionService.registerFunction(continuousQueryFunction);
List<?> resultList = (List<?>) CliUtil
- .executeFunction(contunuousQueryFunction, clientId, dsMembers).getResult();
- for (int i = 0; i < resultList.size(); i++) {
+ .executeFunction(continuousQueryFunction, clientId, dsMembers).getResult();
+ for (Object aResultList : resultList) {
try {
- Object object = resultList.get(i);
+ Object object = aResultList;
if (object instanceof Throwable) {
LogWrapper.getInstance().warning(
"Exception in Describe Client " + ((Throwable) object).getMessage(),
@@ -261,11 +257,11 @@ public class ClientCommands implements GfshCommand {
}
} catch (Exception e) {
LogWrapper.getInstance()
- .info("Error in decribe clients. stack trace" + CliUtil.stackTraceAsString(e));
+ .info("Error in describe clients. stack trace" + CliUtil.stackTraceAsString(e));
result = ResultBuilder.createGemFireErrorResult(CliStrings
.format(CliStrings.DESCRIBE_CLIENT_COULD_NOT_RETRIEVE_CLIENT_0, e.getMessage()));
}
- LogWrapper.getInstance().info("decribe client result " + result);
+ LogWrapper.getInstance().info("describe client result " + result);
return result;
}
@@ -309,29 +305,27 @@ public class ClientCommands implements GfshCommand {
Map<String, String> poolStats = clientHealthStatus.getPoolStats();
if (poolStats.size() > 0) {
- Iterator<Entry<String, String>> it = poolStats.entrySet().iterator();
- while (it.hasNext()) {
- Entry<String, String> entry = it.next();
+ for (Entry<String, String> entry : poolStats.entrySet()) {
TabularResultData poolStatsResultTable =
sectionResult.addTable("Pool Stats For Pool Name = " + entry.getKey());
poolStatsResultTable.setHeader("Pool Stats For Pool Name = " + entry.getKey());
String poolStatsStr = entry.getValue();
String str[] = poolStatsStr.split(";");
- LogWrapper.getInstance().info("decribe client clientHealthStatus min conn="
+ LogWrapper.getInstance().info("describe client clientHealthStatus min conn="
+ str[0].substring(str[0].indexOf("=") + 1));
- LogWrapper.getInstance().info("decribe client clientHealthStatus max conn ="
+ LogWrapper.getInstance().info("describe client clientHealthStatus max conn ="
+ str[1].substring(str[1].indexOf("=") + 1));
- LogWrapper.getInstance().info("decribe client clientHealthStatus redundancy ="
+ LogWrapper.getInstance().info("describe client clientHealthStatus redundancy ="
+ str[2].substring(str[2].indexOf("=") + 1));
- LogWrapper.getInstance().info("decribe client clientHealthStatus CQs ="
+ LogWrapper.getInstance().info("describe client clientHealthStatus CQs ="
+ str[3].substring(str[3].indexOf("=") + 1));
poolStatsResultTable.accumulate(CliStrings.DESCRIBE_CLIENT_MIN_CONN,
str[0].substring(str[0].indexOf("=") + 1));
poolStatsResultTable.accumulate(CliStrings.DESCRIBE_CLIENT_MAX_CONN,
str[1].substring(str[1].indexOf("=") + 1));
- poolStatsResultTable.accumulate(CliStrings.DESCRIBE_CLIENT_REDUDANCY,
+ poolStatsResultTable.accumulate(CliStrings.DESCRIBE_CLIENT_REDUNDANCY,
str[2].substring(str[2].indexOf("=") + 1));
poolStatsResultTable.accumulate(CliStrings.DESCRIBE_CLIENT_CQs,
str[3].substring(str[3].indexOf("=") + 1));
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
index b762396..883bfee 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
@@ -19,7 +19,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -79,6 +78,7 @@ import org.apache.geode.management.internal.configuration.domain.XmlEntity;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* @since GemFire 7.0
@@ -103,7 +103,8 @@ public class CreateAlterDestroyRegionCommands implements GfshCommand {
}
/**
- * TODO: method createRegion is too complex to analyze
+ * Internally, we also verify the resource operation permissions CLUSTER:WRITE:DISK if the region
+ * is persistent
*/
@CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
@@ -295,19 +296,20 @@ public class CreateAlterDestroyRegionCommands implements GfshCommand {
}
}
+ // Do we prefer to validate or authorize first?
validateRegionFunctionArgs(cache, regionFunctionArgs);
+ if (isPersistentShortcut(regionFunctionArgs.getRegionShortcut())
+ || isAttributePersistent(regionFunctionArgs.getRegionAttributes())) {
+ getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
+ }
Set<DistributedMember> membersToCreateRegionOn;
if (groups != null && groups.length != 0) {
membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups);
// have only normal members from the group
- for (Iterator<DistributedMember> it = membersToCreateRegionOn.iterator(); it.hasNext();) {
- DistributedMember distributedMember = it.next();
- if (((InternalDistributedMember) distributedMember)
- .getVmKind() == DistributionManager.LOCATOR_DM_TYPE) {
- it.remove();
- }
- }
+ membersToCreateRegionOn
+ .removeIf(distributedMember -> ((InternalDistributedMember) distributedMember)
+ .getVmKind() == DistributionManager.LOCATOR_DM_TYPE);
} else {
membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache);
}
@@ -340,9 +342,6 @@ public class CreateAlterDestroyRegionCommands implements GfshCommand {
} catch (IllegalArgumentException | IllegalStateException e) {
LogWrapper.getInstance().info(e.getMessage());
result = ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (RuntimeException e) {
- LogWrapper.getInstance().info(e.getMessage(), e);
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
}
if (xmlEntity.get() != null) {
persistClusterConfiguration(result,
@@ -424,7 +423,7 @@ public class CreateAlterDestroyRegionCommands implements GfshCommand {
Result result;
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
- getCache().getSecurityService().authorizeRegionManage(regionPath);
+ getSecurityService().authorizeRegionManage(regionPath);
try {
InternalCache cache = getCache();
@@ -914,7 +913,7 @@ public class CreateAlterDestroyRegionCommands implements GfshCommand {
} // attributes null check
} // not IllegalArgumentException or other throwable
} // iterate over list - there should be only one result in the list
- } // result list is not null or mpty
+ } // result list is not null or empty
} // regionAssociatedMembers is not-empty
} // attributes are null because do not exist on local member
@@ -1128,4 +1127,20 @@ public class CreateAlterDestroyRegionCommands implements GfshCommand {
}
return foundMembers;
}
+
+ private boolean isPersistentShortcut(RegionShortcut shortcut) {
+ return shortcut == RegionShortcut.LOCAL_PERSISTENT
+ || shortcut == RegionShortcut.LOCAL_PERSISTENT_OVERFLOW
+ || shortcut == RegionShortcut.PARTITION_PERSISTENT
+ || shortcut == RegionShortcut.PARTITION_PERSISTENT_OVERFLOW
+ || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT
+ || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW
+ || shortcut == RegionShortcut.REPLICATE_PERSISTENT
+ || shortcut == RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW;
+ }
+
+ private boolean isAttributePersistent(RegionAttributes attributes) {
+ return attributes != null && attributes.getDataPolicy() != null
+ && attributes.getDataPolicy().toString().contains("PERSISTENT");
+ }
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DataCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DataCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DataCommands.java
index b2789e3..3f4397b 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DataCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DataCommands.java
@@ -14,9 +14,28 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
+import org.apache.shiro.subject.Subject;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.LogWriter;
import org.apache.geode.cache.CacheClosedException;
import org.apache.geode.cache.CacheFactory;
@@ -60,24 +79,6 @@ import org.apache.geode.management.internal.cli.shell.Gfsh;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.shiro.subject.Subject;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
/**
* @since GemFire 7.0
@@ -105,10 +106,8 @@ public class DataCommands implements GfshCommand {
@ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
public Result rebalance(
@CliOption(key = CliStrings.REBALANCE__INCLUDEREGION,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.REBALANCE__INCLUDEREGION__HELP) String[] includeRegions,
@CliOption(key = CliStrings.REBALANCE__EXCLUDEREGION,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.REBALANCE__EXCLUDEREGION__HELP) String[] excludeRegions,
@CliOption(key = CliStrings.REBALANCE__TIMEOUT, unspecifiedDefaultValue = "-1",
help = CliStrings.REBALANCE__TIMEOUT__HELP) long timeout,
@@ -135,7 +134,7 @@ public class DataCommands implements GfshCommand {
} catch (Exception ex) {
result = ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.REBALANCE__MSG__EXCEPTION_OCCRED_WHILE_REBALANCING_0, ex.getMessage()));
+ CliStrings.REBALANCE__MSG__EXCEPTION_OCCURRED_WHILE_REBALANCING_0, ex.getMessage()));
}
LogWrapper.getInstance().info("Rebalance returning result >>>" + result);
return result;
@@ -473,12 +472,12 @@ public class DataCommands implements GfshCommand {
return listMembersId.toString();
}
- private CompositeResultData toCompositeResultData(CompositeResultData rebalanceResulteData,
+ private CompositeResultData toCompositeResultData(CompositeResultData rebalanceResultData,
ArrayList<String> rstlist, int index, boolean simulate, InternalCache cache) {
// add only if there are any valid regions in results
if (rstlist.size() > resultItemCount && StringUtils.isNotEmpty(rstlist.get(resultItemCount))) {
- TabularResultData table1 = rebalanceResulteData.addSection().addTable("Table" + index);
+ TabularResultData table1 = rebalanceResultData.addSection().addTable("Table" + index);
String newLine = System.getProperty("line.separator");
StringBuilder resultStr = new StringBuilder();
resultStr.append(newLine);
@@ -541,7 +540,7 @@ public class DataCommands implements GfshCommand {
table1.setHeader(headerText);
cache.getLogger().info(headerText + resultStr);
}
- return rebalanceResulteData;
+ return rebalanceResultData;
}
private CompositeResultData buildResultForRebalance(CompositeResultData rebalanceResultData,
@@ -739,15 +738,12 @@ public class DataCommands implements GfshCommand {
@CliOption(key = CliStrings.EXPORT_DATA__REGION, mandatory = true,
optionContext = ConverterHint.REGION_PATH,
help = CliStrings.EXPORT_DATA__REGION__HELP) String regionName,
- @CliOption(key = CliStrings.EXPORT_DATA__FILE,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, mandatory = true,
+ @CliOption(key = CliStrings.EXPORT_DATA__FILE, mandatory = true,
help = CliStrings.EXPORT_DATA__FILE__HELP) String filePath,
- @CliOption(key = CliStrings.MEMBER,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
- optionContext = ConverterHint.MEMBERIDNAME, mandatory = true,
- help = CliStrings.EXPORT_DATA__MEMBER__HELP) String memberNameOrId) {
+ @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
+ mandatory = true, help = CliStrings.EXPORT_DATA__MEMBER__HELP) String memberNameOrId) {
- getCache().getSecurityService().authorizeRegionRead(regionName);
+ getSecurityService().authorizeRegionRead(regionName);
final DistributedMember targetMember = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
Result result;
@@ -796,16 +792,14 @@ public class DataCommands implements GfshCommand {
@CliOption(key = CliStrings.IMPORT_DATA__REGION, optionContext = ConverterHint.REGION_PATH,
mandatory = true, help = CliStrings.IMPORT_DATA__REGION__HELP) String regionName,
@CliOption(key = CliStrings.IMPORT_DATA__FILE, mandatory = true,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.IMPORT_DATA__FILE__HELP) String filePath,
@CliOption(key = CliStrings.MEMBER, mandatory = true,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.IMPORT_DATA__MEMBER__HELP) String memberNameOrId,
@CliOption(key = CliStrings.IMPORT_DATA__INVOKE_CALLBACKS, unspecifiedDefaultValue = "false",
help = CliStrings.IMPORT_DATA__INVOKE_CALLBACKS__HELP) boolean invokeCallbacks) {
- getCache().getSecurityService().authorizeRegionWrite(regionName);
+ getSecurityService().authorizeRegionWrite(regionName);
Result result;
@@ -1003,7 +997,7 @@ public class DataCommands implements GfshCommand {
help = CliStrings.LOCATE_ENTRY__RECURSIVE__HELP,
unspecifiedDefaultValue = "false") boolean recursive) {
- getCache().getSecurityService().authorizeRegionRead(regionPath, key);
+ getSecurityService().authorizeRegionRead(regionPath, key);
DataCommandResult dataResult;
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
index 9b79e1d..e502154 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
@@ -15,8 +15,17 @@
package org.apache.geode.management.internal.cli.commands;
import static org.apache.commons.io.FileUtils.ONE_MB;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.text.DecimalFormat;
+import java.util.List;
+import java.util.Set;
+
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
import org.apache.geode.SystemFailure;
import org.apache.geode.cache.execute.ResultCollector;
@@ -42,15 +51,9 @@ import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.NotAuthorizedException;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
+import org.apache.geode.security.ResourcePermission.Target;
+
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.text.DecimalFormat;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
/**
* Commands for deploying, un-deploying and listing files deployed using the command line shell.
@@ -76,6 +79,7 @@ public class DeployCommands implements GfshCommand {
@CliMetaData(
interceptor = "org.apache.geode.management.internal.cli.commands.DeployCommands$Interceptor",
relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
public Result deploy(
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, help = CliStrings.DEPLOY__GROUP__HELP,
optionContext = ConverterHint.MEMBERGROUP) String[] groups,
@@ -86,11 +90,7 @@ public class DeployCommands implements GfshCommand {
// since deploy function can potentially do a lot of damage to security, this action should
// require these following privileges
- SecurityService securityService = getCache().getSecurityService();
- securityService.authorizeClusterManage();
- securityService.authorizeClusterWrite();
- securityService.authorizeDataManage();
- securityService.authorizeDataWrite();
+ SecurityService securityService = getSecurityService();
TabularResultData tabularData = ResultBuilder.createTabularResultData();
@@ -155,13 +155,13 @@ public class DeployCommands implements GfshCommand {
*/
@CliCommand(value = {CliStrings.UNDEPLOY}, help = CliStrings.UNDEPLOY__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
public Result undeploy(
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
help = CliStrings.UNDEPLOY__GROUP__HELP,
optionContext = ConverterHint.MEMBERGROUP) String[] groups,
- @CliOption(key = {CliStrings.JAR, CliStrings.JARS}, help = CliStrings.UNDEPLOY__JAR__HELP,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE) String[] jars) {
+ @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
+ help = CliStrings.UNDEPLOY__JAR__HELP) String[] jars) {
try {
TabularResultData tabularData = ResultBuilder.createTabularResultData();
@@ -289,7 +289,7 @@ public class DeployCommands implements GfshCommand {
public Result preExecution(GfshParseResult parseResult) {
// 2nd argument is the jar
String[] jars = (String[]) parseResult.getArguments()[1];
- // 3rd arguemnt is the dir
+ // 3rd argument is the dir
String dir = (String) parseResult.getArguments()[2];
if (ArrayUtils.isEmpty(jars) && StringUtils.isBlank(dir)) {
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
index e14c3a6..80f3804 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
@@ -14,6 +14,28 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.GemFireIOException;
import org.apache.geode.SystemFailure;
import org.apache.geode.admin.BackupStatus;
@@ -68,32 +90,9 @@ import org.apache.geode.management.internal.cli.util.MemberNotFoundException;
import org.apache.geode.management.internal.configuration.domain.XmlEntity;
import org.apache.geode.management.internal.messages.CompactRequest;
import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Target;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* The DiskStoreCommands class encapsulates all GemFire Disk Store commands in Gfsh.
@@ -103,27 +102,31 @@ import java.util.concurrent.atomic.AtomicReference;
*/
@SuppressWarnings("unused")
public class DiskStoreCommands implements GfshCommand {
+
protected Set<DistributedMember> getNormalMembers(final InternalCache cache) {
// TODO determine what this does (as it is untested and unmockable!)
return CliUtil.getAllNormalMembers(cache);
}
+ /**
+ * Internally, we also verify the resource operation permissions CLUSTER:WRITE:DISK if the region
+ * is persistent
+ */
@CliCommand(value = CliStrings.BACKUP_DISK_STORE, help = CliStrings.BACKUP_DISK_STORE__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
@ResourceOperation(resource = Resource.DATA, operation = Operation.READ)
public Result backupDiskStore(
-
@CliOption(key = CliStrings.BACKUP_DISK_STORE__DISKDIRS,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.BACKUP_DISK_STORE__DISKDIRS__HELP, mandatory = true) String targetDir,
@CliOption(key = CliStrings.BACKUP_DISK_STORE__BASELINEDIR,
help = CliStrings.BACKUP_DISK_STORE__BASELINEDIR__HELP) String baselineDir) {
- Result result = null;
+ getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
+ Result result;
try {
InternalCache cache = getCache();
DM dm = cache.getDistributionManager();
- BackupStatus backupStatus = null;
+ BackupStatus backupStatus;
if (baselineDir != null && !baselineDir.isEmpty()) {
backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir),
@@ -159,11 +162,11 @@ public class DiskStoreCommands implements GfshCommand {
String directory = persistentId.getDirectory();
if (printMember) {
- writeToBackupDisktoreTable(backedupDiskStoresTable, memberName, UUID, hostName,
+ writeToBackupDiskStoreTable(backedupDiskStoresTable, memberName, UUID, hostName,
directory);
printMember = false;
} else {
- writeToBackupDisktoreTable(backedupDiskStoresTable, "", UUID, hostName, directory);
+ writeToBackupDiskStoreTable(backedupDiskStoresTable, "", UUID, hostName, directory);
}
}
}
@@ -197,8 +200,8 @@ public class DiskStoreCommands implements GfshCommand {
return result;
}
- private void writeToBackupDisktoreTable(TabularResultData backedupDiskStoreTable, String memberId,
- String UUID, String host, String directory) {
+ private void writeToBackupDiskStoreTable(TabularResultData backedupDiskStoreTable,
+ String memberId, String UUID, String host, String directory) {
backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_MEMBER, memberId);
backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID, UUID);
backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY, directory);
@@ -206,7 +209,7 @@ public class DiskStoreCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.LIST_DISK_STORE, help = CliStrings.LIST_DISK_STORE__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result listDiskStore() {
try {
@@ -242,7 +245,7 @@ public class DiskStoreCommands implements GfshCommand {
final List<?> results = (List<?>) resultCollector.getResult();
final List<DiskStoreDetails> distributedSystemMemberDiskStores =
- new ArrayList<DiskStoreDetails>(results.size());
+ new ArrayList<>(results.size());
for (final Object result : results) {
if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other
@@ -276,8 +279,9 @@ public class DiskStoreCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.CREATE_DISK_STORE, help = CliStrings.CREATE_DISK_STORE__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
public Result createDiskStore(
@CliOption(key = CliStrings.CREATE_DISK_STORE__NAME, mandatory = true,
optionContext = ConverterHint.DISKSTORE,
@@ -398,7 +402,7 @@ public class DiskStoreCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.COMPACT_DISK_STORE, help = CliStrings.COMPACT_DISK_STORE__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
target = Target.DISK)
public Result compactDiskStore(
@@ -406,9 +410,8 @@ public class DiskStoreCommands implements GfshCommand {
optionContext = ConverterHint.DISKSTORE,
help = CliStrings.COMPACT_DISK_STORE__NAME__HELP) String diskStoreName,
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.COMPACT_DISK_STORE__GROUP__HELP) String[] groups) {
- Result result = null;
+ Result result;
try {
// disk store exists validation
@@ -419,29 +422,24 @@ public class DiskStoreCommands implements GfshCommand {
} else {
InternalDistributedSystem ds = getCache().getInternalDistributedSystem();
- Map<DistributedMember, PersistentID> overallCompactInfo =
- new HashMap<DistributedMember, PersistentID>();
+ Map<DistributedMember, PersistentID> overallCompactInfo = new HashMap<>();
Set<?> otherMembers = ds.getDistributionManager().getOtherNormalDistributionManagerIds();
- Set<InternalDistributedMember> allMembers = new HashSet<InternalDistributedMember>();
+ Set<InternalDistributedMember> allMembers = new HashSet<>();
for (Object member : otherMembers) {
allMembers.add((InternalDistributedMember) member);
}
allMembers.add(ds.getDistributedMember());
- otherMembers = null;
String groupInfo = "";
// if groups are specified, find members in the specified group
if (groups != null && groups.length > 0) {
groupInfo = CliStrings.format(CliStrings.COMPACT_DISK_STORE__MSG__FOR_GROUP,
new Object[] {Arrays.toString(groups) + "."});
- final Set<InternalDistributedMember> selectedMembers =
- new HashSet<InternalDistributedMember>();
+ final Set<InternalDistributedMember> selectedMembers = new HashSet<>();
List<String> targetedGroups = Arrays.asList(groups);
- for (Iterator<InternalDistributedMember> iterator = allMembers.iterator(); iterator
- .hasNext();) {
- InternalDistributedMember member = iterator.next();
+ for (InternalDistributedMember member : allMembers) {
List<String> memberGroups = member.getGroups();
if (!Collections.disjoint(targetedGroups, memberGroups)) {
selectedMembers.add(member);
@@ -486,7 +484,7 @@ public class DiskStoreCommands implements GfshCommand {
// If compaction happened at all, then prepare the summary
if (overallCompactInfo != null && !overallCompactInfo.isEmpty()) {
CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
- SectionResultData section = null;
+ SectionResultData section;
Set<Entry<DistributedMember, PersistentID>> entries = overallCompactInfo.entrySet();
@@ -546,20 +544,18 @@ public class DiskStoreCommands implements GfshCommand {
@CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME, mandatory = true,
help = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
@CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
@CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
unspecifiedDefaultValue = "-1",
help = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
@CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__J,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.COMPACT_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps) {
- Result result = null;
+ Result result;
LogWrapper logWrapper = LogWrapper.getInstance();
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
- String errorMessage = "";
+ StringBuilder errorMessage = new StringBuilder();
Process compacterProcess = null;
try {
@@ -570,16 +566,14 @@ public class DiskStoreCommands implements GfshCommand {
+ validatedDirectories + "\"");
}
- List<String> commandList = new ArrayList<String>();
+ List<String> commandList = new ArrayList<>();
commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+ File.separatorChar + "java");
configureLogging(commandList);
if (jvmProps != null && jvmProps.length != 0) {
- for (int i = 0; i < jvmProps.length; i++) {
- commandList.add(jvmProps[i]);
- }
+ commandList.addAll(Arrays.asList(jvmProps));
}
commandList.add("-classpath");
commandList.add(System.getProperty("java.class.path", "."));
@@ -612,12 +606,11 @@ public class DiskStoreCommands implements GfshCommand {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
- String line = null;
+ String line;
while ((line = inputReader.readLine()) != null) {
output.append(line).append(GfshParser.LINE_SEPARATOR);
}
- line = null;
boolean switchToStackTrace = false;
while ((line = errorReader.readLine()) != null) {
if (!switchToStackTrace && DiskStoreCompacter.STACKTRACE_START.equals(line)) {
@@ -625,12 +618,12 @@ public class DiskStoreCommands implements GfshCommand {
} else if (switchToStackTrace) {
error.append(line).append(GfshParser.LINE_SEPARATOR);
} else {
- errorMessage = errorMessage + line;
+ errorMessage.append(line);
}
}
- if (!errorMessage.isEmpty()) {
- throw new GemFireIOException(errorMessage);
+ if (errorMessage.length() > 0) {
+ throw new GemFireIOException(errorMessage.toString());
}
// do we have to waitFor??
@@ -654,7 +647,7 @@ public class DiskStoreCommands implements GfshCommand {
if (output.length() != 0) {
Gfsh.println(output.toString());
}
- result = ResultBuilder.createUserErrorResult(errorMessage);
+ result = ResultBuilder.createUserErrorResult(errorMessage.toString());
if (logWrapper.fineEnabled()) {
logWrapper.fine(error.toString());
}
@@ -686,22 +679,20 @@ public class DiskStoreCommands implements GfshCommand {
@CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME, mandatory = true,
help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
@CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
@CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
unspecifiedDefaultValue = "-1",
help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
@CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps)
throws InterruptedException {
- Result result = null;
+ Result result;
LogWrapper logWrapper = LogWrapper.getInstance();
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
- String errorMessage = "";
+ StringBuilder errorMessage = new StringBuilder();
Process upgraderProcess = null;
try {
@@ -712,16 +703,14 @@ public class DiskStoreCommands implements GfshCommand {
+ validatedDirectories + "\"");
}
- List<String> commandList = new ArrayList<String>();
+ List<String> commandList = new ArrayList<>();
commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+ File.separatorChar + "java");
configureLogging(commandList);
if (jvmProps != null && jvmProps.length != 0) {
- for (int i = 0; i < jvmProps.length; i++) {
- commandList.add(jvmProps[i]);
- }
+ commandList.addAll(Arrays.asList(jvmProps));
}
commandList.add("-classpath");
commandList.add(System.getProperty("java.class.path", "."));
@@ -755,12 +744,11 @@ public class DiskStoreCommands implements GfshCommand {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
- String line = null;
+ String line;
while ((line = inputReader.readLine()) != null) {
output.append(line).append(GfshParser.LINE_SEPARATOR);
}
- line = null;
boolean switchToStackTrace = false;
while ((line = errorReader.readLine()) != null) {
if (!switchToStackTrace && DiskStoreUpgrader.STACKTRACE_START.equals(line)) {
@@ -768,12 +756,12 @@ public class DiskStoreCommands implements GfshCommand {
} else if (switchToStackTrace) {
error.append(line).append(GfshParser.LINE_SEPARATOR);
} else {
- errorMessage = errorMessage + line;
+ errorMessage.append(line);
}
}
- if (!errorMessage.isEmpty()) {
- throw new GemFireIOException(errorMessage);
+ if (errorMessage.length() > 0) {
+ throw new GemFireIOException(errorMessage.toString());
}
upgraderProcess.destroy();
@@ -796,7 +784,7 @@ public class DiskStoreCommands implements GfshCommand {
if (output.length() != 0) {
Gfsh.println(output.toString());
}
- result = ResultBuilder.createUserErrorResult(errorMessage);
+ result = ResultBuilder.createUserErrorResult(errorMessage.toString());
if (logWrapper.fineEnabled()) {
logWrapper.fine(error.toString());
}
@@ -823,7 +811,7 @@ public class DiskStoreCommands implements GfshCommand {
private String validatedDirectories(String[] diskDirs) {
String invalidDirectories = null;
StringBuilder builder = null;
- File diskDir = null;
+ File diskDir;
for (String diskDirPath : diskDirs) {
diskDir = new File(diskDirPath);
if (!diskDir.exists()) {
@@ -843,7 +831,7 @@ public class DiskStoreCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.DESCRIBE_DISK_STORE, help = CliStrings.DESCRIBE_DISK_STORE__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result describeDiskStore(
@CliOption(key = CliStrings.MEMBER, mandatory = true,
@@ -854,9 +842,7 @@ public class DiskStoreCommands implements GfshCommand {
help = CliStrings.DESCRIBE_DISK_STORE__NAME__HELP) final String diskStoreName) {
try {
return toCompositeResult(getDiskStoreDescription(memberName, diskStoreName));
- } catch (DiskStoreNotFoundException e) {
- return ResultBuilder.createShellClientErrorResult(e.getMessage());
- } catch (MemberNotFoundException e) {
+ } catch (DiskStoreNotFoundException | MemberNotFoundException e) {
return ResultBuilder.createShellClientErrorResult(e.getMessage());
} catch (FunctionInvocationTargetException ignore) {
return ResultBuilder.createGemFireErrorResult(CliStrings
@@ -982,7 +968,8 @@ public class DiskStoreCommands implements GfshCommand {
@CliCommand(value = CliStrings.REVOKE_MISSING_DISK_STORE,
help = CliStrings.REVOKE_MISSING_DISK_STORE__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
public Result revokeMissingDiskStore(@CliOption(key = CliStrings.REVOKE_MISSING_DISK_STORE__ID,
mandatory = true, help = CliStrings.REVOKE_MISSING_DISK_STORE__ID__HELP) String id) {
@@ -1049,7 +1036,7 @@ public class DiskStoreCommands implements GfshCommand {
membersFunctionExecutor.execute(new ShowMissingDiskStoresFunction());
final List<?> results = (List<?>) resultCollector.getResult();
- final List<Object> distributedPersistentRecoveryDetails = new ArrayList<Object>(results.size());
+ final List<Object> distributedPersistentRecoveryDetails = new ArrayList<>(results.size());
for (final Object result : results) {
if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other
// Exceptions...
@@ -1062,8 +1049,8 @@ public class DiskStoreCommands implements GfshCommand {
protected Result toMissingDiskStoresTabularResult(final List<Object> resultDetails)
throws ResultDataException {
CompositeResultData crd = ResultBuilder.createCompositeResultData();
- List<PersistentMemberPattern> missingDiskStores = new ArrayList<PersistentMemberPattern>();
- List<ColocatedRegionDetails> missingColocatedRegions = new ArrayList<ColocatedRegionDetails>();
+ List<PersistentMemberPattern> missingDiskStores = new ArrayList<>();
+ List<ColocatedRegionDetails> missingColocatedRegions = new ArrayList<>();
for (Object detail : resultDetails) {
if (detail instanceof PersistentMemberPattern) {
@@ -1082,10 +1069,10 @@ public class DiskStoreCommands implements GfshCommand {
missingDiskStoresSection.setHeader("Missing Disk Stores");
TabularResultData missingDiskStoreData = missingDiskStoresSection.addTable();
- for (PersistentMemberPattern peristentMemberDetails : missingDiskStores) {
- missingDiskStoreData.accumulate("Disk Store ID", peristentMemberDetails.getUUID());
- missingDiskStoreData.accumulate("Host", peristentMemberDetails.getHost());
- missingDiskStoreData.accumulate("Directory", peristentMemberDetails.getDirectory());
+ for (PersistentMemberPattern persistentMemberDetails : missingDiskStores) {
+ missingDiskStoreData.accumulate("Disk Store ID", persistentMemberDetails.getUUID());
+ missingDiskStoreData.accumulate("Host", persistentMemberDetails.getHost());
+ missingDiskStoreData.accumulate("Directory", persistentMemberDetails.getDirectory());
}
} else {
SectionResultData noMissingDiskStores = crd.addSection();
@@ -1124,11 +1111,9 @@ public class DiskStoreCommands implements GfshCommand {
@CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
@CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES__HELP) Boolean listPdxTypes,
@CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME,
- help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME__HELP,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE) String regionName) {
+ help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME__HELP) String regionName) {
try {
final File[] dirs = new File[diskDirs.length];
@@ -1184,7 +1169,7 @@ public class DiskStoreCommands implements GfshCommand {
DiskStoreImpl.exportOfflineSnapshot(diskStoreName, dirs, output);
String resultString =
CliStrings.format(CliStrings.EXPORT_OFFLINE_DISK_STORE__SUCCESS, diskStoreName, dir);
- return ResultBuilder.createInfoResult(resultString.toString());
+ return ResultBuilder.createInfoResult(resultString);
} catch (VirtualMachineError e) {
SystemFailure.initiateFailure(e);
throw e;
@@ -1209,31 +1194,25 @@ public class DiskStoreCommands implements GfshCommand {
@CliOption(key = CliStrings.VALIDATE_DISK_STORE__NAME, mandatory = true,
help = CliStrings.VALIDATE_DISK_STORE__NAME__HELP) String diskStoreName,
@CliOption(key = CliStrings.VALIDATE_DISK_STORE__DISKDIRS, mandatory = true,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.VALIDATE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
@CliOption(key = CliStrings.VALIDATE_DISK_STORE__J,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.VALIDATE_DISK_STORE__J__HELP) String[] jvmProps) {
try {
- String resultString = new String();
-
// create a new process ...bug 46075
StringBuilder dirList = new StringBuilder();
- for (int i = 0; i < diskDirs.length; i++) {
- dirList.append(diskDirs[i]);
+ for (String diskDir : diskDirs) {
+ dirList.append(diskDir);
dirList.append(";");
}
- List<String> commandList = new ArrayList<String>();
+ List<String> commandList = new ArrayList<>();
commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+ File.separatorChar + "java");
configureLogging(commandList);
if (jvmProps != null && jvmProps.length != 0) {
- for (int i = 0; i < jvmProps.length; i++) {
- commandList.add(jvmProps[i]);
- }
+ commandList.addAll(Arrays.asList(jvmProps));
}
// Pass any java options on to the command
@@ -1249,23 +1228,22 @@ public class DiskStoreCommands implements GfshCommand {
ProcessBuilder procBuilder = new ProcessBuilder(commandList);
StringBuilder output = new StringBuilder();
- String errorString = new String();
+ String errorString = "";
Process validateDiskStoreProcess = procBuilder.redirectErrorStream(true).start();
InputStream inputStream = validateDiskStoreProcess.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
- String line = null;
+ String line;
while ((line = br.readLine()) != null) {
output.append(line).append(GfshParser.LINE_SEPARATOR);
}
validateDiskStoreProcess.destroy();
- if (errorString != null) {
- output.append(errorString).append(GfshParser.LINE_SEPARATOR);
- }
- resultString = "Validating " + diskStoreName + GfshParser.LINE_SEPARATOR + output.toString();
- return ResultBuilder.createInfoResult(resultString.toString());
+ output.append(errorString).append(GfshParser.LINE_SEPARATOR);
+ String resultString =
+ "Validating " + diskStoreName + GfshParser.LINE_SEPARATOR + output.toString();
+ return ResultBuilder.createInfoResult(resultString);
} catch (IOException ex) {
return ResultBuilder.createGemFireErrorResult(CliStrings
.format(CliStrings.VALIDATE_DISK_STORE__MSG__IO_ERROR, diskStoreName, ex.getMessage()));
@@ -1285,39 +1263,30 @@ public class DiskStoreCommands implements GfshCommand {
@CliOption(key = CliStrings.ALTER_DISK_STORE__REGIONNAME, mandatory = true,
help = CliStrings.ALTER_DISK_STORE__REGIONNAME__HELP) String regionName,
@CliOption(key = CliStrings.ALTER_DISK_STORE__DISKDIRS,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.ALTER_DISK_STORE__DISKDIRS__HELP, mandatory = true) String[] diskDirs,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__COMPRESSOR,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
- specifiedDefaultValue = "none",
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__COMPRESSOR, specifiedDefaultValue = "none",
help = CliStrings.ALTER_DISK_STORE__COMPRESSOR__HELP) String compressorClassName,
@CliOption(key = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL__HELP) Integer concurrencyLevel,
@CliOption(key = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED__HELP) Boolean statisticsEnabled,
@CliOption(key = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY__HELP) Integer initialCapacity,
@CliOption(key = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR__HELP) Float loadFactor,
@CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION,
help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION__HELP) String lruEvictionAction,
@CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM,
help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM__HELP) String lruEvictionAlgo,
@CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT__HELP) Integer lruEvictionLimit,
@CliOption(key = CliStrings.ALTER_DISK_STORE__OFF_HEAP,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.ALTER_DISK_STORE__OFF_HEAP__HELP) Boolean offHeap,
@CliOption(key = CliStrings.ALTER_DISK_STORE__REMOVE,
- help = CliStrings.ALTER_DISK_STORE__REMOVE__HELP, mandatory = false,
- specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") boolean remove) {
+ help = CliStrings.ALTER_DISK_STORE__REMOVE__HELP, specifiedDefaultValue = "true",
+ unspecifiedDefaultValue = "false") boolean remove) {
- Result result = null;
+ Result result;
try {
File[] dirs = null;
@@ -1390,8 +1359,9 @@ public class DiskStoreCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.DESTROY_DISK_STORE, help = CliStrings.DESTROY_DISK_STORE__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
public Result destroyDiskStore(
@CliOption(key = CliStrings.DESTROY_DISK_STORE__NAME, mandatory = true,
help = CliStrings.DESTROY_DISK_STORE__NAME__HELP) String name,
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
index 87ad1be..c5d859e 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
@@ -14,6 +14,16 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.management.cli.CliMetaData;
@@ -28,7 +38,6 @@ import org.apache.geode.management.internal.cli.functions.CloseDurableCqFunction
import org.apache.geode.management.internal.cli.functions.GetSubscriptionQueueSizeFunction;
import org.apache.geode.management.internal.cli.functions.ListDurableCqNamesFunction;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResultException;
import org.apache.geode.management.internal.cli.result.ErrorResultData;
import org.apache.geode.management.internal.cli.result.InfoResultData;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
@@ -36,15 +45,7 @@ import org.apache.geode.management.internal.cli.result.TabularResultData;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* The DurableClientCommands class encapsulates all GemFire shell (Gfsh) commands related to durable
@@ -63,7 +64,7 @@ public class DurableClientCommands implements GfshCommand {
new GetSubscriptionQueueSizeFunction();
@CliCommand(value = CliStrings.LIST_DURABLE_CQS, help = CliStrings.LIST_DURABLE_CQS__HELP)
- @CliMetaData(shellOnly = false)
+ @CliMetaData()
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result listDurableClientCqs(
@CliOption(key = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, mandatory = true,
@@ -76,7 +77,7 @@ public class DurableClientCommands implements GfshCommand {
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
help = CliStrings.LIST_DURABLE_CQS__GROUP__HELP,
optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
- Result result = null;
+ Result result;
try {
boolean noResults = true;
@@ -89,9 +90,9 @@ public class DurableClientCommands implements GfshCommand {
final ResultCollector<?, ?> rc =
CliUtil.executeFunction(new ListDurableCqNamesFunction(), durableClientId, targetMembers);
final List<DurableCqNamesResult> results = (List<DurableCqNamesResult>) rc.getResult();
- Map<String, List<String>> memberCqNamesMap = new TreeMap<String, List<String>>();
- Map<String, List<String>> errorMessageNodes = new HashMap<String, List<String>>();
- Map<String, List<String>> exceptionMessageNodes = new HashMap<String, List<String>>();
+ Map<String, List<String>> memberCqNamesMap = new TreeMap<>();
+ Map<String, List<String>> errorMessageNodes = new HashMap<>();
+ Map<String, List<String>> exceptionMessageNodes = new HashMap<>();
for (DurableCqNamesResult memberResult : results) {
if (memberResult != null) {
@@ -142,21 +143,21 @@ public class DurableClientCommands implements GfshCommand {
@CliCommand(value = CliStrings.COUNT_DURABLE_CQ_EVENTS,
help = CliStrings.COUNT_DURABLE_CQ_EVENTS__HELP)
- @CliMetaData(shellOnly = false)
+ @CliMetaData()
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result countDurableCqEvents(
@CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, mandatory = true,
help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
- @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME, mandatory = false,
+ @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME,
help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME__HELP) final String cqName,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS}, mandatory = false,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
help = CliStrings.COUNT_DURABLE_CQ_EVENTS__MEMBER__HELP,
optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, mandatory = false,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
- Result result = null;
+ Result result;
try {
Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
@@ -191,19 +192,20 @@ public class DurableClientCommands implements GfshCommand {
@CliCommand(value = CliStrings.CLOSE_DURABLE_CLIENTS,
help = CliStrings.CLOSE_DURABLE_CLIENTS__HELP)
- @CliMetaData(shellOnly = false)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @CliMetaData()
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
public Result closeDurableClient(
@CliOption(key = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, mandatory = true,
help = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID__HELP) final String durableClientId,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS}, mandatory = false,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
help = CliStrings.CLOSE_DURABLE_CLIENTS__MEMBER__HELP,
optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, mandatory = false,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
- Result result = null;
+ Result result;
try {
Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
@@ -228,8 +230,9 @@ public class DurableClientCommands implements GfshCommand {
@CliCommand(value = CliStrings.CLOSE_DURABLE_CQS, help = CliStrings.CLOSE_DURABLE_CQS__HELP)
- @CliMetaData(shellOnly = false)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @CliMetaData()
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
public Result closeDurableCqs(@CliOption(key = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID,
mandatory = true,
help = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
@@ -237,14 +240,14 @@ public class DurableClientCommands implements GfshCommand {
@CliOption(key = CliStrings.CLOSE_DURABLE_CQS__NAME, mandatory = true,
help = CliStrings.CLOSE_DURABLE_CQS__NAME__HELP) final String cqName,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS}, mandatory = false,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
help = CliStrings.CLOSE_DURABLE_CQS__MEMBER__HELP,
optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, mandatory = false,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
help = CliStrings.CLOSE_DURABLE_CQS__GROUP__HELP,
optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
- Result result = null;
+ Result result;
try {
Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
@@ -273,14 +276,14 @@ public class DurableClientCommands implements GfshCommand {
private Result buildResult(List<MemberResult> results, String successHeader,
String failureHeader) {
- Result result = null;
+ Result result;
boolean failure = true;
boolean partialFailure = false;
- Map<String, List<String>> errorMap = new HashMap<String, List<String>>();
- Map<String, List<String>> successMap = new HashMap<String, List<String>>();
- Map<String, List<String>> exceptionMap = new HashMap<String, List<String>>();
+ Map<String, List<String>> errorMap = new HashMap<>();
+ Map<String, List<String>> successMap = new HashMap<>();
+ Map<String, List<String>> exceptionMap = new HashMap<>();
- /***
+ /*
* Aggregate the results from the members
*/
for (MemberResult memberResult : results) {
@@ -314,20 +317,19 @@ public class DurableClientCommands implements GfshCommand {
private Result buildTableResultForQueueSize(List<SubscriptionQueueSizeResult> results,
String queueSizeColumnName) {
- Result result = null;
+ Result result;
boolean failure = true;
- Map<String, List<String>> failureMap = new HashMap<String, List<String>>();
- Map<String, Long> memberQueueSizeTable = new TreeMap<String, Long>();
+ Map<String, List<String>> failureMap = new HashMap<>();
+ Map<String, Long> memberQueueSizeTable = new TreeMap<>();
- /***
+ /*
* Aggregate the results from the members
*/
for (SubscriptionQueueSizeResult memberResult : results) {
if (memberResult.isSuccessful()) {
failure = false;
- memberResult.getSubscriptionQueueSize();
memberQueueSizeTable.put(memberResult.getMemberNameOrId(),
memberResult.getSubscriptionQueueSize());
} else {
@@ -361,7 +363,7 @@ public class DurableClientCommands implements GfshCommand {
List<String> members = map.get(message);
if (members == null) {
- members = new LinkedList<String>();
+ members = new LinkedList<>();
}
members.add(memberNameOrId);
map.put(message, members);
@@ -373,11 +375,11 @@ public class DurableClientCommands implements GfshCommand {
Set<String> successMessages = successMap.keySet();
for (String successMessage : successMessages) {
- ird.addLine(CliStrings.format(CliStrings.ACTION_SUCCCEEDED_ON_MEMBER, successMessage));
+ ird.addLine(CliStrings.format(CliStrings.ACTION_SUCCEEDED_ON_MEMBER, successMessage));
- List<String> successfullMembers = successMap.get(successMessage);
+ List<String> successfulMembers = successMap.get(successMessage);
int num = 0;
- for (String member : successfullMembers) {
+ for (String member : successfulMembers) {
ird.addLine("" + ++num + "." + member);
}
ird.addLine("\n");
[4/6] geode git commit: GEODE-2919: Provide finer grained security
Posted by js...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
index c04820e..21d89c1 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
@@ -14,6 +14,20 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Stream;
+
+import org.apache.commons.lang.BooleanUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.SystemFailure;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.Execution;
@@ -40,7 +54,6 @@ import org.apache.geode.management.internal.cli.functions.ListFunctionFunction;
import org.apache.geode.management.internal.cli.functions.UnregisterFunction;
import org.apache.geode.management.internal.cli.functions.UserFunctionExecution;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResultException;
import org.apache.geode.management.internal.cli.result.CompositeResultData;
import org.apache.geode.management.internal.cli.result.ErrorResultData;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
@@ -48,18 +61,7 @@ import org.apache.geode.management.internal.cli.result.TabularResultData;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* @since GemFire 7.0
@@ -77,25 +79,18 @@ public class FunctionCommands implements GfshCommand {
@CliOption(key = CliStrings.EXECUTE_FUNCTION__ID, mandatory = true,
help = CliStrings.EXECUTE_FUNCTION__ID__HELP) String functionId,
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.EXECUTE_FUNCTION__ONGROUPS__HELP) String[] onGroups,
- @CliOption(key = CliStrings.MEMBER,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
- optionContext = ConverterHint.MEMBERIDNAME,
+ @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.EXECUTE_FUNCTION__ONMEMBER__HELP) String onMember,
@CliOption(key = CliStrings.EXECUTE_FUNCTION__ONREGION,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
optionContext = ConverterHint.REGION_PATH,
help = CliStrings.EXECUTE_FUNCTION__ONREGION__HELP) String onRegion,
@CliOption(key = CliStrings.EXECUTE_FUNCTION__ARGUMENTS,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.EXECUTE_FUNCTION__ARGUMENTS__HELP) String[] arguments,
@CliOption(key = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR__HELP) String resultCollector,
@CliOption(key = CliStrings.EXECUTE_FUNCTION__FILTER,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.EXECUTE_FUNCTION__FILTER__HELP) String filterString) {
Result result = null;
@@ -105,8 +100,8 @@ public class FunctionCommands implements GfshCommand {
resultTable.setHeader(headerText);
ResultCollector resultCollectorInstance = null;
Function function;
- Set<String> filters = new HashSet<String>();
- Execution execution = null;
+ Set<String> filters = new HashSet<>();
+ Execution execution;
if (functionId != null) {
functionId = functionId.trim();
}
@@ -130,31 +125,8 @@ public class FunctionCommands implements GfshCommand {
return result;
}
- if (onRegion != null && onMember != null && onGroups != null) {
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
- result = ResultBuilder.buildResult(errorResultData);
- return result;
- } else if (onRegion != null && onMember != null) {
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
- result = ResultBuilder.buildResult(errorResultData);
- return result;
- } else if (onMember != null && onGroups != null) {
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
- result = ResultBuilder.buildResult(errorResultData);
- return result;
- } else if (onRegion != null && onGroups != null) {
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
- result = ResultBuilder.buildResult(errorResultData);
- return result;
- } else if (onRegion != null && onMember != null && onGroups != null) {
+ if (isMoreThanOneIsTrue(onRegion != null, onMember != null, onGroups != null)) {
+ // Provide Only one of region/member/groups
ErrorResultData errorResultData =
ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
@@ -218,7 +190,7 @@ public class FunctionCommands implements GfshCommand {
boolean matchFound = false;
if (membersName.length > 0) {
- while (it.hasNext() && matchFound == false) {
+ while (it.hasNext() && !matchFound) {
DistributedMember dsmember = (DistributedMember) it.next();
for (String memberName : membersName) {
if (MBeanJMXAdapter.getMemberNameOrId(dsmember).equals(memberName)) {
@@ -229,7 +201,7 @@ public class FunctionCommands implements GfshCommand {
}
}
}
- if (matchFound == true) {
+ if (matchFound) {
executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
member, resultTable, onRegion);
return ResultBuilder.buildResult(resultTable);
@@ -276,7 +248,7 @@ public class FunctionCommands implements GfshCommand {
}
} else if (onGroups != null) {
// execute on group members
- Set<DistributedMember> dsMembers = new HashSet<DistributedMember>();
+ Set<DistributedMember> dsMembers = new HashSet<>();
for (String grp : onGroups) {
dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
}
@@ -310,26 +282,6 @@ public class FunctionCommands implements GfshCommand {
}
return ResultBuilder.buildResult(resultTable);
}
- } catch (InstantiationException e) {
- ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
- .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
- result = ResultBuilder.buildResult(errorResultData);
- return result;
- } catch (IllegalAccessException e) {
- ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
- .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
- result = ResultBuilder.buildResult(errorResultData);
- return result;
- } catch (IllegalArgumentException e) {
- ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
- .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
- result = ResultBuilder.buildResult(errorResultData);
- return result;
- } catch (SecurityException e) {
- ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
- .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
- result = ResultBuilder.buildResult(errorResultData);
- return result;
} catch (Exception e) {
ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
@@ -340,10 +292,14 @@ public class FunctionCommands implements GfshCommand {
return result;
}
+ private boolean isMoreThanOneIsTrue(Boolean... values) {
+ return Stream.of(values).mapToInt(BooleanUtils::toInteger).sum() > 1;
+ }
+
void executeAndGetResults(String functionId, String filterString, String resultCollector,
String[] arguments, InternalCache cache, DistributedMember member,
TabularResultData resultTable, String onRegion) {
- StringBuilder resultMessege = new StringBuilder();
+ StringBuilder resultMessage = new StringBuilder();
try {
Function function = new UserFunctionExecution();
Object[] args = new Object[5];
@@ -355,7 +311,7 @@ public class FunctionCommands implements GfshCommand {
args[2] = resultCollector;
}
if (arguments != null && arguments.length > 0) {
- args[3] = new String();
+ args[3] = "";
for (String str : arguments) {
// send via CSV separated value format
if (str != null) {
@@ -372,30 +328,25 @@ public class FunctionCommands implements GfshCommand {
for (Object resultObj : results) {
if (resultObj != null) {
if (resultObj instanceof String) {
- resultMessege.append(((String) resultObj));
+ resultMessage.append(((String) resultObj));
} else if (resultObj instanceof Exception) {
- resultMessege.append(((Exception) resultObj).getMessage());
+ resultMessage.append(((Exception) resultObj).getMessage());
} else {
- resultMessege.append(resultObj);
+ resultMessage.append(resultObj);
}
}
}
}
- toTabularResultData(resultTable, member.getId(), resultMessege.toString());
+ toTabularResultData(resultTable, member.getId(), resultMessage.toString());
} else {
toTabularResultData(resultTable, member.getId(),
CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR);
}
- } catch (FunctionException e) {
- resultMessege.append(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__COULD_NOT_EXECUTE_FUNCTION_0_ON_MEMBER_1_ERROR_2,
- functionId, member.getId(), e.getMessage()));
- toTabularResultData(resultTable, member.getId(), resultMessege.toString());
} catch (Exception e) {
- resultMessege.append(CliStrings.format(
+ resultMessage.append(CliStrings.format(
CliStrings.EXECUTE_FUNCTION__MSG__COULD_NOT_EXECUTE_FUNCTION_0_ON_MEMBER_1_ERROR_2,
functionId, member.getId(), e.getMessage()));
- toTabularResultData(resultTable, member.getId(), resultMessege.toString());
+ toTabularResultData(resultTable, member.getId(), resultMessage.toString());
}
}
@@ -409,23 +360,20 @@ public class FunctionCommands implements GfshCommand {
@CliCommand(value = CliStrings.DESTROY_FUNCTION, help = CliStrings.DESTROY_FUNCTION__HELP)
@CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION},
interceptor = "org.apache.geode.management.internal.cli.commands.FunctionCommands$Interceptor")
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
// TODO: Add optioncontext for functionId
public Result destroyFunction(
@CliOption(key = CliStrings.DESTROY_FUNCTION__ID, mandatory = true,
help = CliStrings.DESTROY_FUNCTION__HELP) String functionId,
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.DESTROY_FUNCTION__ONGROUPS__HELP) String[] groups,
- @CliOption(key = CliStrings.MEMBER,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
- optionContext = ConverterHint.MEMBERIDNAME,
+ @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.DESTROY_FUNCTION__ONMEMBER__HELP) String memberId) {
- Result result = null;
+ Result result;
try {
InternalCache cache = getCache();
- Set<DistributedMember> dsMembers = new HashSet<DistributedMember>();
+ Set<DistributedMember> dsMembers = new HashSet<>();
if (groups != null && memberId != null) {
return ResultBuilder
.createUserErrorResult(CliStrings.DESTROY_FUNCTION__MSG__PROVIDE_OPTION);
@@ -489,7 +437,7 @@ public class FunctionCommands implements GfshCommand {
// unregister on a set of of members
Function unregisterFunction = new UnregisterFunction();
FunctionService.registerFunction(unregisterFunction);
- List resultList = null;
+ List resultList;
if (DsMembers.isEmpty()) {
return ResultBuilder.createInfoResult("No members for execution");
@@ -564,9 +512,9 @@ public class FunctionCommands implements GfshCommand {
} else if (result.isSuccessful()) {
String[] strings = (String[]) result.getSerializables();
Arrays.sort(strings);
- for (int i = 0; i < strings.length; i++) {
+ for (String string : strings) {
tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Function", strings[i]);
+ tabularData.accumulate("Function", string);
accumulatedData = true;
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshCommand.java
----------------------------------------------------------------------
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 86296b4..88f730e 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,7 +14,14 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.HashSet;
+import java.util.Set;
+
import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.CommandMarker;
+
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.Function;
@@ -23,17 +30,12 @@ import org.apache.geode.distributed.DistributedMember;
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.i18n.CliStrings;
import org.apache.geode.management.internal.cli.shell.Gfsh;
import org.apache.geode.management.internal.cli.util.MemberNotFoundException;
-import org.springframework.shell.core.CommandMarker;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.HashSet;
-import java.util.Set;
/**
* Encapsulates common functionality for implementing command classes for the Geode shell (gfsh).
@@ -102,6 +104,10 @@ public interface GfshCommand extends CommandMarker {
return (InternalCache) CacheFactory.getAnyInstance();
}
+ default SecurityService getSecurityService() {
+ return getCache().getSecurityService();
+ }
+
default Gfsh getGfsh() {
return Gfsh.getCurrentInstance();
}
@@ -129,7 +135,7 @@ public interface GfshCommand extends CommandMarker {
*/
@Deprecated
default Set<DistributedMember> getMembers(final InternalCache cache) {
- Set<DistributedMember> members = new HashSet<DistributedMember>(cache.getMembers());
+ Set<DistributedMember> members = new HashSet<>(cache.getMembers());
members.add(cache.getDistributedSystem().getDistributedMember());
return members;
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
index 4d8d5fe..4734b4c 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
@@ -14,7 +14,20 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicReference;
+
import org.apache.commons.lang.ArrayUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.SystemFailure;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
@@ -23,7 +36,6 @@ import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.FunctionInvocationTargetException;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.execute.AbstractExecution;
import org.apache.geode.internal.lang.StringUtils;
import org.apache.geode.management.cli.CliMetaData;
@@ -47,18 +59,7 @@ import org.apache.geode.management.internal.configuration.domain.XmlEntity;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* The IndexCommands class encapsulates all GemFire shell (Gfsh) commands related to indexes defined
@@ -80,10 +81,9 @@ public class IndexCommands implements GfshCommand {
Collections.synchronizedSet(new HashSet<IndexInfo>());
@CliCommand(value = CliStrings.LIST_INDEX, help = CliStrings.LIST_INDEX__HELP)
- @CliMetaData(shellOnly = false,
- relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
- public Result listIndex(@CliOption(key = CliStrings.LIST_INDEX__STATS, mandatory = false,
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ, target = Target.QUERY)
+ public Result listIndex(@CliOption(key = CliStrings.LIST_INDEX__STATS,
specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
help = CliStrings.LIST_INDEX__STATS__HELP) final boolean showStats) {
try {
@@ -114,7 +114,7 @@ public class IndexCommands implements GfshCommand {
functionExecutor.execute(new ListIndexFunction());
final List<?> results = (List<?>) resultsCollector.getResult();
- final List<IndexDetails> indexDetailsList = new ArrayList<IndexDetails>(results.size());
+ final List<IndexDetails> indexDetailsList = new ArrayList<>(results.size());
for (Object result : results) {
if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other Exceptions
@@ -161,9 +161,10 @@ public class IndexCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
- @CliMetaData(shellOnly = false,
- relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
// TODO : Add optionContext for indexName
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
public Result createIndex(@CliOption(key = CliStrings.CREATE_INDEX__NAME, mandatory = true,
help = CliStrings.CREATE_INDEX__NAME__HELP) final String indexName,
@@ -174,26 +175,25 @@ public class IndexCommands implements GfshCommand {
optionContext = ConverterHint.REGION_PATH,
help = CliStrings.CREATE_INDEX__REGION__HELP) String regionPath,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS}, mandatory = false,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.CREATE_INDEX__MEMBER__HELP) final String[] memberNameOrID,
- @CliOption(key = CliStrings.CREATE_INDEX__TYPE, mandatory = false,
- unspecifiedDefaultValue = "range", optionContext = ConverterHint.INDEX_TYPE,
+ @CliOption(key = CliStrings.CREATE_INDEX__TYPE, unspecifiedDefaultValue = "range",
+ optionContext = ConverterHint.INDEX_TYPE,
help = CliStrings.CREATE_INDEX__TYPE__HELP) final String indexType,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, mandatory = false,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.CREATE_INDEX__GROUP__HELP) final String[] group) {
- Result result = null;
+ Result result;
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
- getCache().getSecurityService().authorizeRegionManage(regionPath);
try {
final Cache cache = CacheFactory.getAnyInstance();
- int idxType = IndexInfo.RANGE_INDEX;
+ int idxType;
// Index type check
if ("range".equalsIgnoreCase(indexType)) {
@@ -235,8 +235,8 @@ public class IndexCommands implements GfshCommand {
CliUtil.executeFunction(createIndexFunction, indexInfo, targetMembers);
final List<Object> funcResults = (List<Object>) rc.getResult();
- final Set<String> successfulMembers = new TreeSet<String>();
- final Map<String, Set<String>> indexOpFailMap = new HashMap<String, Set<String>>();
+ final Set<String> successfulMembers = new TreeSet<>();
+ final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
for (final Object funcResult : funcResults) {
if (funcResult instanceof CliFunctionResult) {
@@ -253,7 +253,7 @@ public class IndexCommands implements GfshCommand {
Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
if (failedMembers == null) {
- failedMembers = new TreeSet<String>();
+ failedMembers = new TreeSet<>();
}
failedMembers.add(cliFunctionResult.getMemberIdOrName());
indexOpFailMap.put(exceptionMessage, failedMembers);
@@ -314,25 +314,25 @@ public class IndexCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP)
- @CliMetaData(shellOnly = false,
- relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- public Result destroyIndex(@CliOption(key = CliStrings.DESTROY_INDEX__NAME, mandatory = false,
- unspecifiedDefaultValue = "",
- help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName,
-
- @CliOption(key = CliStrings.DESTROY_INDEX__REGION, mandatory = false,
- optionContext = ConverterHint.REGION_PATH,
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ public Result destroyIndex(
+ @CliOption(key = CliStrings.DESTROY_INDEX__NAME, unspecifiedDefaultValue = "",
+ help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName,
+
+ @CliOption(key = CliStrings.DESTROY_INDEX__REGION, optionContext = ConverterHint.REGION_PATH,
help = CliStrings.DESTROY_INDEX__REGION__HELP) final String regionPath,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS}, mandatory = false,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.DESTROY_INDEX__MEMBER__HELP) final String[] memberNameOrID,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, mandatory = false,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.DESTROY_INDEX__GROUP__HELP) final String[] group) {
- Result result = null;
+ Result result;
if (StringUtils.isBlank(indexName) && StringUtils.isBlank(regionPath)
&& ArrayUtils.isEmpty(group) && ArrayUtils.isEmpty(memberNameOrID)) {
@@ -340,18 +340,11 @@ public class IndexCommands implements GfshCommand {
CliStrings.format(CliStrings.PROVIDE_ATLEAST_ONE_OPTION, CliStrings.DESTROY_INDEX));
}
- String regionName = null;
final Cache cache = CacheFactory.getAnyInstance();
-
- // If a regionName is specified, then authorize data manage on the regionName, otherwise, it
- // requires data manage permission on all regions
- if (StringUtils.isNotBlank(regionPath)) {
+ String regionName = null;
+ if (regionPath != null) {
regionName = regionPath.startsWith("/") ? regionPath.substring(1) : regionPath;
- getCache().getSecurityService().authorizeRegionManage(regionName);
- } else {
- getCache().getSecurityService().authorizeDataManage();
}
-
IndexInfo indexInfo = new IndexInfo(indexName, regionName);
Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
@@ -362,8 +355,8 @@ public class IndexCommands implements GfshCommand {
ResultCollector rc = CliUtil.executeFunction(destroyIndexFunction, indexInfo, targetMembers);
List<Object> funcResults = (List<Object>) rc.getResult();
- Set<String> successfulMembers = new TreeSet<String>();
- Map<String, Set<String>> indexOpFailMap = new HashMap<String, Set<String>>();
+ Set<String> successfulMembers = new TreeSet<>();
+ Map<String, Set<String>> indexOpFailMap = new HashMap<>();
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
for (Object funcResult : funcResults) {
@@ -383,7 +376,7 @@ public class IndexCommands implements GfshCommand {
Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
if (failedMembers == null) {
- failedMembers = new TreeSet<String>();
+ failedMembers = new TreeSet<>();
}
failedMembers.add(cliFunctionResult.getMemberIdOrName());
indexOpFailMap.put(exceptionMessage, failedMembers);
@@ -451,9 +444,10 @@ public class IndexCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.DEFINE_INDEX, help = CliStrings.DEFINE_INDEX__HELP)
- @CliMetaData(shellOnly = false,
- relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
// TODO : Add optionContext for indexName
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
public Result defineIndex(@CliOption(key = CliStrings.DEFINE_INDEX_NAME, mandatory = true,
help = CliStrings.DEFINE_INDEX__HELP) final String indexName,
@@ -464,16 +458,14 @@ public class IndexCommands implements GfshCommand {
optionContext = ConverterHint.REGION_PATH,
help = CliStrings.DEFINE_INDEX__REGION__HELP) String regionPath,
- @CliOption(key = CliStrings.DEFINE_INDEX__TYPE, mandatory = false,
- unspecifiedDefaultValue = "range", optionContext = ConverterHint.INDEX_TYPE,
+ @CliOption(key = CliStrings.DEFINE_INDEX__TYPE, unspecifiedDefaultValue = "range",
+ optionContext = ConverterHint.INDEX_TYPE,
help = CliStrings.DEFINE_INDEX__TYPE__HELP) final String indexType) {
- Result result = null;
+ Result result;
XmlEntity xmlEntity = null;
- getCache().getSecurityService().authorizeRegionManage(regionPath);
-
- int idxType = IndexInfo.RANGE_INDEX;
+ int idxType;
// Index type check
if ("range".equalsIgnoreCase(indexType)) {
@@ -518,21 +510,21 @@ public class IndexCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.CREATE_DEFINED_INDEXES, help = CliStrings.CREATE_DEFINED__HELP)
- @CliMetaData(shellOnly = false,
- relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
// TODO : Add optionContext for indexName
public Result createDefinedIndexes(
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS}, mandatory = false,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.CREATE_DEFINED_INDEXES__MEMBER__HELP) final String[] memberNameOrID,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, mandatory = false,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.CREATE_DEFINED_INDEXES__GROUP__HELP) final String[] group) {
- Result result = null;
+ Result result;
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
if (indexDefinitions.isEmpty()) {
@@ -553,8 +545,8 @@ public class IndexCommands implements GfshCommand {
CliUtil.executeFunction(createDefinedIndexesFunction, indexDefinitions, targetMembers);
final List<Object> funcResults = (List<Object>) rc.getResult();
- final Set<String> successfulMembers = new TreeSet<String>();
- final Map<String, Set<String>> indexOpFailMap = new HashMap<String, Set<String>>();
+ final Set<String> successfulMembers = new TreeSet<>();
+ final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
for (final Object funcResult : funcResults) {
if (funcResult instanceof CliFunctionResult) {
@@ -571,7 +563,7 @@ public class IndexCommands implements GfshCommand {
Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
if (failedMembers == null) {
- failedMembers = new TreeSet<String>();
+ failedMembers = new TreeSet<>();
}
failedMembers.add(cliFunctionResult.getMemberIdOrName());
indexOpFailMap.put(exceptionMessage, failedMembers);
@@ -624,9 +616,9 @@ public class IndexCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.CLEAR_DEFINED_INDEXES, help = CliStrings.CLEAR_DEFINED__HELP)
- @CliMetaData(shellOnly = false,
- relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
// TODO : Add optionContext for indexName
public Result clearDefinedIndexes() {
indexDefinitions.clear();
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
index 637fa0e..1415bc6 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
@@ -14,7 +14,41 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.zip.DataFormatException;
+import java.util.zip.GZIPInputStream;
+
+import javax.management.ObjectName;
+
import org.apache.commons.lang.StringUtils;
+import org.apache.logging.log4j.Logger;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.LogWriter;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.Function;
@@ -60,7 +94,6 @@ import org.apache.geode.management.internal.cli.functions.NetstatFunction.Netsta
import org.apache.geode.management.internal.cli.functions.ShutDownFunction;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
-import org.apache.geode.management.internal.cli.result.CommandResultException;
import org.apache.geode.management.internal.cli.result.CompositeResultData;
import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
import org.apache.geode.management.internal.cli.result.ErrorResultData;
@@ -72,39 +105,6 @@ import org.apache.geode.management.internal.cli.result.TabularResultData;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.logging.log4j.Logger;
-import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.zip.DataFormatException;
-import java.util.zip.GZIPInputStream;
-import javax.management.ObjectName;
/**
* @since GemFire 7.0
@@ -172,7 +172,7 @@ public class MiscellaneousCommands implements GfshCommand {
return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__IMPROPER_TIMEOUT);
}
- // convert to mili-seconds
+ // convert to milliseconds
long timeout = userSpecifiedTimeout * 1000;
InternalCache cache = getCache();
@@ -211,7 +211,7 @@ public class MiscellaneousCommands implements GfshCommand {
}
for (DistributedMember locator : locators) {
- Set<DistributedMember> lsSet = new HashSet<DistributedMember>();
+ Set<DistributedMember> lsSet = new HashSet<>();
lsSet.add(locator);
long elapsedTime = shutDownNodeWithTimeOut(timeout, lsSet);
timeout = timeout - elapsedTime;
@@ -224,7 +224,7 @@ public class MiscellaneousCommands implements GfshCommand {
return ResultBuilder.createInfoResult("Shutdown is triggered");
}
// now shut down this manager
- Set<DistributedMember> mgrSet = new HashSet<DistributedMember>();
+ Set<DistributedMember> mgrSet = new HashSet<>();
mgrSet.add(manager);
// No need to check further timeout as this is the last node we will be
// shutting down
@@ -290,18 +290,16 @@ public class MiscellaneousCommands implements GfshCommand {
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
public Result gc(
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.GC__GROUP__HELP) String[] groups,
@CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.GC__MEMBER__HELP) String memberId) {
InternalCache cache = getCache();
- Result result = null;
+ Result result;
CompositeResultData gcResultTable = ResultBuilder.createCompositeResultData();
TabularResultData resultTable = gcResultTable.addSection().addTable("Table1");
String headerText = "GC Summary";
resultTable.setHeader(headerText);
- Set<DistributedMember> dsMembers = new HashSet<DistributedMember>();
+ Set<DistributedMember> dsMembers = new HashSet<>();
if (memberId != null && memberId.length() > 0) {
DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberId);
if (member == null) {
@@ -328,13 +326,12 @@ public class MiscellaneousCommands implements GfshCommand {
Result executeAndBuildResult(TabularResultData resultTable, Set<DistributedMember> dsMembers) {
try {
- List<?> resultList = null;
+ List<?> resultList;
Function garbageCollectionFunction = new GarbageCollectionFunction();
resultList =
(List<?>) CliUtil.executeFunction(garbageCollectionFunction, null, dsMembers).getResult();
- for (int i = 0; i < resultList.size(); i++) {
- Object object = resultList.get(i);
+ for (Object object : resultList) {
if (object instanceof Exception) {
LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
((Throwable) object));
@@ -380,24 +377,20 @@ public class MiscellaneousCommands implements GfshCommand {
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
// TODO : Verify the auto-completion for multiple values.
public Result netstat(
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS}, mandatory = false,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.ALL_MEMBER_IDNAME,
help = CliStrings.NETSTAT__MEMBER__HELP) String[] members,
- @CliOption(key = CliStrings.GROUP, mandatory = false,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
- optionContext = ConverterHint.MEMBERGROUP,
+ @CliOption(key = CliStrings.GROUP, optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.NETSTAT__GROUP__HELP) String group,
@CliOption(key = CliStrings.NETSTAT__FILE,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.NETSTAT__FILE__HELP) String saveAs,
@CliOption(key = CliStrings.NETSTAT__WITHLSOF, specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.NETSTAT__WITHLSOF__HELP) boolean withlsof) {
- Result result = null;
+ Result result;
- Map<String, DistributedMember> hostMemberMap = new HashMap<String, DistributedMember>();
- Map<String, List<String>> hostMemberListMap = new HashMap<String, List<String>>();
+ Map<String, DistributedMember> hostMemberMap = new HashMap<>();
+ Map<String, List<String>> hostMemberListMap = new HashMap<>();
try {
if (members != null && members.length > 0 && group != null) {
@@ -410,7 +403,7 @@ public class MiscellaneousCommands implements GfshCommand {
InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
if (members != null) {
- Set<String> notFoundMembers = new HashSet<String>();
+ Set<String> notFoundMembers = new HashSet<>();
for (String memberIdOrName : members) {
Set<DistributedMember> membersToExecuteOn = CliUtil.getAllMembers(system);
boolean memberFound = false;
@@ -435,7 +428,7 @@ public class MiscellaneousCommands implements GfshCommand {
new Object[] {CliUtil.collectionToString(notFoundMembers, -1)}));
}
} else {
- Set<DistributedMember> membersToExecuteOn = null;
+ Set<DistributedMember> membersToExecuteOn;
if (group != null) {
membersToExecuteOn = system.getGroupMembers(group);
} else {
@@ -453,7 +446,7 @@ public class MiscellaneousCommands implements GfshCommand {
}
}
- String lineSeparatorToUse = null;
+ String lineSeparatorToUse;
lineSeparatorToUse = CommandExecutionContext.getShellLineSeparator();
if (lineSeparatorToUse == null) {
lineSeparatorToUse = GfshParser.LINE_SEPARATOR;
@@ -461,13 +454,12 @@ public class MiscellaneousCommands implements GfshCommand {
NetstatFunctionArgument nfa = new NetstatFunctionArgument(lineSeparatorToUse, withlsof);
if (!hostMemberMap.isEmpty()) {
- Set<DistributedMember> membersToExecuteOn =
- new HashSet<DistributedMember>(hostMemberMap.values());
+ Set<DistributedMember> membersToExecuteOn = new HashSet<>(hostMemberMap.values());
ResultCollector<?, ?> netstatResult =
CliUtil.executeFunction(NetstatFunction.INSTANCE, nfa, membersToExecuteOn);
List<?> resultList = (List<?>) netstatResult.getResult();
- for (int i = 0; i < resultList.size(); i++) {
- NetstatFunctionResult netstatFunctionResult = (NetstatFunctionResult) resultList.get(i);
+ for (Object aResultList : resultList) {
+ NetstatFunctionResult netstatFunctionResult = (NetstatFunctionResult) aResultList;
DeflaterInflaterData deflaterInflaterData = netstatFunctionResult.getCompressedBytes();
try {
String remoteHost = netstatFunctionResult.getHost();
@@ -528,9 +520,9 @@ public class MiscellaneousCommands implements GfshCommand {
}
// Maintain all members for a host - display purpose
- List<String> list = null;
+ List<String> list;
if (!hostMemberListMap.containsKey(host)) {
- list = new ArrayList<String>();
+ list = new ArrayList<>();
hostMemberListMap.put(host, list);
} else {
list = hostMemberListMap.get(host);
@@ -539,13 +531,13 @@ public class MiscellaneousCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.SHOW_DEADLOCK, help = CliStrings.SHOW_DEADLOCK__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result showDeadlock(@CliOption(key = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE,
help = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE__HELP,
mandatory = true) String filename) {
- Result result = null;
+ Result result;
try {
if (!filename.endsWith(".txt")) {
return ResultBuilder
@@ -590,20 +582,19 @@ public class MiscellaneousCommands implements GfshCommand {
}
@CliCommand(value = CliStrings.SHOW_LOG, help = CliStrings.SHOW_LOG_HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result showLog(
@CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.SHOW_LOG_MEMBER_HELP, mandatory = true) String memberNameOrId,
@CliOption(key = CliStrings.SHOW_LOG_LINE_NUM, unspecifiedDefaultValue = "0",
- help = CliStrings.SHOW_LOG_LINE_NUM_HELP, mandatory = false) int numberOfLines) {
- Result result = null;
+ help = CliStrings.SHOW_LOG_LINE_NUM_HELP) int numberOfLines) {
+ Result result;
try {
InternalCache cache = getCache();
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
- MemberMXBean bean = null;
+ MemberMXBean bean;
DistributedMember memberToBeInvoked = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
if (memberToBeInvoked != null) {
String memberId = memberToBeInvoked.getId();
@@ -655,7 +646,7 @@ public class MiscellaneousCommands implements GfshCommand {
* Current implementation supports writing it to a file and returning the location of the file
*/
@CliCommand(value = CliStrings.EXPORT_STACKTRACE, help = CliStrings.EXPORT_STACKTRACE__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result exportStackTrace(@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.ALL_MEMBER_IDNAME,
@@ -671,7 +662,7 @@ public class MiscellaneousCommands implements GfshCommand {
unspecifiedDefaultValue = "false",
help = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT__HELP) boolean failIfFilePresent) {
- Result result = null;
+ Result result;
StringBuffer filePrefix = new StringBuffer("stacktrace");
if (fileName == null) {
@@ -690,7 +681,7 @@ public class MiscellaneousCommands implements GfshCommand {
InfoResultData resultData = ResultBuilder.createInfoResultData();
- Map<String, byte[]> dumps = new HashMap<String, byte[]>();
+ Map<String, byte[]> dumps = new HashMap<>();
Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
if (targetMembers.isEmpty()) {
return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
@@ -735,7 +726,7 @@ public class MiscellaneousCommands implements GfshCommand {
return ResultBuilder
.createShellClientAbortOperationResult(CliStrings.EXPORT_STACKTRACE_MSG_ABORTING);
} else {
- // we dont to show any info result
+ // we don't to show any info result
return ResultBuilder.createInfoResult("");
}
}
@@ -750,17 +741,15 @@ public class MiscellaneousCommands implements GfshCommand {
* @throws IOException
*/
private String writeStacksToFile(Map<String, byte[]> dumps, String fileName) throws IOException {
- String filePath = null;
- OutputStream os = null;
- PrintWriter ps = null;
- File outputFile = null;
+ String filePath;
+ PrintWriter ps;
+ File outputFile;
- try {
- outputFile = new File(fileName);
- os = new FileOutputStream(outputFile);
+ outputFile = new File(fileName);
+ try (OutputStream os = new FileOutputStream(outputFile)) {
ps = new PrintWriter(os);
- for (Map.Entry<String, byte[]> entry : dumps.entrySet()) {
+ for (Entry<String, byte[]> entry : dumps.entrySet()) {
ps.append("*** Stack-trace for member " + entry.getKey() + " ***");
ps.flush();
GZIPInputStream zipIn = new GZIPInputStream(new ByteArrayInputStream(entry.getValue()));
@@ -774,15 +763,13 @@ public class MiscellaneousCommands implements GfshCommand {
}
ps.flush();
filePath = outputFile.getCanonicalPath();
- } finally {
- os.close();
}
return filePath;
}
@CliCommand(value = CliStrings.SHOW_METRICS, help = CliStrings.SHOW_METRICS__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEODE_STATISTICS})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_STATISTICS})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result showMetrics(
@CliOption(key = {CliStrings.MEMBER}, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
@@ -796,7 +783,7 @@ public class MiscellaneousCommands implements GfshCommand {
@CliOption(key = {CliStrings.SHOW_METRICS__CATEGORY},
help = CliStrings.SHOW_METRICS__CATEGORY__HELP) String[] categories) {
- Result result = null;
+ Result result;
try {
if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
@@ -873,11 +860,10 @@ public class MiscellaneousCommands implements GfshCommand {
* @return ResultData with required System wide statistics or ErrorResultData if DS MBean is not
* found to gather metrics
*/
- private ResultData getSystemWideMetrics(String export_to_report_to, String[] categoriesArr)
- throws Exception {
+ private ResultData getSystemWideMetrics(String export_to_report_to, String[] categoriesArr) {
final InternalCache cache = getCache();
- final ManagementService managmentService = ManagementService.getManagementService(cache);
- DistributedSystemMXBean dsMxBean = managmentService.getDistributedSystemMXBean();
+ final ManagementService managementService = ManagementService.getManagementService(cache);
+ DistributedSystemMXBean dsMxBean = managementService.getDistributedSystemMXBean();
StringBuilder csvBuilder = null;
if (dsMxBean != null) {
@@ -898,7 +884,7 @@ public class MiscellaneousCommands implements GfshCommand {
if (categoriesArr != null && categoriesArr.length != 0) {
Set<String> categories = createSet(categoriesArr);
- Set<String> checkSet = new HashSet<String>(categoriesMap.keySet());
+ Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
Set<String> userCategories = getSetDifference(categories, checkSet);
// Checking if the categories specified by the user are valid or not
@@ -923,12 +909,12 @@ public class MiscellaneousCommands implements GfshCommand {
}
metricsTable.setHeader("Cluster-wide Metrics");
- if (categoriesMap.get("cluster").booleanValue()) {
+ if (categoriesMap.get("cluster")) {
writeToTableAndCsv(metricsTable, "cluster", "totalHeapSize", dsMxBean.getTotalHeapSize(),
csvBuilder);
}
- if (categoriesMap.get("cache").booleanValue()) {
+ if (categoriesMap.get("cache")) {
writeToTableAndCsv(metricsTable, "cache", "totalRegionEntryCount",
dsMxBean.getTotalRegionEntryCount(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "totalRegionCount", dsMxBean.getTotalRegionCount(),
@@ -939,7 +925,7 @@ public class MiscellaneousCommands implements GfshCommand {
csvBuilder);
}
- if (categoriesMap.get("diskstore").booleanValue()) {
+ if (categoriesMap.get("diskstore")) {
writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
dsMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
@@ -952,7 +938,7 @@ public class MiscellaneousCommands implements GfshCommand {
dsMxBean.getTotalBackupInProgress(), csvBuilder);
}
- if (categoriesMap.get("query").booleanValue()) {
+ if (categoriesMap.get("query")) {
writeToTableAndCsv(metricsTable, "query", "activeCQCount", dsMxBean.getActiveCQCount(),
csvBuilder);
writeToTableAndCsv(metricsTable, "", "queryRequestRate", dsMxBean.getQueryRequestRate(),
@@ -988,7 +974,7 @@ public class MiscellaneousCommands implements GfshCommand {
ObjectName memberMBeanName = managementService.getMemberMBeanName(distributedMember);
MemberMXBean memberMxBean =
managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
- ObjectName csMxBeanName = null;
+ ObjectName csMxBeanName;
CacheServerMXBean csMxBean = null;
if (memberMxBean != null) {
@@ -1028,7 +1014,7 @@ public class MiscellaneousCommands implements GfshCommand {
if (categoriesArr != null && categoriesArr.length != 0) {
Set<String> categories = createSet(categoriesArr);
- Set<String> checkSet = new HashSet<String>(categoriesMap.keySet());
+ Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
Set<String> userCategories = getSetDifference(categories, checkSet);
// Checking if the categories specified by the user are valid or not
@@ -1056,7 +1042,7 @@ public class MiscellaneousCommands implements GfshCommand {
*/
// member, jvm, region, serialization, communication, function, transaction, diskstore, lock,
// eviction, distribution
- if (categoriesMap.get("member").booleanValue()) {
+ if (categoriesMap.get("member")) {
writeToTableAndCsv(metricsTable, "member", "upTime", memberMxBean.getMemberUpTime(),
csvBuilder);
writeToTableAndCsv(metricsTable, "", "cpuUsage", memberMxBean.getCpuUsage(), csvBuilder);
@@ -1068,7 +1054,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* JVM Metrics
*/
- if (categoriesMap.get("jvm").booleanValue()) {
+ if (categoriesMap.get("jvm")) {
writeToTableAndCsv(metricsTable, "jvm ", "jvmThreads ", jvmMetrics.getTotalThreads(),
csvBuilder);
writeToTableAndCsv(metricsTable, "", "fileDescriptorLimit",
@@ -1079,7 +1065,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Member wide region metrics
*/
- if (categoriesMap.get("region").booleanValue()) {
+ if (categoriesMap.get("region")) {
writeToTableAndCsv(metricsTable, "region ", "totalRegionCount ",
memberMxBean.getTotalRegionCount(), csvBuilder);
String[] regionNames = memberMxBean.listRegions();
@@ -1120,7 +1106,7 @@ public class MiscellaneousCommands implements GfshCommand {
csvBuilder);
writeToTableAndCsv(metricsTable, "", "putAllAvgLatency", memberMxBean.getPutAllAvgLatency(),
csvBuilder);
- // Not available from stats. After Stats re-org it will be avaialble
+ // Not available from stats. After Stats re-org it will be available
// writeToTableAndCsv(metricsTable, "", "getAllAvgLatency",
// memberMxBean.getGetAllAvgLatency(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "totalMissCount", memberMxBean.getTotalMissCount(),
@@ -1140,7 +1126,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* SERIALIZATION
*/
- if (categoriesMap.get("serialization").booleanValue()) {
+ if (categoriesMap.get("serialization")) {
writeToTableAndCsv(metricsTable, "serialization", "serializationRate",
memberMxBean.getSerializationRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "serializationLatency",
@@ -1160,7 +1146,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Communication Metrics
*/
- if (categoriesMap.get("communication").booleanValue()) {
+ if (categoriesMap.get("communication")) {
writeToTableAndCsv(metricsTable, "communication", "bytesSentRate",
memberMxBean.getBytesSentRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "bytesReceivedRate",
@@ -1177,23 +1163,20 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Member wide function metrics
*/
- if (categoriesMap.get("function").booleanValue()) {
+ if (categoriesMap.get("function")) {
writeToTableAndCsv(metricsTable, "function", "numRunningFunctions",
memberMxBean.getNumRunningFunctions(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "functionExecutionRate",
memberMxBean.getFunctionExecutionRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "numRunningFunctionsHavingResults",
memberMxBean.getNumRunningFunctionsHavingResults(), csvBuilder);
- // Not Avaialble from Stats
- // writeToTableAndCsv(metricsTable, "", "funcExecutionQueueSize",
- // memberMxBean.getFuncExecutionQueueSize(), csvBuilder);
}
/*
* totalTransactionsCount currentTransactionalThreadIds transactionCommitsAvgLatency
* transactionCommittedTotalCount transactionRolledBackTotalCount transactionCommitsRate
*/
- if (categoriesMap.get("transaction").booleanValue()) {
+ if (categoriesMap.get("transaction")) {
writeToTableAndCsv(metricsTable, "transaction", "totalTransactionsCount",
memberMxBean.getTotalTransactionsCount(), csvBuilder);
@@ -1209,7 +1192,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Member wide disk metrics
*/
- if (categoriesMap.get("diskstore").booleanValue()) {
+ if (categoriesMap.get("diskstore")) {
writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
memberMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
@@ -1227,7 +1210,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Member wide Lock
*/
- if (categoriesMap.get("lock").booleanValue()) {
+ if (categoriesMap.get("lock")) {
writeToTableAndCsv(metricsTable, "lock", "lockWaitsInProgress",
memberMxBean.getLockWaitsInProgress(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "totalLockWaitTime",
@@ -1240,7 +1223,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Eviction
*/
- if (categoriesMap.get("eviction").booleanValue()) {
+ if (categoriesMap.get("eviction")) {
writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
memberMxBean.getLruEvictionRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "lruDestroyRate", memberMxBean.getLruDestroyRate(),
@@ -1249,9 +1232,9 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Distribution
*/
- if (categoriesMap.get("distribution").booleanValue()) {
+ if (categoriesMap.get("distribution")) {
writeToTableAndCsv(metricsTable, "distribution", "getInitialImagesInProgress",
- memberMxBean.getInitialImagesInProgres(), csvBuilder);
+ memberMxBean.getInitialImagesInProgress(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "getInitialImageTime",
memberMxBean.getInitialImageTime(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "getInitialImageKeysReceived",
@@ -1261,7 +1244,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* OffHeap
*/
- if (categoriesMap.get("offheap").booleanValue()) {
+ if (categoriesMap.get("offheap")) {
writeToTableAndCsv(metricsTable, "offheap", "maxMemory", memberMxBean.getOffHeapMaxMemory(),
csvBuilder);
writeToTableAndCsv(metricsTable, "", "freeMemory", memberMxBean.getOffHeapFreeMemory(),
@@ -1381,7 +1364,7 @@ public class MiscellaneousCommands implements GfshCommand {
if (categoriesArr != null && categoriesArr.length != 0) {
Set<String> categories = createSet(categoriesArr);
- Set<String> checkSet = new HashSet<String>(categoriesMap.keySet());
+ Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
Set<String> userCategories = getSetDifference(categories, checkSet);
// Checking if the categories specified by the user are valid or not
@@ -1407,14 +1390,14 @@ public class MiscellaneousCommands implements GfshCommand {
* General System metrics
*/
// cluster, region, partition , diskstore, callback, eviction
- if (categoriesMap.get("cluster").booleanValue()) {
+ if (categoriesMap.get("cluster")) {
writeToTableAndCsv(metricsTable, "cluster", "member count", regionMxBean.getMemberCount(),
csvBuilder);
writeToTableAndCsv(metricsTable, "", "region entry count",
regionMxBean.getSystemRegionEntryCount(), csvBuilder);
}
- if (categoriesMap.get("region").booleanValue()) {
+ if (categoriesMap.get("region")) {
writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
regionMxBean.getLastModifiedTime(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
@@ -1432,7 +1415,7 @@ public class MiscellaneousCommands implements GfshCommand {
csvBuilder);
}
- if (categoriesMap.get("partition").booleanValue()) {
+ if (categoriesMap.get("partition")) {
writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
regionMxBean.getPutLocalRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
@@ -1456,7 +1439,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Disk store
*/
- if (categoriesMap.get("diskstore").booleanValue()) {
+ if (categoriesMap.get("diskstore")) {
writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "diskReadsRate", regionMxBean.getDiskReadsRate(),
@@ -1472,7 +1455,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* LISTENER
*/
- if (categoriesMap.get("callback").booleanValue()) {
+ if (categoriesMap.get("callback")) {
writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
@@ -1482,7 +1465,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Eviction
*/
- if (categoriesMap.get("eviction").booleanValue()) {
+ if (categoriesMap.get("eviction")) {
writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
regionMxBean.getLruEvictionRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
@@ -1549,7 +1532,7 @@ public class MiscellaneousCommands implements GfshCommand {
if (categoriesArr != null && categoriesArr.length != 0) {
Set<String> categories = createSet(categoriesArr);
- Set<String> checkSet = new HashSet<String>(categoriesMap.keySet());
+ Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
Set<String> userCategories = getSetDifference(categories, checkSet);
// Checking if the categories specified by the user are valid or not
@@ -1572,7 +1555,7 @@ public class MiscellaneousCommands implements GfshCommand {
}
}
- if (categoriesMap.get("region").booleanValue()) {
+ if (categoriesMap.get("region")) {
writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
regionMxBean.getLastModifiedTime(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
@@ -1590,7 +1573,7 @@ public class MiscellaneousCommands implements GfshCommand {
csvBuilder);
}
- if (categoriesMap.get("partition").booleanValue()) {
+ if (categoriesMap.get("partition")) {
writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
regionMxBean.getPutLocalRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
@@ -1616,7 +1599,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Disk store
*/
- if (categoriesMap.get("diskstore").booleanValue()) {
+ if (categoriesMap.get("diskstore")) {
writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "diskReadsRate", "" + regionMxBean.getDiskReadsRate(),
@@ -1631,7 +1614,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* LISTENER
*/
- if (categoriesMap.get("callback").booleanValue()) {
+ if (categoriesMap.get("callback")) {
writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
@@ -1641,7 +1624,7 @@ public class MiscellaneousCommands implements GfshCommand {
/*
* Eviction
*/
- if (categoriesMap.get("eviction").booleanValue()) {
+ if (categoriesMap.get("eviction")) {
writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
regionMxBean.getLruEvictionRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
@@ -1686,7 +1669,7 @@ public class MiscellaneousCommands implements GfshCommand {
double metricValue, StringBuilder csvBuilder) {
metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
- metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, Double.valueOf(metricValue));
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
if (csvBuilder != null) {
csvBuilder.append(type);
@@ -1699,10 +1682,8 @@ public class MiscellaneousCommands implements GfshCommand {
}
private Set<String> createSet(String[] categories) {
- Set<String> categoriesSet = new HashSet<String>();
- for (String category : categories) {
- categoriesSet.add(category);
- }
+ Set<String> categoriesSet = new HashSet<>();
+ Collections.addAll(categoriesSet, categories);
return categoriesSet;
}
@@ -1712,7 +1693,7 @@ public class MiscellaneousCommands implements GfshCommand {
* @return map with categories for system metrics and display flag set to true
*/
private Map<String, Boolean> getSystemMetricsCategories() {
- Map<String, Boolean> categories = new HashMap<String, Boolean>();
+ Map<String, Boolean> categories = new HashMap<>();
categories.put("cluster", true);
categories.put("cache", true);
categories.put("diskstore", true);
@@ -1726,7 +1707,7 @@ public class MiscellaneousCommands implements GfshCommand {
* @return map with categories for region metrics and display flag set to true
*/
private Map<String, Boolean> getRegionMetricsCategories() {
- Map<String, Boolean> categories = new HashMap<String, Boolean>();
+ Map<String, Boolean> categories = new HashMap<>();
categories.put("region", true);
categories.put("partition", true);
@@ -1756,7 +1737,7 @@ public class MiscellaneousCommands implements GfshCommand {
* @return map with categories for member metrics and display flag set to true
*/
private Map<String, Boolean> getMemberMetricsCategories() {
- Map<String, Boolean> categories = new HashMap<String, Boolean>();
+ Map<String, Boolean> categories = new HashMap<>();
categories.put("member", true);
categories.put("jvm", true);
categories.put("region", true);
@@ -1842,7 +1823,7 @@ public class MiscellaneousCommands implements GfshCommand {
InternalCache cache = GemFireCacheImpl.getInstance();
LogWriter logger = cache.getLogger();
- Set<DistributedMember> dsMembers = new HashSet<DistributedMember>();
+ Set<DistributedMember> dsMembers = new HashSet<>();
Set<DistributedMember> ds = CliUtil.getAllMembers(cache);
if (grps != null && grps.length > 0) {
@@ -1853,9 +1834,7 @@ public class MiscellaneousCommands implements GfshCommand {
if (memberIds != null && memberIds.length > 0) {
for (String member : memberIds) {
- Iterator<DistributedMember> it = ds.iterator();
- while (it.hasNext()) {
- DistributedMember mem = it.next();
+ for (DistributedMember mem : ds) {
if (mem.getName() != null
&& (mem.getName().equals(member) || mem.getId().equals(member))) {
dsMembers.add(mem);
@@ -1909,7 +1888,6 @@ public class MiscellaneousCommands implements GfshCommand {
}
} catch (Exception ex) {
LogWrapper.getInstance().warning("change log level command exception " + ex);
- continue;
}
}
@@ -1937,7 +1915,7 @@ public class MiscellaneousCommands implements GfshCommand {
}
private Set<String> getSetDifference(Set<String> set1, Set<String> set2) {
- Set<String> setDifference = new HashSet<String>();
+ Set<String> setDifference = new HashSet<>();
for (String element : set1) {
if (!(set2.contains(element.toLowerCase()))) {
setDifference.add(element);
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
index 9bfd47b..e0bad15 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
@@ -14,6 +14,17 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Arrays;
+import java.util.Collection;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.internal.cache.CacheConfig;
import org.apache.geode.internal.cache.DiskStoreImpl;
import org.apache.geode.internal.cache.xmlcache.CacheCreation;
@@ -32,42 +43,25 @@ import org.apache.geode.pdx.internal.EnumInfo;
import org.apache.geode.pdx.internal.PdxType;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Arrays;
-import java.util.Collection;
public class PDXCommands implements GfshCommand {
@CliCommand(value = CliStrings.CONFIGURE_PDX, help = CliStrings.CONFIGURE_PDX__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
public Result configurePDX(
@CliOption(key = CliStrings.CONFIGURE_PDX__READ__SERIALIZED,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONFIGURE_PDX__READ__SERIALIZED__HELP) Boolean readSerialized,
@CliOption(key = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS__HELP) Boolean ignoreUnreadFields,
- @CliOption(key = CliStrings.CONFIGURE_PDX__DISKSTORE,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, specifiedDefaultValue = "",
+ @CliOption(key = CliStrings.CONFIGURE_PDX__DISKSTORE, specifiedDefaultValue = "",
help = CliStrings.CONFIGURE_PDX__DISKSTORE__HELP) String diskStore,
@CliOption(key = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
- specifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES__HELP) String[] patterns,
@CliOption(key = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
- specifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES__HELP) String[] portablePatterns) {
- Result result = null;
+ Result result;
try {
InfoResultData ird = ResultBuilder.createInfoResultData();
@@ -105,7 +99,7 @@ public class PDXCommands implements GfshCommand {
CliStrings.CONFIGURE_PDX__READ__SERIALIZED + " = " + cache.getPdxReadSerialized());
- // Set ingoreUnreadFields
+ // Set ignoreUnreadFields
if (ignoreUnreadFields != null) {
cache.setPdxIgnoreUnreadFields(ignoreUnreadFields);
} else {
@@ -153,7 +147,6 @@ public class PDXCommands implements GfshCommand {
@CliCommand(value = CliStrings.PDX_RENAME, help = CliStrings.PDX_RENAME__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
public Result pdxRename(@CliOption(key = CliStrings.PDX_RENAME_OLD, mandatory = true,
help = CliStrings.PDX_RENAME_OLD__HELP) String oldClassName,
@@ -191,7 +184,7 @@ public class PDXCommands implements GfshCommand {
}
String resultString =
CliStrings.format(CliStrings.PDX_RENAME__SUCCESS, outputStream.toString());
- return ResultBuilder.createInfoResult(resultString.toString());
+ return ResultBuilder.createInfoResult(resultString);
} catch (Exception e) {
return ResultBuilder.createGemFireErrorResult(
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
index 25b95cd..87c5bbc 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
@@ -14,10 +14,18 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.SystemFailure;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
import org.apache.geode.management.cli.ConverterHint;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.cli.Result.Status;
@@ -28,21 +36,13 @@ import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
import org.apache.geode.management.internal.cli.functions.CreateAsyncEventQueueFunction;
import org.apache.geode.management.internal.cli.functions.ListAsyncEventQueuesFunction;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResultException;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
import org.apache.geode.management.internal.cli.result.TabularResultData;
import org.apache.geode.management.internal.configuration.domain.XmlEntity;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* The QueueCommands class encapsulates all GemFire Queue commands in Gfsh.
@@ -54,12 +54,11 @@ public class QueueCommands implements GfshCommand {
@CliCommand(value = CliStrings.CREATE_ASYNC_EVENT_QUEUE,
help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__HELP)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
public Result createAsyncEventQueue(
@CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, mandatory = true,
help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID__HELP) String id,
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GROUP__HELP) String[] groups,
@CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL,
@@ -78,7 +77,6 @@ public class QueueCommands implements GfshCommand {
unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT__HELP) boolean persistent,
@CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE__HELP) String diskStore,
@CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS,
unspecifiedDefaultValue = "true", specifiedDefaultValue = "true",
@@ -104,17 +102,20 @@ public class QueueCommands implements GfshCommand {
@CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE,
help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE__HELP) String[] listenerParamsAndValues) {
+ if (persistent) {
+ getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
+ }
Properties listenerProperties = new Properties();
try {
if (listenerParamsAndValues != null) {
- for (int i = 0; i < listenerParamsAndValues.length; i++) {
- final int hashPosition = listenerParamsAndValues[i].indexOf('#');
+ for (String listenerParamsAndValue : listenerParamsAndValues) {
+ final int hashPosition = listenerParamsAndValue.indexOf('#');
if (hashPosition == -1) {
- listenerProperties.put(listenerParamsAndValues[i], "");
+ listenerProperties.put(listenerParamsAndValue, "");
} else {
- listenerProperties.put(listenerParamsAndValues[i].substring(0, hashPosition),
- listenerParamsAndValues[i].substring(hashPosition + 1));
+ listenerProperties.put(listenerParamsAndValue.substring(0, hashPosition),
+ listenerParamsAndValue.substring(hashPosition + 1));
}
}
}
@@ -205,17 +206,17 @@ public class QueueCommands implements GfshCommand {
tabularData.setStatus(Status.ERROR);
} else {
AsyncEventQueueDetails[] details = (AsyncEventQueueDetails[]) result.getSerializables();
- for (int i = 0; i < details.length; i++) {
+ for (AsyncEventQueueDetails detail : details) {
tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("ID", details[i].getId());
- tabularData.accumulate("Batch Size", details[i].getBatchSize());
- tabularData.accumulate("Persistent", details[i].isPersistent());
- tabularData.accumulate("Disk Store", details[i].getDiskStoreName());
- tabularData.accumulate("Max Memory", details[i].getMaxQueueMemory());
+ tabularData.accumulate("ID", detail.getId());
+ tabularData.accumulate("Batch Size", detail.getBatchSize());
+ tabularData.accumulate("Persistent", detail.isPersistent());
+ tabularData.accumulate("Disk Store", detail.getDiskStoreName());
+ tabularData.accumulate("Max Memory", detail.getMaxQueueMemory());
- Properties listenerProperties = details[i].getListenerProperties();
+ Properties listenerProperties = detail.getListenerProperties();
if (listenerProperties == null || listenerProperties.size() == 0) {
- tabularData.accumulate("Listener", details[i].getListener());
+ tabularData.accumulate("Listener", detail.getListener());
} else {
StringBuilder propsStringBuilder = new StringBuilder();
propsStringBuilder.append('(');
@@ -232,7 +233,7 @@ public class QueueCommands implements GfshCommand {
propsStringBuilder.append(')');
tabularData.accumulate("Listener",
- details[i].getListener() + propsStringBuilder.toString());
+ detail.getListener() + propsStringBuilder.toString());
}
accumulatedData = true;
}
[6/6] geode git commit: GEODE-2919: Provide finer grained security
Posted by js...@apache.org.
GEODE-2919: Provide finer grained security
- For full details, see https://cwiki.apache.org/confluence/display/GEODE/Finer+grained+security
Project: http://git-wip-us.apache.org/repos/asf/geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/geode/commit/451d12e8
Tree: http://git-wip-us.apache.org/repos/asf/geode/tree/451d12e8
Diff: http://git-wip-us.apache.org/repos/asf/geode/diff/451d12e8
Branch: refs/heads/develop
Commit: 451d12e83c2457c22535ae684995e973ba8d3dd2
Parents: 3ee585c
Author: Patrick Rhomberg <pr...@pivotal.io>
Authored: Wed Jun 21 10:51:32 2017 -0700
Committer: Jared Stewart <js...@pivotal.io>
Committed: Fri Jun 23 15:46:01 2017 -0700
----------------------------------------------------------------------
.../geode/management/CacheServerMXBean.java | 122 ++---
.../geode/management/DiskStoreMXBean.java | 68 +--
.../management/DistributedSystemMXBean.java | 174 +++----
.../geode/management/GatewayReceiverMXBean.java | 75 +--
.../geode/management/GatewaySenderMXBean.java | 88 ++--
.../geode/management/LockServiceMXBean.java | 20 +-
.../apache/geode/management/MemberMXBean.java | 263 +++++-----
.../internal/beans/DistributedSystemMBean.java | 21 +-
.../management/internal/beans/MemberMBean.java | 7 +-
.../internal/beans/MemberMBeanBridge.java | 4 +-
.../internal/cli/commands/ClientCommands.java | 90 ++--
.../CreateAlterDestroyRegionCommands.java | 43 +-
.../internal/cli/commands/DataCommands.java | 64 ++-
.../internal/cli/commands/DeployCommands.java | 34 +-
.../cli/commands/DiskStoreCommands.java | 222 ++++-----
.../cli/commands/DurableClientCommands.java | 90 ++--
.../internal/cli/commands/FunctionCommands.java | 136 ++----
.../internal/cli/commands/GfshCommand.java | 20 +-
.../internal/cli/commands/IndexCommands.java | 138 +++---
.../cli/commands/MiscellaneousCommands.java | 258 +++++-----
.../internal/cli/commands/PDXCommands.java | 39 +-
.../internal/cli/commands/QueueCommands.java | 55 +--
.../internal/cli/commands/RegionCommands.java | 76 ++-
.../internal/cli/commands/WanCommands.java | 219 +++++----
.../commands/lifecycle/StartPulseCommand.java | 18 +-
.../cli/functions/ContinuousQueryFunction.java | 148 ++++++
.../cli/functions/ContunuousQueryFunction.java | 150 ------
.../cli/functions/RegionFunctionArgs.java | 26 +-
.../cli/functions/UserFunctionExecution.java | 42 +-
.../internal/cli/i18n/CliStrings.java | 44 +-
.../internal/cli/remote/CommandProcessor.java | 17 +-
.../internal/security/MBeanServerWrapper.java | 38 +-
.../MemberMBeanAttributesDUnitTest.java | 35 +-
.../bean/stats/MemberLevelStatsJUnitTest.java | 8 +-
.../CreateAlterDestroyRegionCommandsTest.java | 17 +-
...CacheServerMBeanAuthenticationJUnitTest.java | 20 +-
.../CacheServerMBeanAuthorizationJUnitTest.java | 42 +-
...eServerMBeanWithShiroIniIntegrationTest.java | 15 +-
.../security/CliCommandsSecurityTest.java | 34 +-
.../security/DataCommandsSecurityTest.java | 13 +-
.../security/DeployCommandsSecurityTest.java | 28 +-
.../DiskStoreMXBeanSecurityJUnitTest.java | 98 ++--
.../DistributedSystemMXBeanSecurityTest.java | 77 +++
.../GatewayReceiverMBeanSecurityTest.java | 42 +-
.../GatewaySenderMBeanSecurityTest.java | 68 +--
.../security/GfshCommandsPostProcessorTest.java | 28 +-
.../security/GfshCommandsSecurityTest.java | 76 +--
.../LockServiceMBeanAuthorizationJUnitTest.java | 73 ++-
.../security/MBeanSecurityJUnitTest.java | 30 +-
.../ManagerMBeanAuthorizationJUnitTest.java | 30 +-
.../security/MemberMBeanSecurityJUnitTest.java | 51 +-
.../internal/security/MultiUserDUnitTest.java | 102 ++--
.../security/ResourcePermissionTest.java | 13 +-
.../internal/security/TestCommand.java | 157 +++---
.../dunit/rules/LocatorServerStartupRule.java | 19 +-
.../test/dunit/rules/MemberStarterRule.java | 6 +
.../codeAnalysis/sanctionedSerializables.txt | 4 +-
.../cli/commands/ClientCommandsDUnitTest.java | 478 ++++++++++---------
.../internal/cli/LuceneIndexCommands.java | 58 ++-
.../lucene/internal/cli/LuceneIndexInfo.java | 10 -
.../functions/LuceneCreateIndexFunction.java | 14 +-
.../lucene/LuceneCommandsSecurityDUnitTest.java | 126 +++--
.../GfshCommandsOverHttpSecurityTest.java | 4 +-
63 files changed, 2342 insertions(+), 2243 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/CacheServerMXBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/CacheServerMXBean.java b/geode-core/src/main/java/org/apache/geode/management/CacheServerMXBean.java
index 3adbf01..d0159f0 100644
--- a/geode-core/src/main/java/org/apache/geode/management/CacheServerMXBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/CacheServerMXBean.java
@@ -18,12 +18,13 @@ import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* MBean that provides access to information and management functionality for a {@link CacheServer}.
*
* <p>
- * The will be one CacheServermBean per {@link CacheServer} started in GemFire node.
+ * The will be one CacheServerMBean per {@link CacheServer} started in GemFire node.
*
* <p>
* ObjectName for this MBean is GemFire:service=CacheServer,port={0},type=Member,member={1}
@@ -60,48 +61,48 @@ public interface CacheServerMXBean {
/**
* Returns the port on which this CacheServer listens for clients.
*/
- public int getPort();
+ int getPort();
/**
* Returns a string representing the IP address or host name that this CacheServer will listen on.
*/
- public String getBindAddress();
+ String getBindAddress();
/**
* Returns the configured buffer size of the socket connection for this CacheServer.
*/
- public int getSocketBufferSize();
+ int getSocketBufferSize();
/**
* Returns the maximum amount of time between client pings. This value is used to determine the
* health of client's attached to the server.
*/
- public int getMaximumTimeBetweenPings();
+ int getMaximumTimeBetweenPings();
/**
* Returns the maximum allowed client connections.
*/
- public int getMaxConnections();
+ int getMaxConnections();
/**
- * Returns the maxium number of threads allowed in this CacheServer to service client requests.
+ * Returns the maximum number of threads allowed in this CacheServer to service client requests.
*/
- public int getMaxThreads();
+ int getMaxThreads();
/**
* Returns the maximum number of messages that can be enqueued in a client-queue.
*/
- public int getMaximumMessageCount();
+ int getMaximumMessageCount();
/**
* Returns the time (in seconds) after which a message in the client queue will expire.
*/
- public int getMessageTimeToLive();
+ int getMessageTimeToLive();
/**
* Returns the frequency (in milliseconds) to poll the load probe on this CacheServer.
*/
- public long getLoadPollInterval();
+ long getLoadPollInterval();
/**
* Returns the name or IP address to pass to the client as the location where the server is
@@ -111,164 +112,164 @@ public interface CacheServerMXBean {
* and won’t be able to find the server. For this situation, you must supply the server’s
* alternate hostname for the locator to pass to the client.
*/
- public String getHostNameForClients();
+ String getHostNameForClients();
/**
* Returns the load probe for this CacheServer.
*/
- public ServerLoadData fetchLoadProbe();
+ ServerLoadData fetchLoadProbe();
/**
* Returns whether or not this CacheServer is running.
*
* @return True of the server is running, false otherwise.
*/
- public boolean isRunning();
+ boolean isRunning();
/**
* Returns the capacity (in megabytes) of the client queue.
*/
- public int getCapacity();
+ int getCapacity();
/**
* Returns the eviction policy that is executed when the capacity of the client queue is reached.
*/
- public String getEvictionPolicy();
+ String getEvictionPolicy();
/**
* Returns the name of the disk store that is used for persistence.
*/
- public String getDiskStoreName();
+ String getDiskStoreName();
/**
* Returns the number of sockets accepted and used for client to server messaging.
*/
- public int getClientConnectionCount();
+ int getClientConnectionCount();
/**
* Returns the number of client virtual machines connected.
*/
- public int getCurrentClients();
+ int getCurrentClients();
/**
* Returns the average get request latency.
*/
- public long getGetRequestAvgLatency();
+ long getGetRequestAvgLatency();
/**
* Returns the average put request latency.
*/
- public long getPutRequestAvgLatency();
+ long getPutRequestAvgLatency();
/**
* Returns the total number of client connections that timed out and were closed.
*/
- public int getTotalConnectionsTimedOut();
+ int getTotalConnectionsTimedOut();
/**
* Returns the total number of client connection requests that failed.
*/
- public int getTotalFailedConnectionAttempts();
+ int getTotalFailedConnectionAttempts();
/**
* Returns the current number of connections waiting for a thread to start processing their
* message.
*/
- public int getThreadQueueSize();
+ int getThreadQueueSize();
/**
* Returns the current number of threads handling a client connection.
*/
- public int getConnectionThreads();
+ int getConnectionThreads();
/**
* Returns the load from client to server connections as reported by the load probe installed in
* this server.
*/
- public double getConnectionLoad();
+ double getConnectionLoad();
/**
* Returns the estimate of how much load is added for each new connection as reported by the load
* probe installed in this server.
*/
- public double getLoadPerConnection();
+ double getLoadPerConnection();
/**
* Returns the load from queues as reported by the load probe installed in this server.
*/
- public double getQueueLoad();
+ double getQueueLoad();
/**
* Returns the estimate of how much load is added for each new queue as reported by the load probe
* installed in this server.
*/
- public double getLoadPerQueue();
+ double getLoadPerQueue();
/**
* Returns the rate of get requests.
*/
- public float getGetRequestRate();
+ float getGetRequestRate();
/**
* Returns the rate of put requests.
*/
- public float getPutRequestRate();
+ float getPutRequestRate();
/**
* Returns the total number of bytes sent to clients.
*/
- public long getTotalSentBytes();
+ long getTotalSentBytes();
/**
* Returns the total number of bytes received from clients.
*/
- public long getTotalReceivedBytes();
+ long getTotalReceivedBytes();
/**
* Returns the number of cache client notification requests.
*/
- public int getNumClientNotificationRequests();
+ int getNumClientNotificationRequests();
/**
* Returns the average latency for processing client notifications.
*/
- public long getClientNotificationAvgLatency();
+ long getClientNotificationAvgLatency();
/**
* Returns the rate of client notifications.
*/
- public float getClientNotificationRate();
+ float getClientNotificationRate();
/**
* Returns the number of registered CQs.
*/
- public long getRegisteredCQCount();
+ long getRegisteredCQCount();
/**
* Returns the number of active (currently executing) CQs.
*/
- public long getActiveCQCount();
+ long getActiveCQCount();
/**
* Returns the rate of queries.
*/
- public float getQueryRequestRate();
+ float getQueryRequestRate();
/**
* Returns the total number of indexes in use by the member.
*/
- public int getIndexCount();
+ int getIndexCount();
/**
* Returns a list of names for all indexes.
*/
- public String[] getIndexList();
+ String[] getIndexList();
/**
* Returns the total time spent updating indexes due to changes in the data.
*/
- public long getTotalIndexMaintenanceTime();
+ long getTotalIndexMaintenanceTime();
/**
* Remove an index.
@@ -276,12 +277,12 @@ public interface CacheServerMXBean {
* @param indexName Name of the index to be removed.
*/
@ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void removeIndex(String indexName) throws Exception;
+ void removeIndex(String indexName) throws Exception;
/**
* Returns a list of names for all registered CQs.
*/
- public String[] getContinuousQueryList();
+ String[] getContinuousQueryList();
/**
* Execute an ad-hoc CQ on the server
@@ -293,7 +294,7 @@ public interface CacheServerMXBean {
*/
@Deprecated
@ResourceOperation(resource = Resource.DATA, operation = Operation.READ)
- public void executeContinuousQuery(String queryName) throws Exception;
+ void executeContinuousQuery(String queryName) throws Exception;
/**
* Stop (pause) a CQ from executing
@@ -305,8 +306,9 @@ public interface CacheServerMXBean {
* methods to modify a CQ.
*/
@Deprecated
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void stopContinuousQuery(String queryName) throws Exception;
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ void stopContinuousQuery(String queryName) throws Exception;
/**
* Unregister all CQs from a region
@@ -317,8 +319,9 @@ public interface CacheServerMXBean {
* methods to modify a CQ.
*/
@Deprecated
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void closeAllContinuousQuery(String regionName) throws Exception;
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ void closeAllContinuousQuery(String regionName) throws Exception;
/**
@@ -330,8 +333,9 @@ public interface CacheServerMXBean {
* methods to modify a CQ.
*/
@Deprecated
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void closeContinuousQuery(String queryName) throws Exception;
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ void closeContinuousQuery(String queryName) throws Exception;
/**
@@ -339,7 +343,7 @@ public interface CacheServerMXBean {
*
* @return A list of IDs or a length 0 array if no clients are registered.
*/
- public String[] getClientIds() throws Exception;
+ String[] getClientIds() throws Exception;
/**
* Returns health and statistic information for the give client id. Some of the information (CPUs,
@@ -348,44 +352,44 @@ public interface CacheServerMXBean {
*
* @param clientId ID of the client for which to retrieve information.
*/
- public ClientHealthStatus showClientStats(String clientId) throws Exception;
+ ClientHealthStatus showClientStats(String clientId) throws Exception;
/**
* Returns the number of clients who have existing subscriptions.
*/
- public int getNumSubscriptions();
+ int getNumSubscriptions();
/**
* Returns health and statistic information for all clients. Some of the information (CPUs,
* NumOfCacheListenerCalls, NumOfGets,NumOfMisses, NumOfPuts,NumOfThreads, ProcessCpuTime) only
* available for clients which have set a "StatisticsInterval".
*/
- public ClientHealthStatus[] showAllClientStats() throws Exception;
+ ClientHealthStatus[] showAllClientStats() throws Exception;
/**
* Shows a list of client with their queue statistics. Client queue statistics shown in this
* method are the following
*
- * eventsEnqued,eventsRemoved , eventsConflated ,markerEventsConflated , eventsExpired,
+ * eventsEnqueued,eventsRemoved , eventsConflated ,markerEventsConflated , eventsExpired,
* eventsRemovedByQrm , eventsTaken , numVoidRemovals
*
* @return an array of ClientQueueDetail
* @throws Exception
*/
- public ClientQueueDetail[] showClientQueueDetails() throws Exception;
+ ClientQueueDetail[] showClientQueueDetails() throws Exception;
/**
*
* Shows queue statistics of the given client. Client queue statistics shown in this method are
* the following
*
- * eventsEnqued,eventsRemoved , eventsConflated ,markerEventsConflated , eventsExpired,
+ * eventsEnqueued,eventsRemoved , eventsConflated ,markerEventsConflated , eventsExpired,
* eventsRemovedByQrm , eventsTaken , numVoidRemovals
*
* @param clientId the ID of client which is returned by the attribute ClientIds
* @return ClientQueueDetail
* @throws Exception
*/
- public ClientQueueDetail showClientQueueDetails(String clientId) throws Exception;
+ ClientQueueDetail showClientQueueDetails(String clientId) throws Exception;
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/DiskStoreMXBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/DiskStoreMXBean.java b/geode-core/src/main/java/org/apache/geode/management/DiskStoreMXBean.java
index cca6272..6275df5 100644
--- a/geode-core/src/main/java/org/apache/geode/management/DiskStoreMXBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/DiskStoreMXBean.java
@@ -18,6 +18,7 @@ import org.apache.geode.cache.DiskStore;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* MBean that provides access to information and management functionality for a {@link DiskStore}.
@@ -31,58 +32,58 @@ public interface DiskStoreMXBean {
/**
* Returns the name of the DiskStore.
*/
- public String getName();
+ String getName();
/**
* Returns whether disk files are to be automatically compacted.
*
* @return True if disk files are automatically compacted, false otherwise
*/
- public boolean isAutoCompact();
+ boolean isAutoCompact();
/**
* Returns the threshold at which an op-log may be compacted. Until it reaches this threshold the
* op-log will not be compacted. The threshold is a percentage in the range 0..100.
*/
- public int getCompactionThreshold();
+ int getCompactionThreshold();
/**
* Returns whether manual compaction of disk files is allowed.
*
* @return True if manual compaction is allowed, false otherwise.
*/
- public boolean isForceCompactionAllowed();
+ boolean isForceCompactionAllowed();
/**
* Returns the maximum size (in megabytes) that a single op-log can grow to.
*/
- public long getMaxOpLogSize();
+ long getMaxOpLogSize();
/**
* Returns the time (in milliseconds) that can elapse before unwritten data is saved to disk.
*/
- public long getTimeInterval();
+ long getTimeInterval();
/**
* Returns the size of the write buffer that this DiskStore will use when writing data to disk.
*/
- public int getWriteBufferSize();
+ int getWriteBufferSize();
/**
* Returns the path of the directories to which the region's data will be written.
*/
- public String[] getDiskDirectories();
+ String[] getDiskDirectories();
/**
* Returns the maximum number of operations that can be asynchronously queued for saving to disk.
* When this limit is reached operations will block until they can be put in the queue.
*/
- public int getQueueSize();
+ int getQueueSize();
/**
* Returns the total number of bytes of space this DiskStore has used.
*/
- public long getTotalBytesOnDisk();
+ long getTotalBytesOnDisk();
/**
* Returns the average latency of disk reads in nanoseconds Its the average latency required to
@@ -92,7 +93,7 @@ public interface DiskStoreMXBean {
* So this rate won't match the number of bytes put in all regions.This is rate of actual bytes
* system is persisting.
*/
- public float getDiskReadsRate();
+ float getDiskReadsRate();
/**
* Returns the average latency of disk writes in nanoseconds. Its the average latency required to
@@ -102,44 +103,44 @@ public interface DiskStoreMXBean {
* So this rate won't match the number of bytes put in all regions. This is rate of actual bytes
* system is persisting.
*/
- public float getDiskWritesRate();
+ float getDiskWritesRate();
/**
* Returns the disk reads average latency in nanoseconds. It depicts average time needed to read
* one byte of data from disk.
*/
- public long getDiskReadsAvgLatency();
+ long getDiskReadsAvgLatency();
/**
* Returns the disk writes average latency in nanoseconds. It depicts average time needed to write
* one byte of data to disk.
*/
- public long getDiskWritesAvgLatency();
+ long getDiskWritesAvgLatency();
/**
* Returns the flush time average latency.
*/
- public long getFlushTimeAvgLatency();
+ long getFlushTimeAvgLatency();
/**
* Returns the number of entries in the asynchronous queue waiting to be written to disk.
*/
- public int getTotalQueueSize();
+ int getTotalQueueSize();
/**
* Returns the number of backups currently in progress on this DiskStore.
*/
- public int getTotalBackupInProgress();
+ int getTotalBackupInProgress();
/**
* Returns the number of backups of this DiskStore that have been completed.
*/
- public int getTotalBackupCompleted();
+ int getTotalBackupCompleted();
/**
* Returns the number of persistent regions currently being recovered from disk.
*/
- public int getTotalRecoveriesInProgress();
+ int getTotalRecoveriesInProgress();
/**
* Requests the DiskStore to start writing to a new op-log. The old oplog will be asynchronously
@@ -149,8 +150,9 @@ public interface DiskStoreMXBean {
* compaction is true then the application will wait for the other op-logs to be compacted and
* additional space is available.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void forceRoll();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ void forceRoll();
/**
* Requests the DiskStore to start compacting. The compaction is done even if automatic compaction
@@ -161,15 +163,17 @@ public interface DiskStoreMXBean {
* @return True if one or more op-logs were compacted or false to indicate that no op-logs were
* ready to be compacted or that a compaction was already in progress.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public boolean forceCompaction();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ boolean forceCompaction();
/**
* Causes any data that is currently in the asynchronous queue to be written to disk. Does not
* return until the flush is complete.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void flush();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ void flush();
/**
* Returns the warning threshold for disk usage as a percentage of the total disk volume.
@@ -177,7 +181,7 @@ public interface DiskStoreMXBean {
* @return the warning percent
* @since GemFire 8.0
*/
- public float getDiskUsageWarningPercentage();
+ float getDiskUsageWarningPercentage();
/**
* Returns the critical threshold for disk usage as a percentage of the total disk volume.
@@ -185,21 +189,23 @@ public interface DiskStoreMXBean {
* @return the critical percent
* @since GemFire 8.0
*/
- public float getDiskUsageCriticalPercentage();
+ float getDiskUsageCriticalPercentage();
/**
* Sets the value of the disk usage warning percentage.
*
* @param warningPercent the warning percent
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void setDiskUsageWarningPercentage(float warningPercent);
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ void setDiskUsageWarningPercentage(float warningPercent);
/**
* Sets the value of the disk usage critical percentage.
*
* @param criticalPercent the critical percent
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void setDiskUsageCriticalPercentage(float criticalPercent);
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ void setDiskUsageCriticalPercentage(float criticalPercent);
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/DistributedSystemMXBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/DistributedSystemMXBean.java b/geode-core/src/main/java/org/apache/geode/management/DistributedSystemMXBean.java
index f6f701e..3d52115 100644
--- a/geode-core/src/main/java/org/apache/geode/management/DistributedSystemMXBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/DistributedSystemMXBean.java
@@ -15,6 +15,7 @@
package org.apache.geode.management;
import java.util.Map;
+
import javax.management.ObjectName;
import org.apache.geode.cache.DiskStore;
@@ -24,6 +25,7 @@ import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* MBean that provides access to information and management operations for a
@@ -76,22 +78,22 @@ import org.apache.geode.security.ResourcePermission.Resource;
public interface DistributedSystemMXBean {
/**
- * Returns the ID of thie DistributedSystem. allow anyone to access this method
+ * Returns the ID of the DistributedSystem. allow anyone to access this method
*
* @return The DistributedSystem ID or -1 if not set.
*/
@ResourceOperation()
- public int getDistributedSystemId();
+ int getDistributedSystemId();
/**
* Returns the number of members in the distributed system.
*/
- public int getMemberCount();
+ int getMemberCount();
/**
* Returns a list of names for all members.
*/
- public String[] listMembers();
+ String[] listMembers();
/**
* Returns a list of names for locator members.
@@ -101,49 +103,49 @@ public interface DistributedSystemMXBean {
* @return a list of names for locator members.
*/
- public String[] listLocatorMembers(boolean onlyStandAloneLocators);
+ String[] listLocatorMembers(boolean onlyStandAloneLocators);
/**
* Returns a list of names for all groups.
*/
- public String[] listGroups();
+ String[] listGroups();
/**
* Returns the number of locators in the distributed system.
*/
- public int getLocatorCount();
+ int getLocatorCount();
/**
* Returns a list of IDs for all locators.
*/
- public String[] listLocators(); // TODO - Abhishek Should be renamed to
- // listLocatorDiscoveryConfigurations? Do we need something for
- // mcast too?
+ String[] listLocators(); // TODO - Abhishek Should be renamed to
+ // listLocatorDiscoveryConfigurations? Do we need something for
+ // mcast too?
/**
* Returns the number of disks stores in the distributed system.
*/
- public int getSystemDiskStoreCount();
+ int getSystemDiskStoreCount();
/**
* Returns a map of all {@link DistributedMember}s and their {@link DiskStore}s.
*/
- public Map<String, String[]> listMemberDiskstore();
+ Map<String, String[]> listMemberDiskstore();
/**
* Returns a list of IDs for all gateway senders.
*/
- public String[] listGatewaySenders();
+ String[] listGatewaySenders();
/**
* Returns a list of IDs for all gateway receivers.
*/
- public String[] listGatewayReceivers();
+ String[] listGatewayReceivers();
/**
* Returns the minimum level set for alerts to be delivered to listeners.
*/
- public String getAlertLevel();
+ String getAlertLevel();
/**
* Sets the minimum level for alerts to be delivered to listeners.
@@ -152,74 +154,74 @@ public interface DistributedSystemMXBean {
* SEVERE or NONE.
*/
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.WRITE)
- public void changeAlertLevel(String alertLevel) throws Exception;
+ void changeAlertLevel(String alertLevel) throws Exception;
/**
* Returns the total available heap (in megabytes) across all distributed members.
*/
- public long getTotalHeapSize();
+ long getTotalHeapSize();
/**
* Returns the total number of entries in all regions.
*/
- public long getTotalRegionEntryCount();
+ long getTotalRegionEntryCount();
/**
* Returns the number of {@link Region}s.
*/
- public int getTotalRegionCount();
+ int getTotalRegionCount();
/**
* Returns the number of times that a cache miss occurred for all regions.
*/
- public int getTotalMissCount();
+ int getTotalMissCount();
/**
* Returns the number of times that a hit occurred for all regions.
*/
- public int getTotalHitCount();
+ int getTotalHitCount();
/**
* Returns the number of connected clients.
*/
- public int getNumClients();
+ int getNumClients();
/**
* Returns the average number of disk reads per second across all distributed members.
*/
- public float getDiskReadsRate();
+ float getDiskReadsRate();
/**
* Returns the average number of disk writes per second across all distributed members.
*/
- public float getDiskWritesRate();
+ float getDiskWritesRate();
/**
* Returns the average disk flush latency time.
*/
- public long getDiskFlushAvgLatency();
+ long getDiskFlushAvgLatency();
/**
* Returns the number of backups currently in progress for all disk stores.
*/
- public int getTotalBackupInProgress();
+ int getTotalBackupInProgress();
/**
* Returns the number of initial images in progress.
*/
- public int getNumInitialImagesInProgress();
+ int getNumInitialImagesInProgress();
/**
* Returns the number of active (currently executing) CQs for all cache servers.
*/
- public long getActiveCQCount();
+ long getActiveCQCount();
/**
* Returns the average number of queries per second across all distributed members.
*/
- public float getQueryRequestRate();
+ float getQueryRequestRate();
/**
* Performs a backup on all members.
@@ -229,8 +231,7 @@ public interface DistributedSystemMXBean {
* @return The results of the backup request.
*/
@ResourceOperation(resource = Resource.DATA, operation = Operation.READ)
- public DiskBackupStatus backupAllMembers(String targetDirPath, String baselineDirPath)
- throws Exception;
+ DiskBackupStatus backupAllMembers(String targetDirPath, String baselineDirPath) throws Exception;
/**
* Returns the configuration information for a distributed member.
@@ -239,7 +240,7 @@ public interface DistributedSystemMXBean {
* @return The configuration information for a member.
* @throws Exception for an invalid member ID.
*/
- public GemFireProperties fetchMemberConfiguration(String member) throws Exception;
+ GemFireProperties fetchMemberConfiguration(String member) throws Exception;
/**
* Returns the total time (in seconds) since a distributed member was started.
@@ -248,21 +249,21 @@ public interface DistributedSystemMXBean {
* @return The total time (in seconds) since a member was started.
* @throws Exception for an invalid member ID.
*/
- public long fetchMemberUpTime(String member) throws Exception;
+ long fetchMemberUpTime(String member) throws Exception;
/**
* Returns a list of names for all cache servers which are able to serve requests from GemFire
* clients.
*
*/
- public String[] listCacheServers();
+ String[] listCacheServers();
/**
* Returns a list of names for all servers where server means any long-running GemFire process
* that was started with "start server" command from GFSH.
*/
- public String[] listServers();
+ String[] listServers();
/**
* Returns JVM metrics for a distributed member.
@@ -270,7 +271,7 @@ public interface DistributedSystemMXBean {
* @param member Name or ID of the member.
* @throws Exception for an invalid member ID.
*/
- public JVMMetrics showJVMMetrics(String member) throws Exception;
+ JVMMetrics showJVMMetrics(String member) throws Exception;
/**
* Returns operating system metrics for a distributed member.
@@ -278,7 +279,7 @@ public interface DistributedSystemMXBean {
* @param member Name or ID of the member.
* @throws Exception for an invalid member ID.
*/
- public OSMetrics showOSMetrics(String member) throws Exception;
+ OSMetrics showOSMetrics(String member) throws Exception;
/**
* Returns network metrics for a distributed member.
@@ -286,7 +287,7 @@ public interface DistributedSystemMXBean {
* @param member Name or ID of the member.
* @throws Exception for an invalid member ID.
*/
- public NetworkMetrics showNetworkMetric(String member) throws Exception;
+ NetworkMetrics showNetworkMetric(String member) throws Exception;
/**
* Returns disk metrics for a distributed member.
@@ -294,7 +295,7 @@ public interface DistributedSystemMXBean {
* @param member Name or ID of the member.
* @throws Exception for an invalid member ID.
*/
- public DiskMetrics showDiskMetrics(String member) throws Exception;
+ DiskMetrics showDiskMetrics(String member) throws Exception;
/**
* Shuts down all members of a distributed system except for the managing member.
@@ -302,17 +303,17 @@ public interface DistributedSystemMXBean {
* @return List of names of all distributed members that were shutdown.
*/
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
- public String[] shutDownAllMembers() throws Exception;
+ String[] shutDownAllMembers() throws Exception;
/**
* Returns a list of names for all regions.
*/
- public String[] listRegions();
+ String[] listRegions();
/**
* Returns a list of full paths for all regions.
*/
- public String[] listAllRegionPaths();
+ String[] listAllRegionPaths();
/**
* Removes a disk store from the distributed system.
@@ -320,40 +321,41 @@ public interface DistributedSystemMXBean {
* @param diskStoreId UUID of the disk store to remove
* @return True if the request is successful, false otherwise.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public boolean revokeMissingDiskStores(String diskStoreId) throws Exception;
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ boolean revokeMissingDiskStores(String diskStoreId);
/**
* Returns a list of details for disk stores which have been determined to be unavailable during
* the recovery of region.
*/
- public PersistentMemberDetails[] listMissingDiskStores();
+ PersistentMemberDetails[] listMissingDiskStores();
/**
* Returns the object name for a {@link MemberMXBean} used to access this distributed member.
* allow anyone to access this method
*/
@ResourceOperation()
- public ObjectName getMemberObjectName();
+ ObjectName getMemberObjectName();
/**
* Returns the object name for a {@link ManagerMXBean} used to access the management service
* running on this distributed member.
*/
- public ObjectName getManagerObjectName();
+ ObjectName getManagerObjectName();
/**
* Returns a list of object names for the {@link MemberMXBean}s used to access all distributed
* members.
*/
- public ObjectName[] listMemberObjectNames();
+ ObjectName[] listMemberObjectNames();
/**
* Returns the object name for a {@link MemberMXBean} used to access a distributed member..
*
* @param member Name or ID of the member.
*/
- public ObjectName fetchMemberObjectName(String member) throws Exception;
+ ObjectName fetchMemberObjectName(String member) throws Exception;
/**
* Returns a list of object names for the {@link RegionMXBean}s used to access all regions on a
@@ -361,7 +363,7 @@ public interface DistributedSystemMXBean {
*
* @param memberMBeanName ObjectName of the member.
*/
- public ObjectName[] fetchRegionObjectNames(ObjectName memberMBeanName) throws Exception;
+ ObjectName[] fetchRegionObjectNames(ObjectName memberMBeanName) throws Exception;
/**
* Returns a list of object names for the {@link DistributedRegionMXBean}s used to access all
@@ -369,7 +371,7 @@ public interface DistributedSystemMXBean {
*
* @return An array of object names or an empty array if no distributed regions are found.
*/
- public ObjectName[] listDistributedRegionObjectNames();
+ ObjectName[] listDistributedRegionObjectNames();
/**
* Returns the object name for a {@link DistributedRegionMXBean} used to access a distributed
@@ -377,7 +379,7 @@ public interface DistributedSystemMXBean {
*
* @param regionPath Full path of the region.
*/
- public ObjectName fetchDistributedRegionObjectName(String regionPath) throws Exception;
+ ObjectName fetchDistributedRegionObjectName(String regionPath) throws Exception;
/**
* Returns the object name for a {@link RegionMXBean} used to access a region.
@@ -385,7 +387,7 @@ public interface DistributedSystemMXBean {
* @param member Name or ID of the member.
* @param regionPath Full path of the region.
*/
- public ObjectName fetchRegionObjectName(String member, String regionPath) throws Exception;
+ ObjectName fetchRegionObjectName(String member, String regionPath) throws Exception;
/**
* Returns the object name for a {@link GatewaySenderMXBean} used to access a gateway sender.
@@ -393,14 +395,14 @@ public interface DistributedSystemMXBean {
* @param member Name or ID of the member.
* @param senderId ID of a gateway sender.
*/
- public ObjectName fetchGatewaySenderObjectName(String member, String senderId) throws Exception;
+ ObjectName fetchGatewaySenderObjectName(String member, String senderId) throws Exception;
/**
* Returns the object name for a {@link GatewayReceiverMXBean} used to access a gateway receiver.
*
* @param member Name or ID of the member.
*/
- public ObjectName fetchGatewayReceiverObjectName(String member) throws Exception;
+ ObjectName fetchGatewayReceiverObjectName(String member) throws Exception;
/**
* Returns a list of object names for the {@link GatewaySenderMXBean}s used to access all gateway
@@ -408,7 +410,7 @@ public interface DistributedSystemMXBean {
*
* @return An array of object names or an empty array if no gateway senders are found.
*/
- public ObjectName[] listGatewaySenderObjectNames();
+ ObjectName[] listGatewaySenderObjectNames();
/**
* Returns a list of object names for the {@link GatewaySenderMXBean}s used to access all gateway
@@ -416,7 +418,7 @@ public interface DistributedSystemMXBean {
*
* @param member Name or ID of the member.
*/
- public ObjectName[] listGatewaySenderObjectNames(String member) throws Exception;
+ ObjectName[] listGatewaySenderObjectNames(String member) throws Exception;
/**
* Returns a list of object names for the {@link GatewayReceiverMXBean}s used to access all
@@ -424,7 +426,7 @@ public interface DistributedSystemMXBean {
*
* @return An array of object names or an empty array if no gateway receivers are found.
*/
- public ObjectName[] listGatewayReceiverObjectNames();
+ ObjectName[] listGatewayReceiverObjectNames();
/**
* Returns the object name for a {@link DistributedLockServiceMXBean} used to access a distributed
@@ -432,7 +434,7 @@ public interface DistributedSystemMXBean {
*
* @param lockServiceName Name of the lock service.
*/
- public ObjectName fetchDistributedLockServiceObjectName(String lockServiceName) throws Exception;
+ ObjectName fetchDistributedLockServiceObjectName(String lockServiceName) throws Exception;
/**
* Returns the object name for a {@link LockServiceMXBean} used to access a lock service.
@@ -440,7 +442,7 @@ public interface DistributedSystemMXBean {
* @param member Name or Id of the member.
* @param lockService Name of the lock service.
*/
- public ObjectName fetchLockServiceObjectName(String member, String lockService) throws Exception;
+ ObjectName fetchLockServiceObjectName(String member, String lockService) throws Exception;
/**
* Returns object name of a {@link DiskStoreMXBean} for a given name and member
@@ -450,7 +452,7 @@ public interface DistributedSystemMXBean {
* @return a ObjectName
* @throws Exception
*/
- public ObjectName fetchDiskStoreObjectName(String member, String diskStoreName) throws Exception;
+ ObjectName fetchDiskStoreObjectName(String member, String diskStoreName) throws Exception;
/**
* Returns the object name for a {@link CacheServerMXBean} used to access a cache server.
@@ -458,70 +460,70 @@ public interface DistributedSystemMXBean {
* @param member Name or ID of the member.
* @param port Port of the server.
*/
- public ObjectName fetchCacheServerObjectName(String member, int port) throws Exception;
+ ObjectName fetchCacheServerObjectName(String member, int port) throws Exception;
/**
* Returns a list of object names for the {@link CacheServerMXBean}s used to access all cache
* servers.
*/
- public ObjectName[] listCacheServerObjectNames();
+ ObjectName[] listCacheServerObjectNames();
/**
* Returns the number of map-reduce jobs currently running on all members in the distributed
* system.
*/
- public int getNumRunningFunctions();
+ int getNumRunningFunctions();
/**
* Returns the number of CQs registers on all members.
*/
- public long getRegisteredCQCount();
+ long getRegisteredCQCount();
/**
* Returns the number of bytes used on all disks.
*/
- public long getTotalDiskUsage();
+ long getTotalDiskUsage();
/**
* Returns the total heap used on all members.
*/
- public long getUsedHeapSize();
+ long getUsedHeapSize();
/**
* Returns the average number of reads per second for all members.
*/
- public float getAverageReads();
+ float getAverageReads();
/**
* Returns the average writes per second, including both put and putAll operations, for all
* members.
*/
- public float getAverageWrites();
+ float getAverageWrites();
/**
* Returns the number of subscriptions for all members.
*/
- public int getNumSubscriptions();
+ int getNumSubscriptions();
/**
* Returns the number of garbage collection operations for all members.
*/
- public long getGarbageCollectionCount();
+ long getGarbageCollectionCount();
/**
* Returns a map of remote distributed system IDs and the current connection status for each.
*/
- public Map<String, Boolean> viewRemoteClusterStatus();
+ Map<String, Boolean> viewRemoteClusterStatus();
/**
* Returns the number JVM pauses (which may or may not include full garbage collection pauses)
* detected by GemFire.
*/
- public long getJVMPauses();
+ long getJVMPauses();
/**
- * This API is used to query data from GemFire system. This returns a JSON formated String having
+ * This API is used to query data from GemFire system. This returns a JSON formatted String having
* data and it's type. Type and value of data makes an array , type preceding the value.
*
* e.g. {"result":[["java.lang.String","v"],["java.lang.String","b"]]}
@@ -548,10 +550,10 @@ public interface DistributedSystemMXBean {
* mandatory to give this input barring join queries on PR. If member list is not provided
* query will be for the whole cluster.
* @param limit result set limit. If not set or 0 is passed default limit of 1000 will be set.
- * @return a JSON formated string containing data and its type
+ * @return a JSON formatted string containing data and its type
*/
@ResourceOperation(resource = Resource.DATA, operation = Operation.READ)
- public String queryData(String queryString, String members, int limit) throws Exception;
+ String queryData(String queryString, String members, int limit) throws Exception;
/**
*
@@ -575,7 +577,7 @@ public interface DistributedSystemMXBean {
* @return a byte[] which is a compressed JSON string.
*/
@ResourceOperation(resource = Resource.DATA, operation = Operation.READ)
- public byte[] queryDataForCompressedResult(String queryString, String members, int limit)
+ byte[] queryDataForCompressedResult(String queryString, String members, int limit)
throws Exception;
@@ -583,31 +585,33 @@ public interface DistributedSystemMXBean {
* Returns the number of committed transactions across all members. It gives point in time value
* i.e. Number of tx committed at the time of reading this value
*/
- public int getTransactionCommitted();
+ int getTransactionCommitted();
/**
* Returns the number of transactions that were rolled back across all members. It gives point in
* time value i.e. Number of tx rolled back at the time of reading this value
*/
- public int getTransactionRolledBack();
+ int getTransactionRolledBack();
/**
* Number of rows DistributedSystemMXBean.queryData() operation will return. By default it will be
* 1000. User can modify this to control number of rows to be shown on Pulse, as Pulse DataBrowser
* internally uses DistributedSystemMXBean.queryData()
*/
- public int getQueryResultSetLimit();
+ int getQueryResultSetLimit();
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void setQueryResultSetLimit(int queryResultSetLimit);
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ void setQueryResultSetLimit(int queryResultSetLimit);
/**
* Number of elements in a collection to be shown in queryData operation if query results contain
* collections like Map, List etc.
*
*/
- public int getQueryCollectionsDepth();
+ int getQueryCollectionsDepth();
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void setQueryCollectionsDepth(int queryCollectionsDepth);
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ void setQueryCollectionsDepth(int queryCollectionsDepth);
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/GatewayReceiverMXBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/GatewayReceiverMXBean.java b/geode-core/src/main/java/org/apache/geode/management/GatewayReceiverMXBean.java
index 749a743..556bd6f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/GatewayReceiverMXBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/GatewayReceiverMXBean.java
@@ -18,6 +18,7 @@ import org.apache.geode.cache.wan.GatewayReceiver;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* MBean that provides access to information and management functionality for a
@@ -32,180 +33,182 @@ public interface GatewayReceiverMXBean {
/**
* Returns the port the receiver is listening on.
*/
- public int getPort();
+ int getPort();
/**
* Returns the configured buffer size of the socket connection.
*/
- public int getSocketBufferSize();
+ int getSocketBufferSize();
/**
* Returns the bind address on the host.
*/
- public String getBindAddress();
+ String getBindAddress();
/**
* Returns the maximum amount of time between client pings.
*/
- public int getMaximumTimeBetweenPings();
+ int getMaximumTimeBetweenPings();
/**
* Returns whether the receiver is in running state.
*
* @return True if the receiver is in a running state, false otherwise.
*/
- public boolean isRunning();
+ boolean isRunning();
/**
* Returns the instantaneous rate of events received.
*/
- public float getEventsReceivedRate();
+ float getEventsReceivedRate();
/**
* Returns the rate of create requests received.
*/
- public float getCreateRequestsRate();
+ float getCreateRequestsRate();
/**
* Returns the rate of update requests received.
*/
- public float getUpdateRequestsRate();
+ float getUpdateRequestsRate();
/**
* Returns the rate of destroy requests received.
*/
- public float getDestroyRequestsRate();
+ float getDestroyRequestsRate();
/**
* Returns the number of duplicate batches which have been received.
*/
- public int getDuplicateBatchesReceived();
+ int getDuplicateBatchesReceived();
/**
* Returns the number of batches which have been received out of order.
*/
- public int getOutoforderBatchesReceived();
+ int getOutoforderBatchesReceived();
/**
* Starts the gateway receiver.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void start() throws Exception;
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
+ void start() throws Exception;
/**
* Stops the gateway receiver.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void stop() throws Exception;
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
+ void stop() throws Exception;
/**
* Returns the configured start port.
*/
- public int getStartPort();
+ int getStartPort();
/**
* Returns the configured end port.
*/
- public int getEndPort();
+ int getEndPort();
/**
* Returns a list of names for the transport filters in use.
*/
- public String[] getGatewayTransportFilters();
+ String[] getGatewayTransportFilters();
/**
* Returns the number of sockets accepted and used for client to server messaging.
*/
- public int getClientConnectionCount();
+ int getClientConnectionCount();
/**
* Returns the number of client virtual machines connected and acting as a gateway.
*/
- public int getNumGateways();
+ int getNumGateways();
/**
* Returns the average get request latency.
*/
- public long getGetRequestAvgLatency();
+ long getGetRequestAvgLatency();
/**
* Returns the average put request latency.
*/
- public long getPutRequestAvgLatency();
+ long getPutRequestAvgLatency();
/**
* Returns the total number of client connections that timed out and were closed.
*/
- public int getTotalConnectionsTimedOut();
+ int getTotalConnectionsTimedOut();
/**
* Returns the total number of client connection requests that failed.
*/
- public int getTotalFailedConnectionAttempts();
+ int getTotalFailedConnectionAttempts();
/**
* Returns the current number of connections waiting for a thread to start processing their
* message.
*/
- public int getThreadQueueSize();
+ int getThreadQueueSize();
/**
* Returns the current number of threads handling a client connection.
*/
- public int getConnectionThreads();
+ int getConnectionThreads();
/**
* Returns the load from client to server connections as reported by the load probe installed in
* this server.
*/
- public double getConnectionLoad();
+ double getConnectionLoad();
/**
* Returns the estimate of how much load is added for each new connection as reported by the load
* probe installed in this server.
*/
- public double getLoadPerConnection();
+ double getLoadPerConnection();
/**
* Returns the load from queues as reported by the load probe installed in this server.
*/
- public double getQueueLoad();
+ double getQueueLoad();
/**
* Returns the estimate of how much load is added for each new queue as reported by the load probe
* installed in this server.
*/
- public double getLoadPerQueue();
+ double getLoadPerQueue();
/**
* Returns the rate of get requests.
*/
- public float getGetRequestRate();
+ float getGetRequestRate();
/**
* Returns the rate of put requests.
*/
- public float getPutRequestRate();
+ float getPutRequestRate();
/**
* Returns the total number of bytes sent to clients.
*/
- public long getTotalSentBytes();
+ long getTotalSentBytes();
/**
* Returns the total number of bytes received from clients.
*/
- public long getTotalReceivedBytes();
+ long getTotalReceivedBytes();
/**
* Returns a list of the host and port information for gateway senders connected to this gateway
* receiver.
*/
- public String[] getConnectedGatewaySenders();
+ String[] getConnectedGatewaySenders();
/**
* Returns the average batch processing time (in milliseconds).
*/
- public long getAverageBatchProcessingTime();
+ long getAverageBatchProcessingTime();
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/GatewaySenderMXBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/GatewaySenderMXBean.java b/geode-core/src/main/java/org/apache/geode/management/GatewaySenderMXBean.java
index 718a9be..f8cad87 100644
--- a/geode-core/src/main/java/org/apache/geode/management/GatewaySenderMXBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/GatewaySenderMXBean.java
@@ -18,6 +18,7 @@ import org.apache.geode.cache.wan.GatewaySender;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* MBean that provides access to information and management functionality for a
@@ -32,51 +33,51 @@ public interface GatewaySenderMXBean {
/**
* Returns the ID of the GatewaySender.
*/
- public String getSenderId();
+ String getSenderId();
/**
* Returns the id of the remote <code>GatewayReceiver</code>'s DistributedSystem.
*/
- public int getRemoteDSId();
+ int getRemoteDSId();
/**
* Returns the configured buffer size of the socket connection between this GatewaySender and its
* receiving <code>GatewayReceiver</code>.
*/
- public int getSocketBufferSize();
+ int getSocketBufferSize();
/**
* Returns the amount of time (in milliseconds) that a socket read between a sending GatewaySender
* and its receiving <code>GatewayReceiver</code> is allowed to block.
*/
- public long getSocketReadTimeout();
+ long getSocketReadTimeout();
/**
* Returns the name of the disk store that is used for persistence.
*/
- public String getOverflowDiskStoreName();
+ String getOverflowDiskStoreName();
/**
* Returns the maximum memory after which the data needs to be overflowed to disk.
*/
- public int getMaximumQueueMemory();
+ int getMaximumQueueMemory();
/**
* Returns the size of a batch that gets delivered by the GatewaySender.
*/
- public int getBatchSize();
+ int getBatchSize();
/**
* Returns the interval between transmissions by the GatewaySender.
*/
- public long getBatchTimeInterval();
+ long getBatchTimeInterval();
/**
* Returns whether batch conflation for the GatewaySender's queue is enabled
*
* @return True if batch conflation is enabled, false otherwise.
*/
- public boolean isBatchConflationEnabled();
+ boolean isBatchConflationEnabled();
/**
* Returns whether the GatewaySender is configured to be persistent or non-persistent.
@@ -84,162 +85,167 @@ public interface GatewaySenderMXBean {
* @return True if the sender is persistent, false otherwise.
*/
- public boolean isPersistenceEnabled();
+ boolean isPersistenceEnabled();
/**
* Returns the alert threshold for entries in a GatewaySender's queue.The default value is 0
* milliseconds in which case no alert will be logged if events are delayed in Queue.
*/
- public int getAlertThreshold();
+ int getAlertThreshold();
/**
* Returns a list of <code>GatewayEventFilter</code>s added to this GatewaySender.
*/
- public String[] getGatewayEventFilters();
+ String[] getGatewayEventFilters();
/**
* Returns a list of <code>GatewayTransportFilter</code>s added to this GatewaySender.
*/
- public String[] getGatewayTransportFilters();
+ String[] getGatewayTransportFilters();
/**
* Returns whether the GatewaySender is configured for manual start.
*
* @return True if the GatewaySender is configured for manual start, false otherwise.
*/
- public boolean isManualStart();
+ boolean isManualStart();
/**
* Returns whether or not this GatewaySender is running.
*
* @return True if the GatewaySender is running, false otherwise.
*/
- public boolean isRunning();
+ boolean isRunning();
/**
* Returns whether or not this GatewaySender is paused.
*
* @return True of the GatewaySender is paused, false otherwise.
*/
- public boolean isPaused();
+ boolean isPaused();
/**
* Returns the rate of events received per second by this Sender if it's a serial-wan.
*/
- public float getEventsReceivedRate();
+ float getEventsReceivedRate();
/**
* Returns the rate of events being queued.
*/
- public float getEventsQueuedRate();
+ float getEventsQueuedRate();
/**
* Returns the current size of the event queue.
*/
- public int getEventQueueSize();
+ int getEventQueueSize();
/**
* Returns the number of events received, but not added to the event queue, because the queue
* already contains an event with the same key.
*/
- public int getTotalEventsConflated();
+ int getTotalEventsConflated();
/**
* Returns the average number of batches sent per second.
*/
- public float getBatchesDispatchedRate();
+ float getBatchesDispatchedRate();
/**
* Returns the average time taken to send a batch of events.
*/
- public long getAverageDistributionTimePerBatch();
+ long getAverageDistributionTimePerBatch();
/**
* Returns the total number of batches of events that were resent.
*/
- public int getTotalBatchesRedistributed();
+ int getTotalBatchesRedistributed();
/**
* Starts this GatewaySender. Once the GatewaySender is running its configuration cannot be
* changed.
*
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void start();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
+ void start();
/**
* Stops this GatewaySender.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void stop();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
+ void stop();
/**
* Pauses this GatewaySender.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void pause();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
+ void pause();
/**
* Resumes this paused GatewaySender.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void resume();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
+ void resume();
/**
* Rebalances this GatewaySender.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void rebalance();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
+ void rebalance();
/**
* Returns whether this GatewaySender is primary or secondary.
*
* @return True if this is the primary, false otherwise.
*/
- public boolean isPrimary();
+ boolean isPrimary();
/**
* Returns the number of dispatcher threads working for this <code>GatewaySender</code>.
*/
- public int getDispatcherThreads();
+ int getDispatcherThreads();
/**
* Returns the order policy followed while dispatching the events to remote distributed system.
* Order policy is only relevant when the number of dispatcher threads is greater than one.
*/
- public String getOrderPolicy();
+ String getOrderPolicy();
/**
* Returns whether the isDiskSynchronous property is set for this GatewaySender.
*
* @return True if the property is set, false otherwise.
*/
- public boolean isDiskSynchronous();
+ boolean isDiskSynchronous();
/**
* Returns whether the isParallel property is set for this GatewaySender.
*
* @return True if the property is set, false otherwise.
*/
- public boolean isParallel();
+ boolean isParallel();
/**
* Returns the host and port information of GatewayReceiver to which this gateway sender is
* connected.
*/
- public String getGatewayReceiver();
+ String getGatewayReceiver();
/**
* Returns whether this GatewaySender is connected and sending data to a GatewayReceiver.
*/
- public boolean isConnected();
+ boolean isConnected();
/**
* Returns number of events which have exceeded the configured alert threshold.
*/
- public int getEventsExceedingAlertThreshold();
+ int getEventsExceedingAlertThreshold();
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/LockServiceMXBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/LockServiceMXBean.java b/geode-core/src/main/java/org/apache/geode/management/LockServiceMXBean.java
index f109022..a62ca49 100644
--- a/geode-core/src/main/java/org/apache/geode/management/LockServiceMXBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/LockServiceMXBean.java
@@ -35,53 +35,53 @@ public interface LockServiceMXBean {
/**
* Returns the name of the lock service.
*/
- public String getName();
+ String getName();
/**
* Returns whether this is a distributed LockService.
*
* @return True is this is a distributed LockService, false otherwise.
*/
- public boolean isDistributed();
+ boolean isDistributed();
/**
* Returns the number of members using this LockService.
*/
- public int getMemberCount();
+ int getMemberCount();
/**
* Returns of the name of the member which grants the lock.
*/
- public String fetchGrantorMember();
+ String fetchGrantorMember();
/**
* Returns a list of names of the members using this LockService.
*/
- public String[] getMemberNames();
+ String[] getMemberNames();
/**
* Returns whether this member is the granter.
*
* @return True if this member is the granter, false otherwise.
*/
- public boolean isLockGrantor();
+ boolean isLockGrantor();
/**
* Requests that this member become the granter.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public void becomeLockGrantor();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
+ void becomeLockGrantor();
/**
* Returns a map of the names of the objects being locked on and the names of the threads holding
* the locks.
*/
- public Map<String, String> listThreadsHoldingLock();
+ Map<String, String> listThreadsHoldingLock();
/**
* Returns a list of names of the locks held by this member's threads.
*/
- public String[] listHeldLocks();
+ String[] listHeldLocks();
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/MemberMXBean.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/MemberMXBean.java b/geode-core/src/main/java/org/apache/geode/management/MemberMXBean.java
index e2de400..ca7c2a2 100644
--- a/geode-core/src/main/java/org/apache/geode/management/MemberMXBean.java
+++ b/geode-core/src/main/java/org/apache/geode/management/MemberMXBean.java
@@ -20,6 +20,7 @@ import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
/**
* MBean that provides access to information and management functionality for a
@@ -143,7 +144,7 @@ public interface MemberMXBean {
*
* @param numberOfLines Number of lines to return, up to a maximum of 100.
*/
- public String showLog(int numberOfLines);
+ String showLog(int numberOfLines);
/**
* Returns the license string for this member.
@@ -151,15 +152,16 @@ public interface MemberMXBean {
* @deprecated Removed licensing in 8.0.
*/
@Deprecated
- public String viewLicense();
+ String viewLicense();
/**
* Performs compaction on all of the member's disk stores.
*
* @return A list of names of the disk stores that were compacted.
*/
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
- public String[] compactAllDiskStores();
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ String[] compactAllDiskStores();
/**
* Creates a Manager MBean on this member.
@@ -167,24 +169,24 @@ public interface MemberMXBean {
* @return True if the Manager MBean was successfully created, false otherwise.
*/
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
- public boolean createManager();
+ boolean createManager();
/**
* Shuts down the member. This is an asynchronous call and it will return immediately without
* waiting for a result.
*/
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
- public void shutDownMember();
+ void shutDownMember();
/**
* Returns JVM metrics.
*/
- public JVMMetrics showJVMMetrics();
+ JVMMetrics showJVMMetrics();
/**
* Returns operating system metrics.
*/
- public OSMetrics showOSMetrics();
+ OSMetrics showOSMetrics();
/**
* Executes a command on the member.
@@ -222,89 +224,89 @@ public interface MemberMXBean {
*
* @param includeRegionOwned Whether to include disk stores owned by a region.
*/
- public String[] listDiskStores(boolean includeRegionOwned);
+ String[] listDiskStores(boolean includeRegionOwned);
/**
* Returns the GemFire specific properties for this member.
*/
- public GemFireProperties listGemFireProperties();
+ GemFireProperties listGemFireProperties();
/**
* Returns the name or IP address of the host on which this member is running.
*/
- public String getHost();
+ String getHost();
/**
* Returns the name of this member.
*/
- public String getName();
+ String getName();
/**
* Returns the ID of this member.
*/
- public String getId();
+ String getId();
/**
* Returns the name of the member if it's been set, otherwise the ID.
*/
- public String getMember();
+ String getMember();
/**
* Returns the names of the groups this member belongs to.
*/
- public String[] getGroups();
+ String[] getGroups();
/**
* Returns the operating system process ID.
*/
- public int getProcessId();
+ int getProcessId();
/**
* Returns the status.
*/
- public String status();
+ String status();
/**
* Returns the GemFire version.
*/
- public String getVersion();
+ String getVersion();
/**
* Returns whether this member is attached to at least one Locator.
*
* @return True if this member is attached to a Locator, false otherwise.
*/
- public boolean isLocator();
+ boolean isLocator();
/**
* Returns the number of seconds that this member will wait for a distributed lock.
*/
- public long getLockTimeout();
+ long getLockTimeout();
/**
* Returns the number of second that this member will lease a distributed lock.
*/
- public long getLockLease();
+ long getLockLease();
/**
* Any long-running GemFire process that was started with "start server" command from GFSH. It
* returns true even if that process has --disable-default-server=true.
*/
- public boolean isServer();
+ boolean isServer();
/**
* Returns whether this member has at least one GatewaySender.
*
- * @return True if this member has at least one GatwaySender, false otherwise.
+ * @return True if this member has at least one GatewaySender, false otherwise.
*/
- public boolean hasGatewaySender();
+ boolean hasGatewaySender();
/**
* Returns whether this member is running the Manager service.
*
* @return True if this member is running the Manager service, false otherwise.
*/
- public boolean isManager();
+ boolean isManager();
/**
* Returns whether this member has created the Manager service (it may be created, but not
@@ -312,29 +314,29 @@ public interface MemberMXBean {
*
* @return True if this member has created the Manager service, false otherwise.
*/
- public boolean isManagerCreated();
+ boolean isManagerCreated();
/**
* Returns whether this member has at least one GatewayReceiver.
*
- * @return True if this member has at least one GatwayReceiver, false otherwise.
+ * @return True if this member has at least one GatewayReceiver, false otherwise.
*/
- public boolean hasGatewayReceiver();
+ boolean hasGatewayReceiver();
/**
* Returns the ClassPath.
*/
- public String getClassPath();
+ String getClassPath();
/**
* Returns the current time on the member's host.
*/
- public long getCurrentTime();
+ long getCurrentTime();
/**
* Returns the number of seconds that this member has been running.
*/
- public long getMemberUpTime();
+ long getMemberUpTime();
/**
* Returns the time (as a percentage) that this member's process time with respect to Statistics
@@ -345,393 +347,402 @@ public interface MemberMXBean {
* the platform it will be shown as -1
*
*/
- public float getCpuUsage();
+ float getCpuUsage();
/**
* Returns the current size of the heap in megabytes.
*
* @deprecated Please use {@link #getUsedMemory()} instead.
*/
- public long getCurrentHeapSize();
+ long getCurrentHeapSize();
/**
* Returns the maximum size of the heap in megabytes.
*
* @deprecated Please use {@link #getMaxMemory()} instead.
*/
- public long getMaximumHeapSize();
+ long getMaximumHeapSize();
/**
* Returns the free heap size in megabytes.
*
* @deprecated Please use {@link #getFreeMemory()} instead.
*/
- public long getFreeHeapSize();
+ long getFreeHeapSize();
/**
* Returns the maximum size of the heap in megabytes.
*
*/
- public long getMaxMemory();
+ long getMaxMemory();
/**
* Returns the free heap size in megabytes.
*/
- public long getFreeMemory();
+ long getFreeMemory();
/**
* Returns the current size of the heap in megabytes.
*/
- public long getUsedMemory();
+ long getUsedMemory();
/**
* Returns the current threads.
*/
- public String[] fetchJvmThreads();
+ String[] fetchJvmThreads();
/**
* Returns the maximum number of open file descriptors allowed for the member's host operating
* system.
*/
- public long getFileDescriptorLimit();
+ long getFileDescriptorLimit();
/**
* Returns the current number of open file descriptors.
*/
- public long getTotalFileDescriptorOpen();
+ long getTotalFileDescriptorOpen();
/**
* Returns the number of Regions present in the Cache.
*/
- public int getTotalRegionCount();
+ int getTotalRegionCount();
/**
* Returns the number of Partition Regions present in the Cache.
*/
- public int getPartitionRegionCount();
+ int getPartitionRegionCount();
/**
* Returns a list of all Region names.
*/
- public String[] listRegions();
+ String[] listRegions();
/**
* Returns a list of all disk stores, including those owned by a Region.
*/
- public String[] getDiskStores();
+ String[] getDiskStores();
/**
* Returns a list of all root Region names.
*/
- public String[] getRootRegionNames();
+ String[] getRootRegionNames();
/**
* Returns the total number of entries in all regions.
*/
- public int getTotalRegionEntryCount();
+ int getTotalRegionEntryCount();
/**
* Returns the total number of buckets.
*/
- public int getTotalBucketCount();
+ int getTotalBucketCount();
/**
* Returns the number of buckets for which this member is the primary holder.
*/
- public int getTotalPrimaryBucketCount();
+ int getTotalPrimaryBucketCount();
/**
* Returns the cache get average latency.
*/
- public long getGetsAvgLatency();
+ long getGetsAvgLatency();
/**
* Returns the cache put average latency.
*/
- public long getPutsAvgLatency();
+ long getPutsAvgLatency();
/**
* Returns the cache putAll average latency.
*/
- public long getPutAllAvgLatency();
+ long getPutAllAvgLatency();
/**
* Returns the number of times that a cache miss occurred for all regions.
*/
- public int getTotalMissCount();
+ int getTotalMissCount();
/**
* Returns the number of times that a hit occurred for all regions.
*/
- public int getTotalHitCount();
+ int getTotalHitCount();
/**
* Returns the number of gets per second.
*/
- public float getGetsRate();
+ float getGetsRate();
/**
* Returns the number of puts per second. Only includes puts done explicitly on this member's
* cache, not those pushed from another member.
*/
- public float getPutsRate();
+ float getPutsRate();
/**
* Returns the number of putAlls per second.
*/
- public float getPutAllRate();
+ float getPutAllRate();
/**
* Returns the number of creates per second.
*/
- public float getCreatesRate();
+ float getCreatesRate();
/**
* Returns the number of destroys per second.
*/
- public float getDestroysRate();
+ float getDestroysRate();
/**
* Returns the average latency of a call to a CacheWriter.
*/
- public long getCacheWriterCallsAvgLatency();
+ long getCacheWriterCallsAvgLatency();
/**
* Returns the average latency of a call to a CacheListener.
*/
- public long getCacheListenerCallsAvgLatency();
+ long getCacheListenerCallsAvgLatency();
/**
* Returns the total number of times that a load on this cache has completed, as a result of
* either a local get or a remote net load.
*/
- public int getTotalLoadsCompleted();
+ int getTotalLoadsCompleted();
/**
* Returns the average latency of a load.
*/
- public long getLoadsAverageLatency();
+ long getLoadsAverageLatency();
/**
* Returns the total number of times the a network load initiated by this cache has completed.
*/
- public int getTotalNetLoadsCompleted();
+ int getTotalNetLoadsCompleted();
/**
* Returns the net load average latency.
*/
- public long getNetLoadsAverageLatency();
+ long getNetLoadsAverageLatency();
/**
* Returns the total number of times that a network search initiated by this cache has completed.
*/
- public int getTotalNetSearchCompleted();
+ int getTotalNetSearchCompleted();
/**
* Returns the net search average latency.
*/
- public long getNetSearchAverageLatency();
+ long getNetSearchAverageLatency();
/**
* Returns the current number of disk tasks (op-log compaction, asynchronous recovery, etc.) that
* are waiting for a thread to run.
*/
- public int getTotalDiskTasksWaiting();
+ int getTotalDiskTasksWaiting();
/**
* Returns the average number of bytes per second sent.
*/
- public float getBytesSentRate();
+ float getBytesSentRate();
/**
* Returns the average number of bytes per second received.
*/
- public float getBytesReceivedRate();
+ float getBytesReceivedRate();
/**
* Returns a list of IDs for all connected gateway receivers.
*/
- public String[] listConnectedGatewayReceivers();
+ String[] listConnectedGatewayReceivers();
/**
* Returns a list of IDs for all gateway senders.
*/
- public String[] listConnectedGatewaySenders();
+ String[] listConnectedGatewaySenders();
/**
* Returns the number of currently executing functions.
*/
- public int getNumRunningFunctions();
+ int getNumRunningFunctions();
/**
* Returns the average function execution rate.
*/
- public float getFunctionExecutionRate();
+ float getFunctionExecutionRate();
/**
- * Returns the number of currently executing functions that will return resutls.
+ * Returns the number of currently executing functions that will return results.
*/
- public int getNumRunningFunctionsHavingResults();
+ int getNumRunningFunctionsHavingResults();
/**
* Returns the number of current transactions.
*/
- public int getTotalTransactionsCount();
+ int getTotalTransactionsCount();
/**
* Returns the average commit latency in nanoseconds .
*/
- public long getTransactionCommitsAvgLatency();
+ long getTransactionCommitsAvgLatency();
/**
* Returns the number of committed transactions.
*/
- public int getTransactionCommittedTotalCount();
+ int getTransactionCommittedTotalCount();
/**
* Returns the number of transactions that were rolled back.
*/
- public int getTransactionRolledBackTotalCount();
+ int getTransactionRolledBackTotalCount();
/**
* Returns the average number of transactions committed per second.
*/
- public float getTransactionCommitsRate();
+ float getTransactionCommitsRate();
/**
* Returns the number of bytes reads per second from all the disks of the member.
*/
- public float getDiskReadsRate();
+ float getDiskReadsRate();
/**
* Returns the number of bytes written per second to disk to all the disks of the member.
*/
- public float getDiskWritesRate();
+ float getDiskWritesRate();
/**
* Returns the average disk flush latency time in nanoseconds.
*/
- public long getDiskFlushAvgLatency();
+ long getDiskFlushAvgLatency();
/**
* Returns the number of backups currently in progress for all disk stores.
*/
- public int getTotalBackupInProgress();
+ int getTotalBackupInProgress();
/**
* Returns the number of backups that have been completed.
*/
- public int getTotalBackupCompleted();
+ int getTotalBackupCompleted();
/**
* Returns the number of threads waiting for a lock.
*/
- public int getLockWaitsInProgress();
+ int getLockWaitsInProgress();
/**
* Returns the amount of time (in milliseconds) spent waiting for a lock.
*/
- public long getTotalLockWaitTime();
+ long getTotalLockWaitTime();
/**
* Returns the number of lock services in use.
*/
- public int getTotalNumberOfLockService();
+ int getTotalNumberOfLockService();
/**
* Returns the number of locks for which this member is a granter.
*/
- public int getTotalNumberOfGrantors();
+ int getTotalNumberOfGrantors();
/**
* Returns the number of lock request queues in use by this member.
*/
- public int getLockRequestQueues();
+ int getLockRequestQueues();
/**
* Returns the entry eviction rate as triggered by the LRU policy.
*/
- public float getLruEvictionRate();
+ float getLruEvictionRate();
/**
* Returns the rate of entries destroyed either by destroy cache operations or eviction.
*/
- public float getLruDestroyRate();
+ float getLruDestroyRate();
+
+ /**
+ * Returns the number of initial images in progress.
+ *
+ * @deprecated as typo in name has been corrected: use
+ * {@link MemberMXBean#getInitialImagesInProgress} instead.
+ */
+ @Deprecated
+ int getInitialImagesInProgres();
/**
* Returns the number of initial images in progress.
*/
- public int getInitialImagesInProgres();
+ int getInitialImagesInProgress();
/**
* Returns the total amount of time spent performing a "get initial image" operation when creating
* a region.
*/
- public long getInitialImageTime();
+ long getInitialImageTime();
/**
* Return the number of keys received while performing a "get initial image" operation when
* creating a region.
*/
- public int getInitialImageKeysReceived();
+ int getInitialImageKeysReceived();
/**
* Returns the average time (in nanoseconds) spent deserializing objects. Includes
* deserializations that result in a PdxInstance.
*/
- public long getDeserializationAvgLatency();
+ long getDeserializationAvgLatency();
/**
* Returns the average latency (in nanoseconds) spent deserializing objects. Includes
* deserializations that result in a PdxInstance.
*/
- public long getDeserializationLatency();
+ long getDeserializationLatency();
/**
* Returns the instantaneous rate of deserializing objects. Includes deserializations that result
* in a PdxInstance.
*/
- public float getDeserializationRate();
+ float getDeserializationRate();
/**
* Returns the average time (in nanoseconds) spent serializing objects. Includes serializations
* that result in a PdxInstance.
*/
- public long getSerializationAvgLatency();
+ long getSerializationAvgLatency();
/**
* Returns the average latency (in nanoseconds) spent serializing objects. Includes serializations
* that result in a PdxInstance.
*/
- public long getSerializationLatency();
+ long getSerializationLatency();
/**
* Returns the instantaneous rate of serializing objects. Includes serializations that result in a
* PdxInstance.
*/
- public float getSerializationRate();
+ float getSerializationRate();
/**
* Returns the instantaneous rate of PDX instance deserialization.
*/
- public float getPDXDeserializationRate();
+ float getPDXDeserializationRate();
/**
* Returns the average time, in seconds, spent deserializing PDX instanced.
*/
- public long getPDXDeserializationAvgLatency();
+ long getPDXDeserializationAvgLatency();
/**
* Returns the total number of bytes used on all disks.
*/
- public long getTotalDiskUsage();
+ long getTotalDiskUsage();
/**
* Returns the number of threads in use.
*/
- public int getNumThreads();
+ int getNumThreads();
/**
* Returns the system load average for the last minute. The system load average is the sum of the
@@ -742,99 +753,99 @@ public interface MemberMXBean {
*
* @return The load average or a negative value if one is not available.
*/
- public double getLoadAverage();
+ double getLoadAverage();
/**
* Returns the number of times garbage collection has occurred.
*/
- public long getGarbageCollectionCount();
+ long getGarbageCollectionCount();
/**
* Returns the amount of time (in milliseconds) spent on garbage collection.
*/
- public long getGarbageCollectionTime();
+ long getGarbageCollectionTime();
/**
* Returns the average number of reads per second.
*/
- public float getAverageReads();
+ float getAverageReads();
/**
* Returns the average writes per second, including both put and putAll operations.
*/
- public float getAverageWrites();
+ float getAverageWrites();
/**
* Returns the number JVM pauses (which may or may not include full garbage collection pauses)
* detected by GemFire.
*/
- public long getJVMPauses();
+ long getJVMPauses();
/**
* Returns the underlying host's current cpuActive percentage
*/
- public int getHostCpuUsage();
+ int getHostCpuUsage();
/**
*
* Returns true if a cache server is running on this member and able server requests from GemFire
* clients
*/
- public boolean isCacheServer();
+ boolean isCacheServer();
/**
* Returns the redundancy-zone of the member;
*/
- public String getRedundancyZone();
+ String getRedundancyZone();
/**
* Returns current number of cache rebalance operations being directed by this process.
*/
- public int getRebalancesInProgress();
+ int getRebalancesInProgress();
/**
* Returns current number of threads waiting for a reply.
*/
- public int getReplyWaitsInProgress();
+ int getReplyWaitsInProgress();
/**
* Returns total number of times waits for a reply have completed.
*/
- public int getReplyWaitsCompleted();
+ int getReplyWaitsCompleted();
/**
* The current number of nodes in this distributed system visible to this member.
*/
- public int getVisibleNodes();
+ int getVisibleNodes();
/**
* Returns the number of off heap objects.
*/
- public int getOffHeapObjects();
+ int getOffHeapObjects();
/**
* Returns the size of the maximum configured off-heap memory in bytes.
*/
- public long getOffHeapMaxMemory();
+ long getOffHeapMaxMemory();
/**
* Returns the size of available (or unallocated) off-heap memory in bytes.
*/
- public long getOffHeapFreeMemory();
+ long getOffHeapFreeMemory();
/**
* Returns the size of utilized off-heap memory in bytes.
*/
- public long getOffHeapUsedMemory();
+ long getOffHeapUsedMemory();
/**
* Returns the percentage of off-heap memory fragmentation.
*/
- public int getOffHeapFragmentation();
+ int getOffHeapFragmentation();
/**
- * Returns the total time spent compacting in millseconds.
+ * Returns the total time spent compacting in milliseconds.
*/
- public long getOffHeapCompactionTime();
+ long getOffHeapCompactionTime();
}
[3/6] geode git commit: GEODE-2919: Provide finer grained security
Posted by js...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
index 68dbbf0..3222666 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
@@ -14,6 +14,17 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.FunctionInvocationTargetException;
import org.apache.geode.cache.execute.ResultCollector;
@@ -31,7 +42,6 @@ import org.apache.geode.management.internal.cli.domain.RegionInformation;
import org.apache.geode.management.internal.cli.functions.GetRegionDescriptionFunction;
import org.apache.geode.management.internal.cli.functions.GetRegionsFunction;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResultException;
import org.apache.geode.management.internal.cli.result.CompositeResultData;
import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
@@ -40,17 +50,6 @@ import org.apache.geode.management.internal.cli.util.RegionAttributesNames;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
/**
* Class containing implementation of commands based on region:
@@ -67,8 +66,8 @@ public class RegionCommands implements GfshCommand {
new GetRegionDescriptionFunction();
@CliCommand(value = {CliStrings.LIST_REGION}, help = CliStrings.LIST_REGION__HELP)
- @CliMetaData(shellOnly = false, relatedTopic = CliStrings.TOPIC_GEODE_REGION)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.READ)
+ @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result listRegion(
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
optionContext = ConverterHint.MEMBERGROUP,
@@ -78,8 +77,8 @@ public class RegionCommands implements GfshCommand {
help = CliStrings.LIST_REGION__MEMBER__HELP) String[] memberNameOrId) {
Result result = null;
try {
- Set<RegionInformation> regionInfoSet = new LinkedHashSet<RegionInformation>();
- ResultCollector<?, ?> rc = null;
+ Set<RegionInformation> regionInfoSet = new LinkedHashSet<>();
+ ResultCollector<?, ?> rc;
Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
@@ -93,11 +92,8 @@ public class RegionCommands implements GfshCommand {
ArrayList<?> resultList = (ArrayList<?>) rc.getResult();
if (resultList != null) {
- Iterator<?> iters = resultList.iterator();
-
- while (iters.hasNext()) {
- Object resultObj = iters.next();
+ for (Object resultObj : resultList) {
if (resultObj != null) {
if (resultObj instanceof Object[]) {
Object[] resultObjectArray = (Object[]) resultObj;
@@ -110,15 +106,13 @@ public class RegionCommands implements GfshCommand {
}
}
- Set<String> regionNames = new TreeSet<String>();
+ Set<String> regionNames = new TreeSet<>();
for (RegionInformation regionInfo : regionInfoSet) {
regionNames.add(regionInfo.getName());
Set<String> subRegionNames = regionInfo.getSubRegionNames();
- for (String subRegionName : subRegionNames) {
- regionNames.add(subRegionName);
- }
+ regionNames.addAll(subRegionNames);
}
for (String regionName : regionNames) {
@@ -143,14 +137,13 @@ public class RegionCommands implements GfshCommand {
}
@CliCommand(value = {CliStrings.DESCRIBE_REGION}, help = CliStrings.DESCRIBE_REGION__HELP)
- @CliMetaData(shellOnly = false,
- relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_CONFIG})
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_CONFIG})
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result describeRegion(
@CliOption(key = CliStrings.DESCRIBE_REGION__NAME, optionContext = ConverterHint.REGION_PATH,
help = CliStrings.DESCRIBE_REGION__NAME__HELP, mandatory = true) String regionName) {
- Result result = null;
+ Result result;
try {
if (regionName == null || regionName.isEmpty()) {
@@ -170,7 +163,7 @@ public class RegionCommands implements GfshCommand {
// The returned result could be a region description with per member and /or single local
// region
Object[] results = resultList.toArray();
- List<RegionDescription> regionDescriptionList = new ArrayList<RegionDescription>();
+ List<RegionDescription> regionDescriptionList = new ArrayList<>();
for (int i = 0; i < results.length; i++) {
@@ -204,11 +197,8 @@ public class RegionCommands implements GfshCommand {
}
CompositeResultData crd = ResultBuilder.createCompositeResultData();
- Iterator<RegionDescription> iters = regionDescriptionList.iterator();
-
- while (iters.hasNext()) {
- RegionDescription regionDescription = iters.next();
+ for (RegionDescription regionDescription : regionDescriptionList) {
// No point in displaying the scope for PR's
if (regionDescription.isPartition()) {
regionDescription.getCndRegionAttributes().remove(RegionAttributesNames.SCOPE);
@@ -228,7 +218,7 @@ public class RegionCommands implements GfshCommand {
regionDescription.getDataPolicy().toString().toLowerCase().replace('_', ' ');
regionSection.addData("Data Policy", dataPolicy);
- String memberType = "";
+ String memberType;
if (regionDescription.isAccessor()) {
memberType = CliStrings.DESCRIBE_REGION__ACCESSOR__MEMBER;
@@ -265,8 +255,6 @@ public class RegionCommands implements GfshCommand {
Set<String> members = regDescPerMemberMap.keySet();
TabularResultData table = regionSection.addSection().addTable();
- // table.setHeader(CliStrings.format(CliStrings.DESCRIBE_REGION__NONDEFAULT__PERMEMBERATTRIBUTES__HEADER,
- // memberType));
boolean setHeader = false;
for (String member : members) {
@@ -291,9 +279,9 @@ public class RegionCommands implements GfshCommand {
if (!(ndRa.isEmpty() && ndEa.isEmpty() && ndPa.isEmpty()) || fpaList != null) {
setHeader = true;
- boolean memberNameAdded = false;
+ boolean memberNameAdded;
memberNameAdded = writeAttributesToTable(table,
- CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, ndRa, member, memberNameAdded);
+ CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, ndRa, member, false);
memberNameAdded =
writeAttributesToTable(table, CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION,
ndEa, member, memberNameAdded);
@@ -302,12 +290,10 @@ public class RegionCommands implements GfshCommand {
memberNameAdded);
writeFixedPartitionAttributesToTable(table, "", fpaList, member, memberNameAdded);
- // Fix for #46767
- // writeAttributeToTable(table, "", "", "", "");
}
}
- if (setHeader == true) {
+ if (setHeader) {
table.setHeader(CliStrings.format(
CliStrings.DESCRIBE_REGION__NONDEFAULT__PERMEMBERATTRIBUTES__HEADER, memberType));
}
@@ -332,10 +318,7 @@ public class RegionCommands implements GfshCommand {
boolean isTypeAdded = false;
final String blank = "";
- Iterator<String> iters = attributes.iterator();
-
- while (iters.hasNext()) {
- String attributeName = iters.next();
+ for (String attributeName : attributes) {
String attributeValue = attributesMap.get(attributeName);
String type, memName;
@@ -403,10 +386,7 @@ public class RegionCommands implements GfshCommand {
boolean isTypeAdded = false;
final String blank = "";
- Iterator<String> iters = attributes.iterator();
-
- while (iters.hasNext()) {
- String attributeName = iters.next();
+ for (String attributeName : attributes) {
String attributeValue = attributesMap.get(attributeName);
String type, memName;
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java
index a6745fd..c6fb709 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/WanCommands.java
@@ -14,6 +14,26 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.management.ObjectName;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.internal.cache.InternalCache;
@@ -44,37 +64,20 @@ import org.apache.geode.management.internal.configuration.domain.XmlEntity;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
-import javax.management.ObjectName;
+import org.apache.geode.security.ResourcePermission.Target;
public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.CREATE_GATEWAYSENDER, help = CliStrings.CREATE_GATEWAYSENDER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result createGatewaySender(@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.CREATE_GATEWAYSENDER__GROUP__HELP) String[] onGroups,
@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.MEMBERIDNAME,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CREATE_GATEWAYSENDER__MEMBER__HELP) String[] onMember,
@CliOption(key = CliStrings.CREATE_GATEWAYSENDER__ID, mandatory = true,
@@ -131,7 +134,7 @@ public class WanCommands implements GfshCommand {
@CliOption(key = CliStrings.CREATE_GATEWAYSENDER__GATEWAYTRANSPORTFILTER,
help = CliStrings.CREATE_GATEWAYSENDER__GATEWAYTRANSPORTFILTER__HELP) String[] gatewayTransportFilter) {
- Result result = null;
+ Result result;
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
try {
@@ -182,7 +185,8 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.START_GATEWAYSENDER, help = CliStrings.START_GATEWAYSENDER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result startGatewaySender(@CliOption(key = CliStrings.START_GATEWAYSENDER__ID,
mandatory = true, optionContext = ConverterHint.GATEWAY_SENDER_ID,
help = CliStrings.START_GATEWAYSENDER__ID__HELP) String senderId,
@@ -195,7 +199,7 @@ public class WanCommands implements GfshCommand {
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.START_GATEWAYSENDER__MEMBER__HELP) String[] onMember) {
- Result result = null;
+ Result result;
final String id = senderId.trim();
try {
@@ -222,45 +226,41 @@ public class WanCommands implements GfshCommand {
}
});
- List<Callable<List>> callables = new ArrayList<Callable<List>>();
+ List<Callable<List>> callables = new ArrayList<>();
for (final DistributedMember member : dsMembers) {
- callables.add(new Callable<List>() {
-
- public List call() throws Exception {
+ callables.add(() -> {
- GatewaySenderMXBean bean = null;
- ArrayList<String> statusList = new ArrayList<String>();
- if (cache.getDistributedSystem().getDistributedMember().getId()
- .equals(member.getId())) {
- bean = service.getLocalGatewaySenderMXBean(id);
- } else {
- ObjectName objectName = service.getGatewaySenderMBeanName(member, id);
- bean = service.getMBeanProxy(objectName, GatewaySenderMXBean.class);
- }
- if (bean != null) {
- if (bean.isRunning()) {
- statusList.add(member.getId());
- statusList.add(CliStrings.GATEWAY_ERROR);
- statusList.add(
- CliStrings.format(CliStrings.GATEWAY_SENDER_0_IS_ALREADY_STARTED_ON_MEMBER_1,
- id, member.getId()));
- } else {
- bean.start();
- statusList.add(member.getId());
- statusList.add(CliStrings.GATEWAY_OK);
- statusList.add(CliStrings.format(CliStrings.GATEWAY_SENDER_0_IS_STARTED_ON_MEMBER_1,
- id, member.getId()));
- }
- } else {
+ GatewaySenderMXBean bean;
+ ArrayList<String> statusList = new ArrayList<>();
+ if (cache.getDistributedSystem().getDistributedMember().getId().equals(member.getId())) {
+ bean = service.getLocalGatewaySenderMXBean(id);
+ } else {
+ ObjectName objectName = service.getGatewaySenderMBeanName(member, id);
+ bean = service.getMBeanProxy(objectName, GatewaySenderMXBean.class);
+ }
+ if (bean != null) {
+ if (bean.isRunning()) {
statusList.add(member.getId());
statusList.add(CliStrings.GATEWAY_ERROR);
statusList.add(CliStrings.format(
- CliStrings.GATEWAY_SENDER_0_IS_NOT_AVAILABLE_ON_MEMBER_1, id, member.getId()));
+ CliStrings.GATEWAY_SENDER_0_IS_ALREADY_STARTED_ON_MEMBER_1, id, member.getId()));
+ } else {
+ bean.start();
+ statusList.add(member.getId());
+ statusList.add(CliStrings.GATEWAY_OK);
+ statusList.add(CliStrings.format(CliStrings.GATEWAY_SENDER_0_IS_STARTED_ON_MEMBER_1,
+ id, member.getId()));
}
- return statusList;
+ } else {
+ statusList.add(member.getId());
+ statusList.add(CliStrings.GATEWAY_ERROR);
+ statusList.add(CliStrings.format(
+ CliStrings.GATEWAY_SENDER_0_IS_NOT_AVAILABLE_ON_MEMBER_1, id, member.getId()));
}
+ return statusList;
+
});
}
@@ -276,21 +276,15 @@ public class WanCommands implements GfshCommand {
for (Future<List> future : futures) {
DistributedMember member = memberIterator.next();
- List<String> memberStatus = null;
+ List<String> memberStatus;
try {
memberStatus = future.get();
accumulateStartResult(resultData, memberStatus.get(0), memberStatus.get(1),
memberStatus.get(2));
- } catch (InterruptedException ite) {
+ } catch (InterruptedException | ExecutionException ite) {
accumulateStartResult(resultData, member.getId(), CliStrings.GATEWAY_ERROR,
CliStrings.format(CliStrings.GATEWAY_SENDER_0_COULD_NOT_BE_STARTED_ON_MEMBER_DUE_TO_1,
id, ite.getMessage()));
- continue;
- } catch (ExecutionException ee) {
- accumulateStartResult(resultData, member.getId(), CliStrings.GATEWAY_ERROR,
- CliStrings.format(CliStrings.GATEWAY_SENDER_0_COULD_NOT_BE_STARTED_ON_MEMBER_DUE_TO_1,
- id, ee.getMessage()));
- continue;
}
}
execService.shutdown();
@@ -305,7 +299,8 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.PAUSE_GATEWAYSENDER, help = CliStrings.PAUSE_GATEWAYSENDER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result pauseGatewaySender(@CliOption(key = CliStrings.PAUSE_GATEWAYSENDER__ID,
mandatory = true, optionContext = ConverterHint.GATEWAY_SENDER_ID,
help = CliStrings.PAUSE_GATEWAYSENDER__ID__HELP) String senderId,
@@ -318,7 +313,7 @@ public class WanCommands implements GfshCommand {
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.PAUSE_GATEWAYSENDER__MEMBER__HELP) String[] onMember) {
- Result result = null;
+ Result result;
if (senderId != null) {
senderId = senderId.trim();
}
@@ -328,7 +323,7 @@ public class WanCommands implements GfshCommand {
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
- GatewaySenderMXBean bean = null;
+ GatewaySenderMXBean bean;
TabularResultData resultData = ResultBuilder.createTabularResultData();
@@ -378,7 +373,8 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.RESUME_GATEWAYSENDER, help = CliStrings.RESUME_GATEWAYSENDER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result resumeGatewaySender(@CliOption(key = CliStrings.RESUME_GATEWAYSENDER__ID,
mandatory = true, optionContext = ConverterHint.GATEWAY_SENDER_ID,
help = CliStrings.RESUME_GATEWAYSENDER__ID__HELP) String senderId,
@@ -390,7 +386,7 @@ public class WanCommands implements GfshCommand {
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.RESUME_GATEWAYSENDER__MEMBER__HELP) String[] onMember) {
- Result result = null;
+ Result result;
if (senderId != null) {
senderId = senderId.trim();
}
@@ -400,7 +396,7 @@ public class WanCommands implements GfshCommand {
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
- GatewaySenderMXBean bean = null;
+ GatewaySenderMXBean bean;
TabularResultData resultData = ResultBuilder.createTabularResultData();
@@ -450,7 +446,8 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.STOP_GATEWAYSENDER, help = CliStrings.STOP_GATEWAYSENDER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result stopGatewaySender(@CliOption(key = CliStrings.STOP_GATEWAYSENDER__ID,
mandatory = true, optionContext = ConverterHint.GATEWAY_SENDER_ID,
help = CliStrings.STOP_GATEWAYSENDER__ID__HELP) String senderId,
@@ -463,7 +460,7 @@ public class WanCommands implements GfshCommand {
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.STOP_GATEWAYSENDER__MEMBER__HELP) String[] onMember) {
- Result result = null;
+ Result result;
if (senderId != null)
senderId = senderId.trim();
@@ -472,7 +469,7 @@ public class WanCommands implements GfshCommand {
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
- GatewaySenderMXBean bean = null;
+ GatewaySenderMXBean bean;
TabularResultData resultData = ResultBuilder.createTabularResultData();
@@ -518,14 +515,14 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.CREATE_GATEWAYRECEIVER,
help = CliStrings.CREATE_GATEWAYRECEIVER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result createGatewayReceiver(@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.CREATE_GATEWAYRECEIVER__GROUP__HELP) String[] onGroups,
@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.MEMBERIDNAME,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CREATE_GATEWAYRECEIVER__MEMBER__HELP) String[] onMember,
@CliOption(key = CliStrings.CREATE_GATEWAYRECEIVER__MANUALSTART,
@@ -549,7 +546,7 @@ public class WanCommands implements GfshCommand {
@CliOption(key = CliStrings.CREATE_GATEWAYRECEIVER__GATEWAYTRANSPORTFILTER,
help = CliStrings.CREATE_GATEWAYRECEIVER__GATEWAYTRANSPORTFILTER__HELP) String[] gatewayTransportFilters) {
- Result result = null;
+ Result result;
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
try {
@@ -601,12 +598,13 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.LOAD_BALANCE_GATEWAYSENDER,
help = CliStrings.LOAD_BALANCE_GATEWAYSENDER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result loadBalanceGatewaySender(@CliOption(key = CliStrings.LOAD_BALANCE_GATEWAYSENDER__ID,
mandatory = true, optionContext = ConverterHint.GATEWAY_SENDER_ID,
help = CliStrings.LOAD_BALANCE_GATEWAYSENDER__ID__HELP) String senderId) {
- Result result = null;
+ Result result;
if (senderId != null) {
senderId = senderId.trim();
}
@@ -623,7 +621,7 @@ public class WanCommands implements GfshCommand {
} else {
boolean gatewaySenderExists = false;
for (DistributedMember member : dsMembers) {
- GatewaySenderMXBean bean = null;
+ GatewaySenderMXBean bean;
if (cache.getDistributedSystem().getDistributedMember().getId().equals(member.getId())) {
bean = service.getLocalGatewaySenderMXBean(senderId);
} else {
@@ -660,7 +658,8 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.START_GATEWAYRECEIVER,
help = CliStrings.START_GATEWAYRECEIVER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result startGatewayReceiver(@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.START_GATEWAYRECEIVER__GROUP__HELP) String[] onGroup,
@@ -668,14 +667,14 @@ public class WanCommands implements GfshCommand {
@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.START_GATEWAYRECEIVER__MEMBER__HELP) String[] onMember) {
- Result result = null;
+ Result result;
try {
InternalCache cache = getCache();
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
- GatewayReceiverMXBean receieverBean = null;
+ GatewayReceiverMXBean receiverBean;
TabularResultData resultData = ResultBuilder.createTabularResultData();
@@ -689,15 +688,15 @@ public class WanCommands implements GfshCommand {
ObjectName gatewayReceiverObjectName = MBeanJMXAdapter.getGatewayReceiverMBeanName(member);
if (gatewayReceiverObjectName != null) {
- receieverBean =
+ receiverBean =
service.getMBeanProxy(gatewayReceiverObjectName, GatewayReceiverMXBean.class);
- if (receieverBean != null) {
- if (receieverBean.isRunning()) {
+ if (receiverBean != null) {
+ if (receiverBean.isRunning()) {
accumulateStartResult(resultData, member.getId(), CliStrings.GATEWAY_ERROR,
CliStrings.format(CliStrings.GATEWAY_RECEIVER_IS_ALREADY_STARTED_ON_MEMBER_0,
new Object[] {member.getId()}));
} else {
- receieverBean.start();
+ receiverBean.start();
accumulateStartResult(resultData, member.getId(), CliStrings.GATEWAY_OK,
CliStrings.format(CliStrings.GATEWAY_RECEIVER_IS_STARTED_ON_MEMBER_0,
new Object[] {member.getId()}));
@@ -725,7 +724,8 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.STOP_GATEWAYRECEIVER, help = CliStrings.STOP_GATEWAYRECEIVER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result stopGatewayReceiver(
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
@@ -736,14 +736,14 @@ public class WanCommands implements GfshCommand {
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.STOP_GATEWAYRECEIVER__MEMBER__HELP) String[] onMember) {
- Result result = null;
+ Result result;
try {
InternalCache cache = getCache();
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
- GatewayReceiverMXBean receieverBean = null;
+ GatewayReceiverMXBean receiverBean;
TabularResultData resultData = ResultBuilder.createTabularResultData();
@@ -757,11 +757,11 @@ public class WanCommands implements GfshCommand {
ObjectName gatewayReceiverObjectName = MBeanJMXAdapter.getGatewayReceiverMBeanName(member);
if (gatewayReceiverObjectName != null) {
- receieverBean =
+ receiverBean =
service.getMBeanProxy(gatewayReceiverObjectName, GatewayReceiverMXBean.class);
- if (receieverBean != null) {
- if (receieverBean.isRunning()) {
- receieverBean.stop();
+ if (receiverBean != null) {
+ if (receiverBean.isRunning()) {
+ receiverBean.stop();
accumulateStartResult(resultData, member.getId(), CliStrings.GATEWAY_OK,
CliStrings.format(CliStrings.GATEWAY_RECEIVER_IS_STOPPED_ON_MEMBER_0,
new Object[] {member.getId()}));
@@ -802,7 +802,7 @@ public class WanCommands implements GfshCommand {
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.LIST_GATEWAY__GROUP__HELP) String[] onGroup) {
- Result result = null;
+ Result result;
InternalCache cache = getCache();
try {
SystemManagementService service =
@@ -814,10 +814,8 @@ public class WanCommands implements GfshCommand {
return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
}
- Map<String, Map<String, GatewaySenderMXBean>> gatewaySenderBeans =
- new TreeMap<String, Map<String, GatewaySenderMXBean>>();
- Map<String, GatewayReceiverMXBean> gatewayReceiverBeans =
- new TreeMap<String, GatewayReceiverMXBean>();
+ Map<String, Map<String, GatewaySenderMXBean>> gatewaySenderBeans = new TreeMap<>();
+ Map<String, GatewayReceiverMXBean> gatewayReceiverBeans = new TreeMap<>();
DistributedSystemMXBean dsMXBean = service.getDistributedSystemMXBean();
for (DistributedMember member : dsMembers) {
@@ -837,8 +835,7 @@ public class WanCommands implements GfshCommand {
gatewaySenderBeans.get(senderBean.getSenderId());
memberToBeanMap.put(member.getId(), senderBean);
} else {
- Map<String, GatewaySenderMXBean> memberToBeanMap =
- new TreeMap<String, GatewaySenderMXBean>();
+ Map<String, GatewaySenderMXBean> memberToBeanMap = new TreeMap<>();
memberToBeanMap.put(member.getId(), senderBean);
gatewaySenderBeans.put(senderBean.getSenderId(), memberToBeanMap);
}
@@ -848,11 +845,11 @@ public class WanCommands implements GfshCommand {
// gateway receivers : a member can have only one gateway receiver
ObjectName gatewayReceiverObjectName = MBeanJMXAdapter.getGatewayReceiverMBeanName(member);
if (gatewayReceiverObjectName != null) {
- GatewayReceiverMXBean receieverBean = null;
- receieverBean =
+ GatewayReceiverMXBean receiverBean;
+ receiverBean =
service.getMBeanProxy(gatewayReceiverObjectName, GatewayReceiverMXBean.class);
- if (receieverBean != null) {
- gatewayReceiverBeans.put(member.getId(), receieverBean);
+ if (receiverBean != null) {
+ gatewayReceiverBeans.put(member.getId(), receiverBean);
}
}
}
@@ -886,7 +883,7 @@ public class WanCommands implements GfshCommand {
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.STATUS_GATEWAYSENDER__MEMBER__HELP) String[] onMember) {
- Result result = null;
+ Result result;
if (senderId != null)
senderId = senderId.trim();
try {
@@ -894,7 +891,7 @@ public class WanCommands implements GfshCommand {
SystemManagementService service =
(SystemManagementService) ManagementService.getExistingManagementService(cache);
- GatewaySenderMXBean bean = null;
+ GatewaySenderMXBean bean;
CompositeResultData crd = ResultBuilder.createCompositeResultData();
TabularResultData availableSenderData =
@@ -944,7 +941,7 @@ public class WanCommands implements GfshCommand {
optionContext = ConverterHint.MEMBERIDNAME,
help = CliStrings.STATUS_GATEWAYRECEIVER__MEMBER__HELP) String[] onMember) {
- Result result = null;
+ Result result;
try {
InternalCache cache = getCache();
@@ -969,10 +966,10 @@ public class WanCommands implements GfshCommand {
for (DistributedMember member : dsMembers) {
ObjectName gatewayReceiverObjectName = MBeanJMXAdapter.getGatewayReceiverMBeanName(member);
if (gatewayReceiverObjectName != null) {
- GatewayReceiverMXBean receieverBean =
+ GatewayReceiverMXBean receiverBean =
service.getMBeanProxy(gatewayReceiverObjectName, GatewayReceiverMXBean.class);
- if (receieverBean != null) {
- buildReceiverStatus(member.getId(), receieverBean, availableReceiverData);
+ if (receiverBean != null) {
+ buildReceiverStatus(member.getId(), receiverBean, availableReceiverData);
continue;
}
}
@@ -989,19 +986,19 @@ public class WanCommands implements GfshCommand {
@CliCommand(value = CliStrings.DESTROY_GATEWAYSENDER,
help = CliStrings.DESTROY_GATEWAYSENDER__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_WAN)
- @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.GATEWAY)
public Result destroyGatewaySender(
@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
optionContext = ConverterHint.MEMBERGROUP,
help = CliStrings.DESTROY_GATEWAYSENDER__GROUP__HELP) String[] onGroups,
@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
optionContext = ConverterHint.MEMBERIDNAME,
- unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.DESTROY_GATEWAYSENDER__MEMBER__HELP) String[] onMember,
@CliOption(key = CliStrings.DESTROY_GATEWAYSENDER__ID, mandatory = true,
optionContext = ConverterHint.GATEWAY_SENDER_ID,
help = CliStrings.DESTROY_GATEWAYSENDER__ID__HELP) String id) {
- Result result = null;
+ Result result;
try {
GatewaySenderDestroyFunctionArgs gatewaySenderDestroyFunctionArgs =
new GatewaySenderDestroyFunctionArgs(id);
@@ -1128,7 +1125,7 @@ public class WanCommands implements GfshCommand {
private Result handleCommandResultException(CommandResultException crex) {
- Result result = null;
+ Result result;
if (crex.getResult() != null) {
result = crex.getResult();
} else {
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StartPulseCommand.java
----------------------------------------------------------------------
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 b5c6148..fbf32d8 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
@@ -16,6 +16,15 @@ package org.apache.geode.management.internal.cli.commands.lifecycle;
import static org.apache.geode.internal.Assert.assertState;
+import java.awt.Desktop;
+import java.io.IOException;
+import java.net.URI;
+
+import javax.management.ObjectName;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import org.apache.geode.SystemFailure;
import org.apache.geode.internal.lang.StringUtils;
import org.apache.geode.management.cli.CliMetaData;
@@ -25,13 +34,6 @@ import org.apache.geode.management.internal.cli.commands.GfshCommand;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
import org.apache.geode.management.internal.cli.shell.OperationInvoker;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import java.awt.Desktop;
-import java.io.IOException;
-import java.net.URI;
-import javax.management.ObjectName;
public class StartPulseCommand implements GfshCommand {
@@ -85,7 +87,7 @@ public class StartPulseCommand implements GfshCommand {
private void browse(URI uri) throws IOException {
assertState(Desktop.isDesktopSupported(),
- String.format(CliStrings.DESKSTOP_APP_RUN_ERROR_MESSAGE, System.getProperty("os.name")));
+ String.format(CliStrings.DESKTOP_APP_RUN_ERROR_MESSAGE, System.getProperty("os.name")));
Desktop.getDesktop().browse(uri);
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ContinuousQueryFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ContinuousQueryFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ContinuousQueryFunction.java
new file mode 100644
index 0000000..1f06a41
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ContinuousQueryFunction.java
@@ -0,0 +1,148 @@
+/*
+ * 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 java.io.Serializable;
+import java.util.Collection;
+import java.util.Iterator;
+import org.apache.geode.cache.CacheFactory;
+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.CacheServerImpl;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.cache.tier.sockets.AcceptorImpl;
+import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
+import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
+import org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID;
+import org.apache.geode.internal.cache.tier.sockets.ServerConnection;
+
+/**
+ * @since GemFire 8.0
+ */
+public class ContinuousQueryFunction implements Function, InternalEntity {
+ private static final long serialVersionUID = 1L;
+
+ public static final String ID = ContinuousQueryFunction.class.getName();
+
+ private InternalCache getCache() {
+ return (InternalCache) CacheFactory.getAnyInstance();
+ }
+
+ @Override
+ public void execute(FunctionContext context) {
+ try {
+ String clientID = (String) context.getArguments();
+ InternalCache cache = getCache();
+ if (cache.getCacheServers().size() > 0) {
+ CacheServerImpl server = (CacheServerImpl) cache.getCacheServers().iterator().next();
+ if (server != null) {
+ AcceptorImpl acceptorImpl = server.getAcceptor();
+ if (acceptorImpl != null) {
+ CacheClientNotifier cacheClientNotifier = acceptorImpl.getCacheClientNotifier();
+ if (cacheClientNotifier != null) {
+ Collection<CacheClientProxy> cacheClientProxySet =
+ cacheClientNotifier.getClientProxies();
+ ClientInfo clientInfo = null;
+ boolean foundClientinCCP = false;
+ Iterator<CacheClientProxy> it = cacheClientProxySet.iterator();
+ while (it.hasNext()) {
+
+ CacheClientProxy ccp = it.next();
+ if (ccp != null) {
+ String clientIdFromProxy = ccp.getProxyID().getDSMembership();
+ if (clientIdFromProxy != null && clientIdFromProxy.equals(clientID)) {
+ foundClientinCCP = true;
+ String durableId = ccp.getProxyID().getDurableId();
+ boolean isPrimary = ccp.isPrimary();
+ clientInfo = new ClientInfo(
+ (durableId != null && durableId.length() > 0 ? "Yes" : "No"),
+ (isPrimary == true
+ ? cache.getDistributedSystem().getDistributedMember().getId() : ""),
+ (isPrimary == false
+ ? cache.getDistributedSystem().getDistributedMember().getId() : ""));
+ break;
+
+ }
+ }
+ }
+
+ // try getting from server connections
+ if (foundClientinCCP == false) {
+ ServerConnection[] serverConnections = acceptorImpl.getAllServerConnectionList();
+
+ for (ServerConnection conn : serverConnections) {
+ ClientProxyMembershipID cliIdFrmProxy = conn.getProxyID();
+
+ if (clientID.equals(cliIdFrmProxy.getDSMembership())) {
+ String durableId = cliIdFrmProxy.getDurableId();
+ clientInfo =
+ new ClientInfo((durableId != null && durableId.length() > 0 ? "Yes" : "No"),
+ "N.A.", "N.A.");
+ }
+
+ }
+ }
+ context.getResultSender().lastResult(clientInfo);
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ context.getResultSender()
+ .lastResult("Exception in ContinuousQueryFunction =" + e.getMessage());
+ }
+ context.getResultSender().lastResult(null);
+ }
+
+ @Override
+ public String getId() {
+ return ContinuousQueryFunction.ID;
+ }
+
+ @Override
+ public boolean hasResult() {
+ return true;
+ }
+
+ @Override
+ public boolean optimizeForWrite() {
+ return false;
+ }
+
+ @Override
+ public boolean isHA() {
+ return false;
+ }
+
+ public class ClientInfo implements Serializable {
+ private static final long serialVersionUID = 1L;
+ public String isDurable;
+ public String primaryServer;
+ public String secondaryServer;
+
+ public ClientInfo(String IsClientDurable, String primaryServerId, String secondaryServerId) {
+ isDurable = IsClientDurable;
+ primaryServer = primaryServerId;
+ secondaryServer = secondaryServerId;
+ }
+
+ @Override
+ public String toString() {
+ return "ClientInfo [isDurable=" + isDurable + ", primaryServer=" + primaryServer
+ + ", secondaryServer=" + secondaryServer + "]";
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ContunuousQueryFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ContunuousQueryFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ContunuousQueryFunction.java
deleted file mode 100644
index 47890e1..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ContunuousQueryFunction.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.management.internal.cli.functions;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Iterator;
-import org.apache.geode.cache.CacheFactory;
-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.CacheServerImpl;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.cache.tier.sockets.AcceptorImpl;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
-import org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID;
-import org.apache.geode.internal.cache.tier.sockets.ServerConnection;
-
-/**
- * TODO: rename ContunuousQueryFunction
- *
- * @since GemFire 8.0
- */
-public class ContunuousQueryFunction implements Function, InternalEntity {
- private static final long serialVersionUID = 1L;
-
- public static final String ID = ContunuousQueryFunction.class.getName();
-
- private InternalCache getCache() {
- return (InternalCache) CacheFactory.getAnyInstance();
- }
-
- @Override
- public void execute(FunctionContext context) {
- try {
- String clientID = (String) context.getArguments();
- InternalCache cache = getCache();
- if (cache.getCacheServers().size() > 0) {
- CacheServerImpl server = (CacheServerImpl) cache.getCacheServers().iterator().next();
- if (server != null) {
- AcceptorImpl acceptorImpl = server.getAcceptor();
- if (acceptorImpl != null) {
- CacheClientNotifier cacheClientNotifier = acceptorImpl.getCacheClientNotifier();
- if (cacheClientNotifier != null) {
- Collection<CacheClientProxy> cacheClientProxySet =
- cacheClientNotifier.getClientProxies();
- ClientInfo clientInfo = null;
- boolean foundClientinCCP = false;
- Iterator<CacheClientProxy> it = cacheClientProxySet.iterator();
- while (it.hasNext()) {
-
- CacheClientProxy ccp = it.next();
- if (ccp != null) {
- String clientIdFromProxy = ccp.getProxyID().getDSMembership();
- if (clientIdFromProxy != null && clientIdFromProxy.equals(clientID)) {
- foundClientinCCP = true;
- String durableId = ccp.getProxyID().getDurableId();
- boolean isPrimary = ccp.isPrimary();
- clientInfo = new ClientInfo(
- (durableId != null && durableId.length() > 0 ? "Yes" : "No"),
- (isPrimary == true
- ? cache.getDistributedSystem().getDistributedMember().getId() : ""),
- (isPrimary == false
- ? cache.getDistributedSystem().getDistributedMember().getId() : ""));
- break;
-
- }
- }
- }
-
- // try getting from server connections
- if (foundClientinCCP == false) {
- ServerConnection[] serverConnections = acceptorImpl.getAllServerConnectionList();
-
- for (ServerConnection conn : serverConnections) {
- ClientProxyMembershipID cliIdFrmProxy = conn.getProxyID();
-
- if (clientID.equals(cliIdFrmProxy.getDSMembership())) {
- String durableId = cliIdFrmProxy.getDurableId();
- clientInfo =
- new ClientInfo((durableId != null && durableId.length() > 0 ? "Yes" : "No"),
- "N.A.", "N.A.");
- }
-
- }
- }
- context.getResultSender().lastResult(clientInfo);
- }
- }
- }
- }
- } catch (Exception e) {
- context.getResultSender()
- .lastResult("Exception in ContunuousQueryFunction =" + e.getMessage());
- }
- context.getResultSender().lastResult(null);
- }
-
- @Override
- public String getId() {
- return ContunuousQueryFunction.ID;
- }
-
- @Override
- public boolean hasResult() {
- return true;
- }
-
- @Override
- public boolean optimizeForWrite() {
- return false;
- }
-
- @Override
- public boolean isHA() {
- return false;
- }
-
- public class ClientInfo implements Serializable {
- private static final long serialVersionUID = 1L;
- public String isDurable;
- public String primaryServer;
- public String secondaryServer;
-
- public ClientInfo(String IsClientDurable, String primaryServerId, String secondaryServerId) {
- isDurable = IsClientDurable;
- primaryServer = primaryServerId;
- secondaryServer = secondaryServerId;
- }
-
- @Override
- public String toString() {
- return "ClientInfo [isDurable=" + isDurable + ", primaryServer=" + primaryServer
- + ", secondaryServer=" + secondaryServer + "]";
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionFunctionArgs.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionFunctionArgs.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionFunctionArgs.java
index 573b82e..3af79eb 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionFunctionArgs.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionFunctionArgs.java
@@ -13,12 +13,6 @@
* the License.
*/
-/**
- * Used to carry arguments between gfsh region command implementations and the functions that do the
- * work for those commands.
- *
- * @since GemFire 7.0
- */
package org.apache.geode.management.internal.cli.functions;
import java.io.Serializable;
@@ -35,6 +29,12 @@ import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.management.internal.cli.CliUtil;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
+/**
+ * Used to carry arguments between gfsh region command implementations and the functions that do the
+ * work for those commands.
+ *
+ * @since GemFire 7.0
+ */
public class RegionFunctionArgs implements Serializable {
private static final long serialVersionUID = -5158224572470173267L;
@@ -122,7 +122,7 @@ public class RegionFunctionArgs implements Serializable {
this.enableSubscriptionConflation = enableSubscriptionConflation;
}
if (cacheListeners != null) {
- this.cacheListeners = new LinkedHashSet<String>();
+ this.cacheListeners = new LinkedHashSet<>();
this.cacheListeners.addAll(Arrays.asList(cacheListeners));
} else {
this.cacheListeners = null;
@@ -130,13 +130,13 @@ public class RegionFunctionArgs implements Serializable {
this.cacheLoader = cacheLoader;
this.cacheWriter = cacheWriter;
if (asyncEventQueueIds != null) {
- this.asyncEventQueueIds = new LinkedHashSet<String>();
+ this.asyncEventQueueIds = new LinkedHashSet<>();
this.asyncEventQueueIds.addAll(Arrays.asList(asyncEventQueueIds));
} else {
this.asyncEventQueueIds = null;
}
if (gatewaySenderIds != null) {
- this.gatewaySenderIds = new LinkedHashSet<String>();
+ this.gatewaySenderIds = new LinkedHashSet<>();
this.gatewaySenderIds.addAll(Arrays.asList(gatewaySenderIds));
} else {
this.gatewaySenderIds = null;
@@ -527,7 +527,7 @@ public class RegionFunctionArgs implements Serializable {
}
public ExpirationAttributes convertToExpirationAttributes() {
- ExpirationAttributes expirationAttr = null;
+ ExpirationAttributes expirationAttr;
if (action != null) {
expirationAttr = new ExpirationAttributes(time, action);
} else {
@@ -590,8 +590,8 @@ public class RegionFunctionArgs implements Serializable {
}
}
- public static enum ExpirationFor {
- REGION_IDLE, REGION_TTL, ENTRY_IDLE, ENTRY_TTL;
+ public enum ExpirationFor {
+ REGION_IDLE, REGION_TTL, ENTRY_IDLE, ENTRY_TTL
}
}
@@ -615,7 +615,7 @@ public class RegionFunctionArgs implements Serializable {
private String partitionResolver;
private boolean hasPartitionAttributes;
- private final Set<String> userSpecifiedPartitionAttributes = new HashSet<String>();
+ private final Set<String> userSpecifiedPartitionAttributes = new HashSet<>();
public PartitionArgs(String prColocatedWith, Integer prLocalMaxMemory, Long prRecoveryDelay,
Integer prRedundantCopies, Long prStartupRecoveryDelay, Long prTotalMaxMemory,
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/UserFunctionExecution.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/UserFunctionExecution.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/UserFunctionExecution.java
index 630c2bc..1f9a607 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/UserFunctionExecution.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/UserFunctionExecution.java
@@ -17,7 +17,6 @@ package org.apache.geode.management.internal.cli.functions;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-import java.util.concurrent.CancellationException;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
@@ -25,7 +24,6 @@ import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
-import org.apache.geode.cache.execute.FunctionException;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;
@@ -61,7 +59,7 @@ public class UserFunctionExecution implements Function, InternalEntity {
if (argumentsString != null && argumentsString.length() > 0) {
functionArgs = argumentsString.split(",");
}
- Set<String> filters = new HashSet<String>();
+ Set<String> filters = new HashSet<>();
ResultCollector resultCollectorInstance = null;
if (resultCollectorName != null && resultCollectorName.length() > 0) {
resultCollectorInstance = (ResultCollector) ClassPathLoader.getLatest()
@@ -94,29 +92,29 @@ public class UserFunctionExecution implements Function, InternalEntity {
if (functionArgs != null && functionArgs.length > 0) {
execution = execution.setArguments(functionArgs);
}
- if (filters != null && filters.size() > 0) {
+ if (filters.size() > 0) {
execution = execution.withFilter(filters);
}
List<Object> results = (List<Object>) execution.execute(function).getResult();
- StringBuilder resultMessege = new StringBuilder();
+ StringBuilder resultMessage = new StringBuilder();
if (results != null) {
for (Object resultObj : results) {
if (resultObj != null) {
if (resultObj instanceof String) {
- resultMessege.append(((String) resultObj));
- resultMessege.append(GfshParser.LINE_SEPARATOR);
+ resultMessage.append(((String) resultObj));
+ resultMessage.append(GfshParser.LINE_SEPARATOR);
} else if (resultObj instanceof Exception) {
- resultMessege.append(((IllegalArgumentException) resultObj).getMessage());
+ resultMessage.append(((IllegalArgumentException) resultObj).getMessage());
} else {
- resultMessege.append(resultObj);
- resultMessege.append(GfshParser.LINE_SEPARATOR);
+ resultMessage.append(resultObj);
+ resultMessage.append(GfshParser.LINE_SEPARATOR);
}
}
}
}
- context.getResultSender().lastResult(resultMessege);
+ context.getResultSender().lastResult(resultMessage);
} else {
context.getResultSender()
.lastResult(CliStrings.format(
@@ -126,27 +124,7 @@ public class UserFunctionExecution implements Function, InternalEntity {
}
}
- } catch (ClassNotFoundException e) {
- context.getResultSender()
- .lastResult(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__RESULT_COLLECTOR_0_NOT_FOUND_ERROR_1,
- resultCollectorName, e.getMessage()));
- } catch (FunctionException e) {
- context.getResultSender()
- .lastResult(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_ON_MEMBER_1_DETAILS_2,
- functionId, member.getId(), e.getMessage()));
- } catch (CancellationException e) {
- context.getResultSender()
- .lastResult(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_ON_MEMBER_1_DETAILS_2,
- functionId, member.getId(), e.getMessage()));
- } catch (InstantiationException e) {
- context.getResultSender()
- .lastResult(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__RESULT_COLLECTOR_0_NOT_FOUND_ERROR_1,
- resultCollectorName, e.getMessage()));
- } catch (IllegalAccessException e) {
+ } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
context.getResultSender()
.lastResult(CliStrings.format(
CliStrings.EXECUTE_FUNCTION__MSG__RESULT_COLLECTOR_0_NOT_FOUND_ERROR_1,
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
index 0f74edd..3d4d53f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
@@ -140,7 +140,7 @@ public class CliStrings {
public static final String TOPIC_GFSH__DESC = "The Geode Shell";
public static final String TOPIC_SHARED_CONFIGURATION = "Cluster Configuration";
public static final String TOPIC_SHARED_CONFIGURATION_HELP =
- "Configuration for cluster and various groups. It consists of cache.xml, geode properties and deployed jars.\nChanges due to gfshs command are persisted to the locator hosting the cluster configuration service.";
+ "Configuration for cluster and various groups. It consists of cache.xml, geode properties and deployed jars.\nChanges due to gfsh command are persisted to the locator hosting the cluster configuration service.";
public static final String TOPIC_LOGS = "Logs";
public static final String TOPIC_LOGS__DESC = "Generate log contents as per the need";
public static final String TOPIC_CLIENT = "Client";
@@ -150,7 +150,7 @@ public class CliStrings {
* ********* String Constants other than command name, options & help ******
* *************************************************************************/
- public static final String DESKSTOP_APP_RUN_ERROR_MESSAGE =
+ public static final String DESKTOP_APP_RUN_ERROR_MESSAGE =
"Running desktop applications is not supported on %1$s.";
public static final String GEODE_HOME_NOT_FOUND_ERROR_MESSAGE =
"The GEODE environment variable was not defined. Please set the GEODE environment variable to the directory where GEODE is installed.";
@@ -203,7 +203,7 @@ public class CliStrings {
public static final String NO_CLIENT_FOUND = "No client found on this server";
public static final String NO_CLIENT_FOUND_WITH_CLIENT_ID =
"No client found with client-id : {0}";
- public static final String ACTION_SUCCCEEDED_ON_MEMBER = "{0} on following members.";
+ public static final String ACTION_SUCCEEDED_ON_MEMBER = "{0} on following members.";
public static final String OCCURRED_ON_MEMBERS = "Occurred on members";
public static final String SHARED_CONFIGURATION_NOT_STARTED =
"Cluster configuration service is enabled but has not started yet.";
@@ -216,8 +216,8 @@ public class CliStrings {
public static final String GFSHPARSER__MSG__REQUIRED_ARGUMENT_0 = "Required Argument: \"{0}\"";
public static final String GFSHPARSER__MSG__VALUE_REQUIRED_FOR_OPTION_0 =
"Value is required for parameter \"{0}\"";
- public static final String GFSHPARSER__MSG__AMBIGIOUS_COMMAND_0_FOR_ASSISTANCE_USE_1_OR_HINT_HELP =
- "Ambigious command \"{0}\" (for assistance press \"{1}\" or type \"hint\" or \"help <command name>\" & then hit ENTER)";
+ public static final String GFSHPARSER__MSG__AMBIGUOUS_COMMAND_0_FOR_ASSISTANCE_USE_1_OR_HINT_HELP =
+ "Ambiguous command \"{0}\" (for assistance press \"{1}\" or type \"hint\" or \"help <command name>\" & then hit ENTER)";
public static final String GFSHPARSER__MSG__COMMAND_ARGUMENT_0_IS_REQUIRED_USE_HELP =
"Command parameter \"{0}\" is required. Use \"help <command name>\" for assistance.";
public static final String GFSHPARSER__MSG__COMMAND_OPTION_0_IS_REQUIRED_USE_HELP =
@@ -583,7 +583,7 @@ public class CliStrings {
"The gfsecurity.properties file for configuring gfsh to connect to the Locator/Manager. The file's path can be absolute or relative to gfsh directory.";
public static final String CONNECT__USE_SSL = "use-ssl";
public static final String CONNECT__USE_SSL__HELP =
- "Whether to use SSL for communication with Locator and/or JMX Manager. If set to \"true\", will also read \"gfsecurity.properties\". SSL Options take precedence over proeprties file. If none are specified, defaults will be used. The default value for this options is \"false\".";
+ "Whether to use SSL for communication with Locator and/or JMX Manager. If set to \"true\", will also read \"gfsecurity.properties\". SSL Options take precedence over properties file. If none are specified, defaults will be used. The default value for this options is \"false\".";
public static final String CONNECT__MSG__CONNECTING_TO_MANAGER_AT_0 =
"Connecting to Manager at {0} ..";
public static final String CONNECT__MSG__CONNECTING_TO_MANAGER_HTTP_SERVICE_AT_0 =
@@ -1326,7 +1326,7 @@ public class CliStrings {
public static final String EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_MEMBER_1_ON_REGION_2_DETAILS_3 =
"While executing function : {0} on member : {1} one region : {2} error occurred : {3}";
public static final String EXECUTE_FUNCTION__MSG__MEMBER_SHOULD_NOT_HAVE_FILTER_FOR_EXECUTION =
- "Filters for executing on \"member\"/\"mebers of group\" is not supported.";
+ "Filters for executing on \"member\"/\"members of group\" is not supported.";
/* exit command */
public static final String EXIT = "exit";
@@ -1366,7 +1366,7 @@ public class CliStrings {
public static final String EXPORT_DATA__MEMBER__NOT__FOUND = "Member {0} not found";
public static final String EXPORT_DATA__REGION__NOT__FOUND = "Region {0} not found";
public static final String EXPORT_DATA__SUCCESS__MESSAGE =
- "Data succesfully exported from region : {0} to file : {1} on host : {2}";
+ "Data successfully exported from region : {0} to file : {1} on host : {2}";
/* export logs command */
public static final String EXPORT_LOGS = "export logs";
@@ -1607,7 +1607,7 @@ public class CliStrings {
public static final String DESCRIBE_CLIENT_COLUMN_DURABLE = "Is Durable";
public static final String DESCRIBE_CLIENT_MIN_CONN = "Minimum Connections";
public static final String DESCRIBE_CLIENT_MAX_CONN = "Maximum Connections";
- public static final String DESCRIBE_CLIENT_REDUDANCY = "Redudancy";
+ public static final String DESCRIBE_CLIENT_REDUNDANCY = "Redundancy";
public static final String DESCRIBE_CLIENT_CQs = "Num of CQs";
@@ -1722,7 +1722,7 @@ public class CliStrings {
"Group of members on which to run the netstat command.";
public static final String NETSTAT__FILE = "file";
public static final String NETSTAT__FILE__HELP =
- "Text file to which output from the netstat command will be written. A \".txt\" extention will be added if it's not already a part of the specified name.";
+ "Text file to which output from the netstat command will be written. A \".txt\" extension will be added if it's not already a part of the specified name.";
public static final String NETSTAT__WITHLSOF = "with-lsof";
public static final String NETSTAT__WITHLSOF__HELP =
"Whether lsof (list open files) command output should also be displayed. Not applicable for \"Microsoft Windows(TM)\" hosts.";
@@ -1848,9 +1848,9 @@ public class CliStrings {
public static final String REBALANCE__MSG__NO_REBALANCING_REGIONS_ON_DS =
"Distributed system has no regions that can be rebalanced";
public static final String REBALANCE__MSG__EXCEPTION_IN_REBALANCE_FOR_MEMBER_0_Exception =
- "Excpetion occurred while rebalancing on member : {0} . Exception is ";
+ "Exception occurred while rebalancing on member : {0} . Exception is ";
public static final String REBALANCE__MSG__EXCEPTION_IN_REBALANCE_FOR_MEMBER_0_Exception_1 =
- "Excpetion occurred while rebalancing on member : {0} . Exception is : {1}";
+ "Exception occurred while rebalancing on member : {0} . Exception is : {1}";
public static final String REBALANCE__MSG__ERROR_IN_RETRIEVING_MBEAN =
"Could not retrieve MBean for region : {0}";
public static final String REBALANCE__MSG__NO_EXECUTION_FOR_REGION_0_ON_MEMBERS_1 =
@@ -1864,7 +1864,7 @@ public class CliStrings {
"Rebalance will continue in background";
public static final String REBALANCE__MSG__REGION_NOT_ASSOCIATED_WITH_MORE_THAN_ONE_MEMBER =
"No regions associated with more than 1 members";
- public static final String REBALANCE__MSG__EXCEPTION_OCCRED_WHILE_REBALANCING_0 =
+ public static final String REBALANCE__MSG__EXCEPTION_OCCURRED_WHILE_REBALANCING_0 =
"Exception occurred while rebelancing. Reason : {0}";
/* remove command */
@@ -1954,7 +1954,7 @@ public class CliStrings {
+ "3. APP_LAST_EXIT_STATUS Numeric value for last command exit status. One of: 0 (success), 1 (error), 2 (crash) (read only)\n"
+ "4. APP_COLLECTION_LIMIT Number of items in the embedded collection of a result to be iterated. Valid values are: 1-100.\n"
+ "5. APP_QUERY_RESULTS_DISPLAY_MODE How command results should be shown. Valid values are: table and catalog.\n"
- + "6. APP_QUIET_EXECUTION. Whether commands should be excuted in quiet mode. Valid values are: true and false.\n";
+ + "6. APP_QUIET_EXECUTION. Whether commands should be executed in quiet mode. Valid values are: true and false.\n";
/* 'sh' command */
public static final String SH = "sh";
@@ -2593,11 +2593,11 @@ public class CliStrings {
public static final String START_SERVER__MAX__CONNECTIONS = "max-connections";
public static final String START_SERVER__MAX__CONNECTIONS__HELP =
- "Sets the maxium number of client connections allowed. When the maximum is reached the cache server will stop accepting connections";
+ "Sets the maximum number of client connections allowed. When the maximum is reached the cache server will stop accepting connections";
public static final String START_SERVER__MAX__THREADS = "max-threads";
public static final String START_SERVER__MAX__THREADS__HELP =
- "Sets the maxium number of threads allowed in this cache server to service client requests. The default of 0 causes the cache server to dedicate a thread for every client connection";
+ "Sets the maximum number of threads allowed in this cache server to service client requests. The default of 0 causes the cache server to dedicate a thread for every client connection";
public static final String START_SERVER__MAX__MESSAGE__COUNT = "max-message-count";
public static final String START_SERVER__MAX__MESSAGE__COUNT__HELP =
@@ -2699,7 +2699,7 @@ public class CliStrings {
public static final String STATUS_SERVER__PID__HELP =
"Process ID (PID) of the running Geode Cache Server. Deprecated: Since Geode1.2. Requires the JDK tools.jar which is not included on the classpath by default. Use --dir instead.";
- /* stop gateway-reciver */
+ /* stop gateway-receiver */
public static final String STOP_GATEWAYRECEIVER = "stop gateway-receiver";
public static final String STOP_GATEWAYRECEIVER__HELP =
"Stop the Gateway Receiver on a member or members.";
@@ -2797,7 +2797,7 @@ public class CliStrings {
public static final String UPGRADE_OFFLINE_DISK_STORE__UPGRADE_ATTEMPTED_BUT_NOTHING_TO_UPGRADE =
"Upgradation was attempted but nothing to upgrade.";
public static final String UPGRADE_OFFLINE_DISK_STORE__ERROR_WHILE_UPGRADATION_REASON_0 =
- "Error occurred while perfoming disk store upgrade. Reason: \"{0}\"";
+ "Error occurred while performing disk store upgrade. Reason: \"{0}\"";
public static final String UPGRADE_OFFLINE_DISK_STORE__MSG__CANNOT_LOCATE_0_DISKSTORE_IN_1 =
"Cannot locate disk store \"{0}\" in directory : \"{1}\"";
public static final String UPGRADE_OFFLINE_DISK_STORE__MSG__DISKSTORE_IN_USE_COMPACT_DISKSTORE_CAN_BE_USED =
@@ -2914,7 +2914,7 @@ public class CliStrings {
public static final String GATEWAY_RECEIVER_IS_NOT_RUNNING_ON_MEMBER_0 =
"GatewayReceiver is not running on member {0}";
public static final String GATEWAYS_ARE_NOT_AVAILABLE_IN_CLUSTER =
- "GatewaySenders or GatewayRecievers are not available in cluster";
+ "GatewaySenders or GatewayReceivers are not available in cluster";
public static final String GATEWAY_SENDER_0_COULD_NOT_BE_INVOKED_DUE_TO_1 =
"Could not invoke start gateway sender {0} operation on members due to {1}";
public static final String GATEWAY_SENDER_0_COULD_NOT_BE_STARTED_ON_MEMBER_DUE_TO_1 =
@@ -3010,9 +3010,9 @@ public class CliStrings {
public static final String COUNT_DURABLE_CQ_EVENTS__NO__CQS__REGISTERED =
"No cq's registered on this member";
public static final String COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CQ =
- "subcription-queue-size for durable-cq : \"{0}\".";
+ "subscription-queue-size for durable-cq : \"{0}\".";
public static final String COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT =
- "subcription-queue-size for durable-client : \"{0}\".";
+ "subscription-queue-size for durable-client : \"{0}\".";
/***
* Cluster Configuration commands
@@ -3180,6 +3180,6 @@ public class CliStrings {
}
- public static final String IGNORE_INTERCEPTORS = "ignoreInterCeptors";
+ public static final String IGNORE_INTERCEPTORS = "ignoreInterceptors";
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandProcessor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandProcessor.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandProcessor.java
index e9c2736..2464b00 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandProcessor.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/remote/CommandProcessor.java
@@ -14,6 +14,14 @@
*/
package org.apache.geode.management.internal.cli.remote;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.Properties;
+
+import org.springframework.shell.core.Parser;
+import org.springframework.shell.event.ParseResult;
+
import org.apache.geode.internal.security.SecurityService;
import org.apache.geode.internal.security.SecurityServiceFactory;
import org.apache.geode.management.cli.CommandProcessingException;
@@ -27,13 +35,6 @@ import org.apache.geode.management.internal.cli.util.CommentSkipHelper;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.NotAuthorizedException;
import org.apache.geode.security.ResourcePermission;
-import org.springframework.shell.core.Parser;
-import org.springframework.shell.event.ParseResult;
-
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.util.Map;
-import java.util.Properties;
/**
* @since GemFire 7.0
@@ -85,7 +86,7 @@ public class CommandProcessor {
}
public Result executeCommand(CommandStatement cmdStmt) {
- Object result = null;
+ Object result;
Result commandResult = null;
CommentSkipHelper commentSkipper = new CommentSkipHelper();
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/main/java/org/apache/geode/management/internal/security/MBeanServerWrapper.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/security/MBeanServerWrapper.java b/geode-core/src/main/java/org/apache/geode/management/internal/security/MBeanServerWrapper.java
index 47260bc..7c3ecb8 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/security/MBeanServerWrapper.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/security/MBeanServerWrapper.java
@@ -14,17 +14,9 @@
*/
package org.apache.geode.management.internal.security;
-import org.apache.commons.lang.StringUtils;
-import org.apache.geode.internal.security.SecurityService;
-import org.apache.geode.management.internal.ManagementConstants;
-import org.apache.geode.security.GemFireSecurityException;
-import org.apache.geode.security.ResourcePermission;
-import org.apache.geode.security.ResourcePermission.Resource;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Target;
-
import java.io.ObjectInputStream;
import java.util.Set;
+
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
@@ -51,6 +43,16 @@ import javax.management.ReflectionException;
import javax.management.loading.ClassLoaderRepository;
import javax.management.remote.MBeanServerForwarder;
+import org.apache.commons.lang.StringUtils;
+
+import org.apache.geode.internal.security.SecurityService;
+import org.apache.geode.management.internal.ManagementConstants;
+import org.apache.geode.security.GemFireSecurityException;
+import org.apache.geode.security.ResourcePermission;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
/**
* This class intercepts all MBean requests for GemFire MBeans and passed it to
* ManagementInterceptor for authorization
@@ -217,15 +219,13 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
ResourcePermission ctx = getOperationContext(name, operationName, true);
this.securityService.authorize(ctx);
- Object result = mbs.invoke(name, operationName, params, signature);
-
- return result;
+ return mbs.invoke(name, operationName, params, signature);
}
// TODO: cache this
private ResourcePermission getOperationContext(ObjectName objectName, String featureName,
boolean isOp) throws InstanceNotFoundException, ReflectionException {
- MBeanInfo beanInfo = null;
+ MBeanInfo beanInfo;
try {
beanInfo = mbs.getMBeanInfo(objectName);
} catch (IntrospectionException e) {
@@ -238,7 +238,7 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
// find the context in the beanInfo if defined in the class level
result = getOperationContext(beanInfo.getDescriptor(), result);
- MBeanFeatureInfo[] featureInfos = null;
+ MBeanFeatureInfo[] featureInfos;
if (isOp) {
featureInfos = beanInfo.getOperations();
} else {
@@ -262,8 +262,7 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
String targetCode = (String) descriptor.getFieldValue("target");
if (resource != null && operationCode != null) {
if (StringUtils.isBlank(targetCode)) {
- return new ResourcePermission(Resource.valueOf(resource), Operation.valueOf(operationCode),
- targetCode);
+ return new ResourcePermission(Resource.valueOf(resource), Operation.valueOf(operationCode));
} else {
return new ResourcePermission(Resource.valueOf(resource), Operation.valueOf(operationCode),
Target.valueOf(targetCode).getName());
@@ -358,21 +357,20 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
@SuppressWarnings("deprecation")
@Override
- public ObjectInputStream deserialize(ObjectName name, byte[] data)
- throws InstanceNotFoundException, OperationsException {
+ public ObjectInputStream deserialize(ObjectName name, byte[] data) throws OperationsException {
return mbs.deserialize(name, data);
}
@Override
public ObjectInputStream deserialize(String className, byte[] data)
throws OperationsException, ReflectionException {
- return deserialize(className, data);
+ return mbs.deserialize(className, data);
}
@SuppressWarnings("deprecation")
@Override
public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] data)
- throws InstanceNotFoundException, OperationsException, ReflectionException {
+ throws OperationsException, ReflectionException {
return mbs.deserialize(className, loaderName, data);
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/MemberMBeanAttributesDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/MemberMBeanAttributesDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/MemberMBeanAttributesDUnitTest.java
index 94b049e..97f766e 100644
--- a/geode-core/src/test/java/org/apache/geode/management/MemberMBeanAttributesDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/MemberMBeanAttributesDUnitTest.java
@@ -14,18 +14,15 @@
*/
package org.apache.geode.management;
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.lang.management.ManagementFactory;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
@@ -37,6 +34,8 @@ import org.apache.geode.internal.process.ProcessUtils;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.FlakyTest;
/**
* This test class checks around 89 attributes of Member MBeans
@@ -81,8 +80,8 @@ public class MemberMBeanAttributesDUnitTest extends ManagementTestBase {
@Test
public void testReplRegionAttributes() throws Exception {
initManagement(false);
- setupForReplicateRegonAttributes(managedNodeList.get(0), 1);
- setupForReplicateRegonAttributes(managedNodeList.get(1), 201);
+ setupForReplicateRegionAttributes(managedNodeList.get(0), 1);
+ setupForReplicateRegionAttributes(managedNodeList.get(1), 201);
sample(managedNodeList.get(1));// Sample now
isReplicatedRegionAttrsOK(managedNodeList.get(1));
@@ -92,7 +91,7 @@ public class MemberMBeanAttributesDUnitTest extends ManagementTestBase {
@Test
public void testPRRegionAttributes() throws Exception {
initManagement(false);
- setupForPartitionedRegonAttributes(managedNodeList.get(0), 1);
+ setupForPartitionedRegionAttributes(managedNodeList.get(0), 1);
sample(managedNodeList.get(0));// Sample now
isPartitionedRegionAttrsOK(managedNodeList.get(0));
@@ -112,7 +111,7 @@ public class MemberMBeanAttributesDUnitTest extends ManagementTestBase {
}
- public void setupForReplicateRegonAttributes(VM vm1, final int offset) throws Exception {
+ public void setupForReplicateRegionAttributes(VM vm1, final int offset) {
vm1.invoke(new SerializableRunnable("Create Cache") {
public void run() {
GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
@@ -144,7 +143,7 @@ public class MemberMBeanAttributesDUnitTest extends ManagementTestBase {
}
- public void setupForPartitionedRegonAttributes(VM vm1, final int offset) throws Exception {
+ public void setupForPartitionedRegionAttributes(VM vm1, final int offset) {
vm1.invoke(new SerializableRunnable("Create Cache") {
public void run() {
GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
@@ -177,7 +176,7 @@ public class MemberMBeanAttributesDUnitTest extends ManagementTestBase {
* @throws Exception
*/
@SuppressWarnings("serial")
- public void isPartitionedRegionAttrsOK(VM vm1) throws Exception {
+ public void isPartitionedRegionAttrsOK(VM vm1) {
vm1.invoke(new SerializableRunnable("Create Cache") {
public void run() {
MemberMXBean bean = managementService.getMemberMXBean();
@@ -197,7 +196,7 @@ public class MemberMBeanAttributesDUnitTest extends ManagementTestBase {
* @throws Exception
*/
@SuppressWarnings("serial")
- public void isReplicatedRegionAttrsOK(VM vm1) throws Exception {
+ public void isReplicatedRegionAttrsOK(VM vm1) {
vm1.invoke(new SerializableRunnable("Create Cache") {
public void run() {
MemberMXBean bean = managementService.getMemberMXBean();
@@ -220,7 +219,7 @@ public class MemberMBeanAttributesDUnitTest extends ManagementTestBase {
* @throws Exception
*/
@SuppressWarnings("serial")
- public void isOSRelatedAttrsOK(VM vm1) throws Exception {
+ public void isOSRelatedAttrsOK(VM vm1) {
vm1.invoke(new SerializableRunnable("Create Cache") {
public void run() {
MemberMXBean bean = managementService.getMemberMXBean();
@@ -259,7 +258,7 @@ public class MemberMBeanAttributesDUnitTest extends ManagementTestBase {
}
@SuppressWarnings("serial")
- public void isConfigRelatedAttrsOK(VM vm1) throws Exception {
+ public void isConfigRelatedAttrsOK(VM vm1) {
vm1.invoke(new SerializableRunnable("Create Cache") {
public void run() {
MemberMXBean bean = managementService.getMemberMXBean();
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/bean/stats/MemberLevelStatsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/bean/stats/MemberLevelStatsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/bean/stats/MemberLevelStatsJUnitTest.java
index 4a6d16a..e430b49 100644
--- a/geode-core/src/test/java/org/apache/geode/management/bean/stats/MemberLevelStatsJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/bean/stats/MemberLevelStatsJUnitTest.java
@@ -30,12 +30,12 @@ import org.apache.geode.distributed.internal.DistributionStats;
import org.apache.geode.distributed.internal.locks.DLockStats;
import org.apache.geode.internal.NanoTimer;
import org.apache.geode.internal.OSProcess;
-import org.apache.geode.internal.statistics.VMStatsContract;
import org.apache.geode.internal.cache.CachePerfStats;
import org.apache.geode.internal.cache.DiskStoreStats;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.PartitionedRegionStats;
import org.apache.geode.internal.cache.execute.FunctionServiceStats;
+import org.apache.geode.internal.statistics.VMStatsContract;
import org.apache.geode.internal.stats50.VMStats50;
import org.apache.geode.management.ManagementService;
import org.apache.geode.management.internal.beans.MemberMBeanBridge;
@@ -165,7 +165,7 @@ public class MemberLevelStatsJUnitTest extends MBeanStatsTestCase {
sample();
- assertEquals(1, getInitialImagesInProgres());
+ assertEquals(1, getInitialImagesInProgress());
cachePerfStats.endGetInitialImage(startGIITime);
cachePerfStats.endCacheListenerCall(startCacheListenerTime);
cachePerfStats.endCacheWriterCall(startCacheWriterTime);
@@ -389,8 +389,8 @@ public class MemberLevelStatsJUnitTest extends MBeanStatsTestCase {
return bridge.getInitialImageTime();
}
- private int getInitialImagesInProgres() {
- return bridge.getInitialImagesInProgres();
+ private int getInitialImagesInProgress() {
+ return bridge.getInitialImagesInProgress();
}
private float getBytesReceivedRate() {
[2/6] geode git commit: GEODE-2919: Provide finer grained security
Posted by js...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
index 155b1ad..c281080 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
@@ -16,21 +16,16 @@
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.verify;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
-import org.mockito.ArgumentCaptor;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs;
import org.apache.geode.test.dunit.rules.GfshParserRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
@@ -49,17 +44,7 @@ public class CreateAlterDestroyRegionCommandsTest {
doReturn(cache).when(spy).getCache();
doReturn(dsMBean).when(spy).getDSMBean(cache);
- parser.executeLastCommandWithInstance(spy);
-
- ArgumentCaptor<RegionFunctionArgs> argsCaptor =
- ArgumentCaptor.forClass(RegionFunctionArgs.class);
-
- verify(spy).validateRegionFunctionArgs(any(), argsCaptor.capture());
-
- RegionFunctionArgs args = argsCaptor.getValue();
- assertThat(args.getPartitionResolver()).isEqualTo("Foo");
-
- assertThatThrownBy(() -> spy.validateRegionFunctionArgs(cache, args))
+ assertThatThrownBy(() -> parser.executeLastCommandWithInstance(spy))
.hasMessageContaining("Foo is an invalid Partition Resolver");
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthenticationJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthenticationJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthenticationJUnitTest.java
index 9a1605a..1d98087 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthenticationJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthenticationJUnitTest.java
@@ -16,28 +16,26 @@ package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
-import org.apache.geode.management.CacheServerMXBean;
-import org.apache.geode.security.TestSecurityManager;
-import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
-import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
-import org.apache.geode.test.dunit.rules.ServerStarterRule;
-import org.apache.geode.test.junit.categories.IntegrationTest;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
+import org.apache.geode.management.CacheServerMXBean;
+import org.apache.geode.security.SimpleTestSecurityManager;
+import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
+import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
+import org.apache.geode.test.dunit.rules.ServerStarterRule;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+
@Category(IntegrationTest.class)
public class CacheServerMBeanAuthenticationJUnitTest {
private CacheServerMXBean bean;
@ClassRule
public static ServerStarterRule server = new ServerStarterRule().withJMXManager()
- .withProperty(SECURITY_MANAGER, TestSecurityManager.class.getName())
- .withProperty(TestSecurityManager.SECURITY_JSON,
- "org/apache/geode/management/internal/security/cacheServer.json")
- .withAutoStart();
+ .withProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName()).withAutoStart();
@Rule
public MBeanServerConnectionRule connectionRule =
@@ -49,7 +47,7 @@ public class CacheServerMBeanAuthenticationJUnitTest {
}
@Test
- @ConnectionConfiguration(user = "data-admin", password = "1234567")
+ @ConnectionConfiguration(user = "data,cluster", password = "data,cluster")
public void testAllAccess() throws Exception {
bean.removeIndex("foo");
bean.fetchLoadProbe();
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthorizationJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthorizationJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthorizationJUnitTest.java
index c7c76f6..de88614 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthorizationJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanAuthorizationJUnitTest.java
@@ -17,6 +17,13 @@ package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import org.assertj.core.api.SoftAssertions;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.management.CacheServerMXBean;
import org.apache.geode.security.TestSecurityManager;
import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
@@ -24,11 +31,6 @@ import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
@Category({IntegrationTest.class, SecurityTest.class})
public class CacheServerMBeanAuthorizationJUnitTest {
@@ -58,8 +60,10 @@ public class CacheServerMBeanAuthorizationJUnitTest {
.hasMessageContaining(TestCommand.dataRead.toString());
bean.fetchLoadProbe();
bean.getActiveCQCount();
- bean.stopContinuousQuery("bar");
- bean.closeAllContinuousQuery("bar");
+ assertThatThrownBy(() -> bean.stopContinuousQuery("bar"))
+ .hasMessageContaining(TestCommand.clusterManageQuery.toString());
+ assertThatThrownBy(() -> bean.closeAllContinuousQuery("bar"))
+ .hasMessageContaining(TestCommand.clusterManageQuery.toString());
bean.isRunning();
bean.showClientQueueDetails("foo");
}
@@ -88,21 +92,25 @@ public class CacheServerMBeanAuthorizationJUnitTest {
@Test
@ConnectionConfiguration(user = "stranger", password = "1234567")
public void testNoAccess() throws Exception {
- assertThatThrownBy(() -> bean.removeIndex("foo"))
+ SoftAssertions softly = new SoftAssertions();
+
+ softly.assertThatThrownBy(() -> bean.removeIndex("foo"))
.hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.executeContinuousQuery("bar"))
+ softly.assertThatThrownBy(() -> bean.executeContinuousQuery("bar"))
.hasMessageContaining(TestCommand.dataRead.toString());
- assertThatThrownBy(() -> bean.fetchLoadProbe())
+ softly.assertThatThrownBy(() -> bean.fetchLoadProbe())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getActiveCQCount())
+ softly.assertThatThrownBy(() -> bean.getActiveCQCount())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.stopContinuousQuery("bar"))
- .hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.closeAllContinuousQuery("bar"))
- .hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.isRunning())
+ softly.assertThatThrownBy(() -> bean.stopContinuousQuery("bar"))
+ .hasMessageContaining(TestCommand.clusterManageQuery.toString());
+ softly.assertThatThrownBy(() -> bean.closeAllContinuousQuery("bar"))
+ .hasMessageContaining(TestCommand.clusterManageQuery.toString());
+ softly.assertThatThrownBy(() -> bean.isRunning())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.showClientQueueDetails("bar"))
+ softly.assertThatThrownBy(() -> bean.showClientQueueDetails("bar"))
.hasMessageContaining(TestCommand.clusterRead.toString());
+
+ softly.assertAll();
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanWithShiroIniIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanWithShiroIniIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanWithShiroIniIntegrationTest.java
index 55f592e..dc1c01a 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanWithShiroIniIntegrationTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/CacheServerMBeanWithShiroIniIntegrationTest.java
@@ -17,17 +17,18 @@ package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_SHIRO_INIT;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.management.CacheServerMXBean;
import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
@Category({IntegrationTest.class, SecurityTest.class})
public class CacheServerMBeanWithShiroIniIntegrationTest {
@@ -71,9 +72,9 @@ public class CacheServerMBeanWithShiroIniIntegrationTest {
assertThatThrownBy(() -> bean.getActiveCQCount())
.hasMessageContaining(TestCommand.clusterRead.toString());
assertThatThrownBy(() -> bean.stopContinuousQuery("bar"))
- .hasMessageContaining(TestCommand.dataManage.toString());
+ .hasMessageContaining(TestCommand.clusterManageQuery.toString());
assertThatThrownBy(() -> bean.closeAllContinuousQuery("bar"))
- .hasMessageContaining(TestCommand.dataManage.toString());
+ .hasMessageContaining(TestCommand.clusterManageQuery.toString());
assertThatThrownBy(() -> bean.isRunning())
.hasMessageContaining(TestCommand.clusterRead.toString());
assertThatThrownBy(() -> bean.showClientQueueDetails("bar"))
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/CliCommandsSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/CliCommandsSecurityTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/CliCommandsSecurityTest.java
index a66f05b..dec4703 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/CliCommandsSecurityTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/CliCommandsSecurityTest.java
@@ -15,8 +15,15 @@
package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+
+import java.util.List;
+
+import org.assertj.core.api.SoftAssertions;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.management.MemberMXBean;
@@ -27,13 +34,6 @@ import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.util.List;
@Category({IntegrationTest.class, SecurityTest.class})
public class CliCommandsSecurityTest {
@@ -60,22 +60,22 @@ public class CliCommandsSecurityTest {
@Test
@ConnectionConfiguration(user = "stranger", password = "1234567")
public void testNoAccess() {
+ SoftAssertions softly = new SoftAssertions();
for (TestCommand command : commands) {
// skip query commands since query commands are only available in client shell
if (command.getCommand().startsWith("query"))
continue;
LogService.getLogger().info("processing: " + command.getCommand());
// for those commands that requires a permission, we expect an exception to be thrown
- if (command.getPermission() != null) {
- try {
- String result = bean.processCommand(command.getCommand());
- fail(command.getCommand() + " has result: " + result);
- } catch (NotAuthorizedException e) {
- assertTrue(e.getMessage() + " should contain " + command.getPermission(),
- e.getMessage().contains(command.getPermission().toString()));
- }
+ // This has the potential to become flaky for commands with more than one permission.
+ if (command.getPermissions() != null && command.getPermissions().length > 0) {
+ softly.assertThatThrownBy(() -> bean.processCommand(command.getCommand()))
+ .describedAs(command.getCommand()).isInstanceOf(NotAuthorizedException.class)
+ .hasMessageContaining(command.getPermissions()[0].toString());
+ // }
}
}
+ softly.assertAll();
}
@Test
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/DataCommandsSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/DataCommandsSecurityTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/DataCommandsSecurityTest.java
index f746aaf..6269cf5 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/DataCommandsSecurityTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/DataCommandsSecurityTest.java
@@ -17,6 +17,13 @@ package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.cache.Cache;
import org.apache.geode.management.MemberMXBean;
import org.apache.geode.security.GemFireSecurityException;
@@ -26,12 +33,6 @@ import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
@Category({IntegrationTest.class, SecurityTest.class})
public class DataCommandsSecurityTest {
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/DeployCommandsSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/DeployCommandsSecurityTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/DeployCommandsSecurityTest.java
index a4b8c67..9dd4d99 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/DeployCommandsSecurityTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/DeployCommandsSecurityTest.java
@@ -18,14 +18,8 @@ import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANA
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertTrue;
-import org.apache.geode.management.MemberMXBean;
-import org.apache.geode.security.NotAuthorizedException;
-import org.apache.geode.security.SimpleTestSecurityManager;
-import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
-import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
-import org.apache.geode.test.dunit.rules.ServerStarterRule;
-import org.apache.geode.test.junit.categories.IntegrationTest;
-import org.apache.geode.test.junit.categories.SecurityTest;
+import java.io.File;
+
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
@@ -34,7 +28,14 @@ import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
-import java.io.File;
+import org.apache.geode.management.MemberMXBean;
+import org.apache.geode.security.NotAuthorizedException;
+import org.apache.geode.security.SimpleTestSecurityManager;
+import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
+import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
+import org.apache.geode.test.dunit.rules.ServerStarterRule;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+import org.apache.geode.test.junit.categories.SecurityTest;
@Category({IntegrationTest.class, SecurityTest.class})
public class DeployCommandsSecurityTest {
@@ -81,14 +82,7 @@ public class DeployCommandsSecurityTest {
.isInstanceOf(NotAuthorizedException.class);
}
- @Test // only cluster access right is not enough to deploy
- @ConnectionConfiguration(user = "cluster", password = "cluster")
- public void testNoAccess3() {
- assertThatThrownBy(() -> bean.processCommand(deployCommand))
- .isInstanceOf(NotAuthorizedException.class);
- }
-
- @Test // not sufficient privalge
+ @Test // not sufficient privilege
@ConnectionConfiguration(user = "clusterRead,clusterWrite,dataRead,dataWrite",
password = "clusterRead,clusterWrite,dataRead,dataWrite")
public void testNoAccess4() {
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/DiskStoreMXBeanSecurityJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/DiskStoreMXBeanSecurityJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/DiskStoreMXBeanSecurityJUnitTest.java
index e6502c0..4d101e7 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/DiskStoreMXBeanSecurityJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/DiskStoreMXBeanSecurityJUnitTest.java
@@ -17,13 +17,7 @@ package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import org.apache.geode.management.DiskStoreMXBean;
-import org.apache.geode.security.TestSecurityManager;
-import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
-import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
-import org.apache.geode.test.dunit.rules.ServerStarterRule;
-import org.apache.geode.test.junit.categories.IntegrationTest;
-import org.apache.geode.test.junit.categories.SecurityTest;
+import org.assertj.core.api.SoftAssertions;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
@@ -31,16 +25,21 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
+import org.apache.geode.management.DiskStoreMXBean;
+import org.apache.geode.security.SimpleTestSecurityManager;
+import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
+import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
+import org.apache.geode.test.dunit.rules.ServerStarterRule;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+import org.apache.geode.test.junit.categories.SecurityTest;
+
@Category({IntegrationTest.class, SecurityTest.class})
public class DiskStoreMXBeanSecurityJUnitTest {
private DiskStoreMXBean bean;
@ClassRule
public static ServerStarterRule server = new ServerStarterRule().withJMXManager()
- .withProperty(SECURITY_MANAGER, TestSecurityManager.class.getName())
- .withProperty(TestSecurityManager.SECURITY_JSON,
- "org/apache/geode/management/internal/security/cacheServer.json")
- .withAutoStart();
+ .withProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName()).withAutoStart();
@BeforeClass
public static void beforeClass() throws Exception {
@@ -57,7 +56,48 @@ public class DiskStoreMXBeanSecurityJUnitTest {
}
@Test
- @ConnectionConfiguration(user = "data-admin", password = "1234567")
+ @ConnectionConfiguration(user = "clusterRead", password = "clusterRead")
+ public void testClusterReadAccess() throws Exception {
+ assertThatThrownBy(() -> bean.flush()).hasMessageContaining(TestCommand.diskManage.toString());
+ assertThatThrownBy(() -> bean.forceCompaction())
+ .hasMessageContaining(TestCommand.diskManage.toString());
+ assertThatThrownBy(() -> bean.forceRoll())
+ .hasMessageContaining(TestCommand.diskManage.toString());
+ assertThatThrownBy(() -> bean.setDiskUsageCriticalPercentage(0.5f))
+ .hasMessageContaining(TestCommand.diskManage.toString());
+ assertThatThrownBy(() -> bean.setDiskUsageWarningPercentage(0.5f))
+ .hasMessageContaining(TestCommand.diskManage.toString());
+
+ bean.getCompactionThreshold();
+ bean.getDiskDirectories();
+ bean.getDiskReadsRate();
+ bean.isAutoCompact();
+ bean.isForceCompactionAllowed();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "clusterManageDisk", password = "clusterManageDisk")
+ public void testDiskManageAccess() throws Exception {
+ assertThatThrownBy(() -> bean.getCompactionThreshold())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+ assertThatThrownBy(() -> bean.getDiskDirectories())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+ assertThatThrownBy(() -> bean.getDiskReadsRate())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+ assertThatThrownBy(() -> bean.isAutoCompact())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+ assertThatThrownBy(() -> bean.isForceCompactionAllowed())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+
+ bean.flush();
+ bean.forceCompaction();
+ bean.forceRoll();
+ bean.setDiskUsageCriticalPercentage(0.5f);
+ bean.setDiskUsageWarningPercentage(0.5f);
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "data,cluster", password = "data,cluster")
public void testAllAccess() throws Exception {
bean.flush();
bean.forceCompaction();
@@ -72,26 +112,30 @@ public class DiskStoreMXBeanSecurityJUnitTest {
}
@Test
- @ConnectionConfiguration(user = "data-user", password = "1234567")
+ @ConnectionConfiguration(user = "noAccess", password = "noAccess")
public void testNoAccess() throws Exception {
- assertThatThrownBy(() -> bean.flush()).hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.forceCompaction())
- .hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.forceRoll())
- .hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.getCompactionThreshold())
+ SoftAssertions softly = new SoftAssertions();
+
+ softly.assertThatThrownBy(() -> bean.flush())
+ .hasMessageContaining(TestCommand.clusterManageDisk.toString());
+ softly.assertThatThrownBy(() -> bean.forceCompaction())
+ .hasMessageContaining(TestCommand.clusterManageDisk.toString());
+ softly.assertThatThrownBy(() -> bean.forceRoll())
+ .hasMessageContaining(TestCommand.clusterManageDisk.toString());
+ softly.assertThatThrownBy(() -> bean.getCompactionThreshold())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getDiskDirectories())
+ softly.assertThatThrownBy(() -> bean.getDiskDirectories())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getDiskReadsRate())
+ softly.assertThatThrownBy(() -> bean.getDiskReadsRate())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.isAutoCompact())
+ softly.assertThatThrownBy(() -> bean.isAutoCompact())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.isForceCompactionAllowed())
+ softly.assertThatThrownBy(() -> bean.isForceCompactionAllowed())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.setDiskUsageCriticalPercentage(0.5f))
- .hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.setDiskUsageWarningPercentage(0.5f))
- .hasMessageContaining(TestCommand.dataManage.toString());
+ softly.assertThatThrownBy(() -> bean.setDiskUsageCriticalPercentage(0.5f))
+ .hasMessageContaining(TestCommand.clusterManageDisk.toString());
+ softly.assertThatThrownBy(() -> bean.setDiskUsageWarningPercentage(0.5f))
+ .hasMessageContaining(TestCommand.clusterManageDisk.toString());
+ softly.assertAll();
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/DistributedSystemMXBeanSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/DistributedSystemMXBeanSecurityTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/DistributedSystemMXBeanSecurityTest.java
new file mode 100644
index 0000000..138aba6
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/DistributedSystemMXBeanSecurityTest.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.management.internal.security;
+
+import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.security.NotAuthorizedException;
+import org.apache.geode.security.SimpleTestSecurityManager;
+import org.apache.geode.security.TestSecurityManager;
+import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
+import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
+import org.apache.geode.test.dunit.rules.ServerStarterRule;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.SecurityTest;
+
+@Category({DistributedTest.class, SecurityTest.class})
+public class DistributedSystemMXBeanSecurityTest {
+
+ private DistributedSystemMXBean bean;
+
+ @ClassRule
+ public static ServerStarterRule server = new ServerStarterRule().withJMXManager()
+ .withProperty(SECURITY_MANAGER, TestSecurityManager.class.getName())
+ .withSecurityManager(SimpleTestSecurityManager.class).withAutoStart();
+
+ @Rule
+ public MBeanServerConnectionRule connectionRule =
+ new MBeanServerConnectionRule(server::getJmxPort);
+
+ @Before
+ public void setUp() throws Exception {
+ bean = connectionRule.getProxyMBean(DistributedSystemMXBean.class);
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataRead", password = "dataRead")
+ public void testDataReadAccess() throws Exception {
+ assertThatThrownBy(() -> bean.backupAllMembers(null, null))
+ .isInstanceOf(NotAuthorizedException.class);
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "clusterManageDisk", password = "clusterManageDisk")
+ public void testDiskManageAccess() throws Exception {
+ assertThatThrownBy(() -> bean.backupAllMembers(null, null))
+ .isInstanceOf(NotAuthorizedException.class);
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataRead,clusterWriteDisk",
+ password = "dataRead,clusterWriteDisk")
+ public void testBothAccess() throws Exception {
+ assertThatThrownBy(() -> bean.backupAllMembers(null, null))
+ .isNotInstanceOf(NotAuthorizedException.class);
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewayReceiverMBeanSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewayReceiverMBeanSecurityTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewayReceiverMBeanSecurityTest.java
index 73783d5..3257edb 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewayReceiverMBeanSecurityTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewayReceiverMBeanSecurityTest.java
@@ -15,17 +15,11 @@
package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
-import org.apache.geode.management.GatewayReceiverMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.security.TestSecurityManager;
-import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
-import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
-import org.apache.geode.test.dunit.rules.ServerStarterRule;
-import org.apache.geode.test.junit.categories.IntegrationTest;
-import org.apache.geode.test.junit.categories.SecurityTest;
+import javax.management.ObjectName;
+
+import org.assertj.core.api.SoftAssertions;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -34,7 +28,14 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
-import javax.management.ObjectName;
+import org.apache.geode.management.GatewayReceiverMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.security.SimpleTestSecurityManager;
+import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
+import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
+import org.apache.geode.test.dunit.rules.ServerStarterRule;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+import org.apache.geode.test.junit.categories.SecurityTest;
@Category({IntegrationTest.class, SecurityTest.class})
public class GatewayReceiverMBeanSecurityTest {
@@ -47,10 +48,7 @@ public class GatewayReceiverMBeanSecurityTest {
@ClassRule
public static ServerStarterRule server = new ServerStarterRule().withJMXManager()
- .withProperty(SECURITY_MANAGER, TestSecurityManager.class.getName())
- .withProperty(TestSecurityManager.SECURITY_JSON,
- "org/apache/geode/management/internal/security/cacheServer.json")
- .withAutoStart();
+ .withProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName()).withAutoStart();
@Rule
public MBeanServerConnectionRule connectionRule =
@@ -58,7 +56,7 @@ public class GatewayReceiverMBeanSecurityTest {
@BeforeClass
public static void beforeClass() throws Exception {
- // the server does not have a GAtewayReceiverMXBean registered initially, has to register a mock
+ // the server does not have a GatewayReceiverMXBean registered initially, has to register a mock
// one.
service = ManagementService.getManagementService(server.getCache());
mockBeanName = ObjectName.getInstance("GemFire", "key", "value");
@@ -76,7 +74,7 @@ public class GatewayReceiverMBeanSecurityTest {
}
@Test
- @ConnectionConfiguration(user = "data-admin", password = "1234567")
+ @ConnectionConfiguration(user = "data,cluster", password = "data,cluster")
public void testAllAccess() throws Exception {
bean.getAverageBatchProcessingTime();
bean.getBindAddress();
@@ -87,12 +85,16 @@ public class GatewayReceiverMBeanSecurityTest {
}
@Test
- @ConnectionConfiguration(user = "data-user", password = "1234567")
+ @ConnectionConfiguration(user = "user", password = "user")
public void testNoAccess() throws Exception {
- assertThatThrownBy(() -> bean.getTotalConnectionsTimedOut())
+ SoftAssertions softly = new SoftAssertions();
+ softly.assertThatThrownBy(() -> bean.getTotalConnectionsTimedOut())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.start()).hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.stop()).hasMessageContaining(TestCommand.dataManage.toString());
+ softly.assertThatThrownBy(() -> bean.start())
+ .hasMessageContaining(TestCommand.clusterManageGateway.toString());
+ softly.assertThatThrownBy(() -> bean.stop())
+ .hasMessageContaining(TestCommand.clusterManageGateway.toString());
+ softly.assertAll();
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewaySenderMBeanSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewaySenderMBeanSecurityTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewaySenderMBeanSecurityTest.java
index 887d0dc..3faa73e 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewaySenderMBeanSecurityTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/GatewaySenderMBeanSecurityTest.java
@@ -15,18 +15,11 @@
package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
-import org.apache.geode.management.GatewaySenderMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.internal.beans.GatewaySenderMBean;
-import org.apache.geode.security.TestSecurityManager;
-import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
-import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
-import org.apache.geode.test.dunit.rules.ServerStarterRule;
-import org.apache.geode.test.junit.categories.IntegrationTest;
-import org.apache.geode.test.junit.categories.SecurityTest;
+import javax.management.ObjectName;
+
+import org.assertj.core.api.SoftAssertions;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -35,7 +28,15 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
-import javax.management.ObjectName;
+import org.apache.geode.management.GatewaySenderMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.internal.beans.GatewaySenderMBean;
+import org.apache.geode.security.SimpleTestSecurityManager;
+import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
+import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
+import org.apache.geode.test.dunit.rules.ServerStarterRule;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+import org.apache.geode.test.junit.categories.SecurityTest;
@Category({IntegrationTest.class, SecurityTest.class})
public class GatewaySenderMBeanSecurityTest {
@@ -47,10 +48,7 @@ public class GatewaySenderMBeanSecurityTest {
@ClassRule
public static ServerStarterRule server = new ServerStarterRule().withJMXManager()
- .withProperty(SECURITY_MANAGER, TestSecurityManager.class.getName())
- .withProperty(TestSecurityManager.SECURITY_JSON,
- "org/apache/geode/management/internal/security/cacheServer.json")
- .withAutoStart();
+ .withProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName()).withAutoStart();
@Rule
public MBeanServerConnectionRule connectionRule =
@@ -58,7 +56,7 @@ public class GatewaySenderMBeanSecurityTest {
@BeforeClass
public static void beforeClass() throws Exception {
- // the server does not have a GAtewaySenderMXBean registered initially, has to register a mock
+ // the server does not have a GatewaySenderMXBean registered initially, has to register a mock
// one.
service = ManagementService.getManagementService(server.getCache());
mockBeanName = ObjectName.getInstance("GemFire", "key", "value");
@@ -76,7 +74,7 @@ public class GatewaySenderMBeanSecurityTest {
}
@Test
- @ConnectionConfiguration(user = "data-admin", password = "1234567")
+ @ConnectionConfiguration(user = "data,cluster", password = "data,cluster")
public void testAllAccess() throws Exception {
bean.getAlertThreshold();
bean.getAverageDistributionTimePerBatch();
@@ -93,28 +91,36 @@ public class GatewaySenderMBeanSecurityTest {
}
@Test
- @ConnectionConfiguration(user = "stranger", password = "1234567")
+ @ConnectionConfiguration(user = "stranger", password = "stranger")
public void testNoAccess() throws Exception {
- assertThatThrownBy(() -> bean.getAlertThreshold())
+ SoftAssertions softly = new SoftAssertions();
+
+ softly.assertThatThrownBy(() -> bean.getAlertThreshold())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getAverageDistributionTimePerBatch())
+ softly.assertThatThrownBy(() -> bean.getAverageDistributionTimePerBatch())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getBatchSize())
+ softly.assertThatThrownBy(() -> bean.getBatchSize())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getMaximumQueueMemory())
+ softly.assertThatThrownBy(() -> bean.getMaximumQueueMemory())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getOrderPolicy())
+ softly.assertThatThrownBy(() -> bean.getOrderPolicy())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.isBatchConflationEnabled())
+ softly.assertThatThrownBy(() -> bean.isBatchConflationEnabled())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.isManualStart())
+ softly.assertThatThrownBy(() -> bean.isManualStart())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.pause()).hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.rebalance())
- .hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.resume()).hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.start()).hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.stop()).hasMessageContaining(TestCommand.dataManage.toString());
+ softly.assertThatThrownBy(() -> bean.pause())
+ .hasMessageContaining(TestCommand.clusterManageGateway.toString());
+ softly.assertThatThrownBy(() -> bean.rebalance())
+ .hasMessageContaining(TestCommand.clusterManageGateway.toString());
+ softly.assertThatThrownBy(() -> bean.resume())
+ .hasMessageContaining(TestCommand.clusterManageGateway.toString());
+ softly.assertThatThrownBy(() -> bean.start())
+ .hasMessageContaining(TestCommand.clusterManageGateway.toString());
+ softly.assertThatThrownBy(() -> bean.stop())
+ .hasMessageContaining(TestCommand.clusterManageGateway.toString());
+
+ softly.assertAll();
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsPostProcessorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsPostProcessorTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsPostProcessorTest.java
index 1486866..5603eab 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsPostProcessorTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsPostProcessorTest.java
@@ -18,19 +18,20 @@ import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANA
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_POST_PROCESSOR;
import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.security.SimpleTestSecurityManager;
import org.apache.geode.security.TestPostProcessor;
-import org.apache.geode.security.TestSecurityManager;
import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
import org.apache.geode.test.dunit.rules.GfshShellConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
@Category({IntegrationTest.class, SecurityTest.class})
public class GfshCommandsPostProcessorTest {
@@ -38,10 +39,7 @@ public class GfshCommandsPostProcessorTest {
@ClassRule
public static ServerStarterRule serverStarter = new ServerStarterRule().withJMXManager()
.withProperty(SECURITY_POST_PROCESSOR, TestPostProcessor.class.getName())
- .withProperty(SECURITY_MANAGER, TestSecurityManager.class.getName())
- .withProperty("security-json",
- "org/apache/geode/management/internal/security/cacheServer.json")
- .withAutoStart();
+ .withProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName()).withAutoStart();
@Rule
public GfshShellConnectionRule gfshConnection = new GfshShellConnectionRule(
@@ -53,7 +51,7 @@ public class GfshCommandsPostProcessorTest {
}
@Test
- @ConnectionConfiguration(user = "data-user", password = "1234567")
+ @ConnectionConfiguration(user = "dataWrite,dataRead", password = "dataWrite,dataRead")
public void testGetPostProcess() throws Exception {
gfshConnection.executeCommand("put --region=region1 --key=key1 --value=value1");
gfshConnection.executeCommand("put --region=region1 --key=key2 --value=value2");
@@ -61,12 +59,12 @@ public class GfshCommandsPostProcessorTest {
// for get command, assert the return value is processed
String result = gfshConnection.execute("get --region=region1 --key=key1");
- assertThat(result).contains("data-user/region1/key1/value1");
+ assertThat(result).contains("dataWrite,dataRead/region1/key1/value1");
// for query command, assert the return values are processed
result = gfshConnection.execute("query --query=\"select * from /region1\"");
- assertThat(result).contains("data-user/null/null/value1");
- assertThat(result).contains("data-user/null/null/value2");
- assertThat(result).contains("data-user/null/null/value3");
+ assertThat(result).contains("dataWrite,dataRead/null/null/value1");
+ assertThat(result).contains("dataWrite,dataRead/null/null/value2");
+ assertThat(result).contains("dataWrite,dataRead/null/null/value3");
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java
index 84ef3fc..c2be173 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/GfshCommandsSecurityTest.java
@@ -15,12 +15,20 @@
package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import java.util.List;
+
+import org.apache.shiro.authz.permission.WildcardPermission;
+import org.assertj.core.api.SoftAssertions;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.management.cli.Result;
@@ -33,14 +41,6 @@ import org.apache.geode.test.dunit.rules.GfshShellConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.apache.shiro.authz.permission.WildcardPermission;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.util.List;
@Category({IntegrationTest.class, SecurityTest.class})
public class GfshCommandsSecurityTest {
@@ -49,7 +49,7 @@ public class GfshCommandsSecurityTest {
.withProperty(SECURITY_MANAGER, TestSecurityManager.class.getName())
.withProperty("security-json",
"org/apache/geode/management/internal/security/cacheServer.json")
- .withAutoStart();
+ .withRegion(RegionShortcut.REPLICATE_PERSISTENT, "persistentRegion");
@Rule
public GfshShellConnectionRule gfshConnection = new GfshShellConnectionRule(
@@ -75,82 +75,89 @@ public class GfshCommandsSecurityTest {
@Test
@ConnectionConfiguration(user = "cluster-reader", password = "1234567")
public void testClusterReader() throws Exception {
- runCommandsWithAndWithout("CLUSTER:READ");
+ runCommandsPermittedAndForbiddenBy("CLUSTER:READ");
}
@Test
@ConnectionConfiguration(user = "cluster-writer", password = "1234567")
public void testClusterWriter() throws Exception {
- runCommandsWithAndWithout("CLUSTER:WRITE");
+ runCommandsPermittedAndForbiddenBy("CLUSTER:WRITE");
}
@Test
@ConnectionConfiguration(user = "cluster-manager", password = "1234567")
public void testClusterManager() throws Exception {
- runCommandsWithAndWithout("CLUSTER:MANAGE");
+ runCommandsPermittedAndForbiddenBy("CLUSTER:MANAGE");
}
@Test
@ConnectionConfiguration(user = "data-reader", password = "1234567")
public void testDataReader() throws Exception {
- runCommandsWithAndWithout("DATA:READ");
+ runCommandsPermittedAndForbiddenBy("DATA:READ");
}
@Test
@ConnectionConfiguration(user = "data-writer", password = "1234567")
public void testDataWriter() throws Exception {
- runCommandsWithAndWithout("DATA:WRITE");
+ runCommandsPermittedAndForbiddenBy("DATA:WRITE");
}
@Test
@ConnectionConfiguration(user = "data-manager", password = "1234567")
public void testDataManager() throws Exception {
- runCommandsWithAndWithout("DATA:MANAGE");
+ runCommandsPermittedAndForbiddenBy("DATA:MANAGE");
}
@Test
@ConnectionConfiguration(user = "regionA-reader", password = "1234567")
public void testRegionAReader() throws Exception {
- runCommandsWithAndWithout("DATA:READ:RegionA");
+ runCommandsPermittedAndForbiddenBy("DATA:READ:RegionA");
}
@Test
@ConnectionConfiguration(user = "regionA-writer", password = "1234567")
public void testRegionAWriter() throws Exception {
- runCommandsWithAndWithout("DATA:WRITE:RegionA");
+ runCommandsPermittedAndForbiddenBy("DATA:WRITE:RegionA");
}
@Test
@ConnectionConfiguration(user = "regionA-manager", password = "1234567")
public void testRegionAManager() throws Exception {
- runCommandsWithAndWithout("DATA:MANAGE:RegionA");
+ runCommandsPermittedAndForbiddenBy("DATA:MANAGE:RegionA");
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "super-user", password = "1234567")
+ public void testRegionSuperUser() throws Exception {
+ runCommandsPermittedAndForbiddenBy("*");
}
- private void runCommandsWithAndWithout(String permission) throws Exception {
+ private void runCommandsPermittedAndForbiddenBy(String permission) throws Exception {
List<TestCommand> allPermitted =
TestCommand.getPermittedCommands(new WildcardPermission(permission, true));
+ SoftAssertions softly = new SoftAssertions();
+
for (TestCommand permitted : allPermitted) {
System.out.println("Processing authorized command: " + permitted.getCommand());
CommandResult result = gfshConnection.executeCommand(permitted.getCommand());
assertNotNull(result);
if (result.getResultData() instanceof ErrorResultData) {
- assertNotEquals(ResultBuilder.ERRORCODE_UNAUTHORIZED,
- ((ErrorResultData) result.getResultData()).getErrorCode());
+ softly.assertThat(ResultBuilder.ERRORCODE_UNAUTHORIZED).describedAs(permitted.getCommand())
+ .isNotEqualTo(((ErrorResultData) result.getResultData()).getErrorCode());
} else {
- assertEquals(Result.Status.OK, result.getStatus());
+ softly.assertThat(Result.Status.OK).describedAs(permitted.toString())
+ .isEqualTo(result.getStatus());
}
}
- List<TestCommand> others = TestCommand.getCommands();
+ // skip no permission commands
+ List<TestCommand> others = TestCommand.getOnlineCommands();
others.removeAll(allPermitted);
for (TestCommand other : others) {
- // skip no permission commands
- if (other.getPermission() == null)
- continue;
System.out.println("Processing unauthorized command: " + other.getCommand());
- CommandResult result = (CommandResult) gfshConnection.executeCommand(other.getCommand());
+ CommandResult result = gfshConnection.executeCommand(other.getCommand());
int errorCode = ((ErrorResultData) result.getResultData()).getErrorCode();
// for some commands there are pre execution checks to check for user input error, will skip
@@ -160,13 +167,12 @@ public class GfshCommandsSecurityTest {
continue;
}
- assertEquals(ResultBuilder.ERRORCODE_UNAUTHORIZED,
- ((ErrorResultData) result.getResultData()).getErrorCode());
- String resultMessage = result.getContent().toString();
- String permString = other.getPermission().toString();
- assertTrue(resultMessage + " does not contain " + permString,
- resultMessage.contains(permString));
+ softly.assertThat(ResultBuilder.ERRORCODE_UNAUTHORIZED).describedAs(other.getCommand())
+ .isEqualTo(((ErrorResultData) result.getResultData()).getErrorCode());
}
+
+ softly.assertAll();
+
}
@Test
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/LockServiceMBeanAuthorizationJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/LockServiceMBeanAuthorizationJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/LockServiceMBeanAuthorizationJUnitTest.java
index dad2e9c..dd5cd13 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/LockServiceMBeanAuthorizationJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/LockServiceMBeanAuthorizationJUnitTest.java
@@ -15,25 +15,26 @@
package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.assertj.core.api.SoftAssertions;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Cache;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.locks.DLockService;
import org.apache.geode.management.LockServiceMXBean;
-import org.apache.geode.security.TestSecurityManager;
+import org.apache.geode.security.SimpleTestSecurityManager;
import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
@Category({IntegrationTest.class, SecurityTest.class})
public class LockServiceMBeanAuthorizationJUnitTest {
@@ -41,10 +42,7 @@ public class LockServiceMBeanAuthorizationJUnitTest {
@ClassRule
public static ServerStarterRule server = new ServerStarterRule().withJMXManager()
- .withProperty(SECURITY_MANAGER, TestSecurityManager.class.getName())
- .withProperty(TestSecurityManager.SECURITY_JSON,
- "org/apache/geode/management/internal/security/cacheServer.json")
- .withAutoStart();
+ .withProperty(SECURITY_MANAGER, SimpleTestSecurityManager.class.getName()).withAutoStart();
@Rule
public MBeanServerConnectionRule connectionRule =
@@ -68,7 +66,8 @@ public class LockServiceMBeanAuthorizationJUnitTest {
}
@Test
- @ConnectionConfiguration(user = "data-admin", password = "1234567")
+ @ConnectionConfiguration(user = "clusterRead,clusterManage",
+ password = "clusterRead,clusterManage")
public void testAllAccess() throws Exception {
lockServiceMBean.becomeLockGrantor();
lockServiceMBean.fetchGrantorMember();
@@ -78,24 +77,50 @@ public class LockServiceMBeanAuthorizationJUnitTest {
}
@Test
- @ConnectionConfiguration(user = "cluster-admin", password = "1234567")
- public void testSomeAccess() throws Exception {
- assertThatThrownBy(() -> lockServiceMBean.becomeLockGrantor());
+ @ConnectionConfiguration(user = "clusterManage", password = "clusterManage")
+ public void testClusterManage() throws Exception {
+ SoftAssertions softly = new SoftAssertions();
+ lockServiceMBean.becomeLockGrantor(); // c:m
+ softly.assertThatThrownBy(() -> lockServiceMBean.fetchGrantorMember())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+ softly.assertThatThrownBy(() -> lockServiceMBean.getMemberCount())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+ softly.assertThatThrownBy(() -> lockServiceMBean.isDistributed())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+ softly.assertThatThrownBy(() -> lockServiceMBean.listThreadsHoldingLock())
+ .hasMessageContaining(TestCommand.clusterRead.toString());
+ softly.assertAll();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "clusterRead", password = "clusterRead")
+ public void testClusterRead() throws Exception {
+ SoftAssertions softly = new SoftAssertions();
+ softly.assertThatThrownBy(() -> lockServiceMBean.becomeLockGrantor())
+ .hasMessageContaining(TestCommand.clusterManage.toString());
+ lockServiceMBean.fetchGrantorMember();
lockServiceMBean.getMemberCount();
+ lockServiceMBean.isDistributed();
+ lockServiceMBean.listThreadsHoldingLock();
+ softly.assertAll();
}
@Test
- @ConnectionConfiguration(user = "data-user", password = "1234567")
+ @ConnectionConfiguration(user = "user", password = "user")
public void testNoAccess() throws Exception {
- assertThatThrownBy(() -> lockServiceMBean.becomeLockGrantor())
- .hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> lockServiceMBean.fetchGrantorMember())
+ SoftAssertions softly = new SoftAssertions();
+
+ softly.assertThatThrownBy(() -> lockServiceMBean.becomeLockGrantor())
+ .hasMessageContaining(TestCommand.clusterManage.toString());
+ softly.assertThatThrownBy(() -> lockServiceMBean.fetchGrantorMember())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> lockServiceMBean.getMemberCount())
+ softly.assertThatThrownBy(() -> lockServiceMBean.getMemberCount())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> lockServiceMBean.isDistributed())
+ softly.assertThatThrownBy(() -> lockServiceMBean.isDistributed())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> lockServiceMBean.listThreadsHoldingLock())
+ softly.assertThatThrownBy(() -> lockServiceMBean.listThreadsHoldingLock())
.hasMessageContaining(TestCommand.clusterRead.toString());
+
+ softly.assertAll();
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/MBeanSecurityJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/MBeanSecurityJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/MBeanSecurityJUnitTest.java
index 091b1db..187246d 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/MBeanSecurityJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/MBeanSecurityJUnitTest.java
@@ -19,6 +19,22 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
+import java.io.IOException;
+import java.util.Set;
+
+import javax.management.DynamicMBean;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerConnection;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectInstance;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
+
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.management.ManagementException;
import org.apache.geode.management.ManagementService;
import org.apache.geode.management.MemberMXBean;
@@ -29,20 +45,6 @@ import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.IOException;
-import java.util.Set;
-import javax.management.DynamicMBean;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerConnection;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectInstance;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
@Category({IntegrationTest.class, SecurityTest.class})
public class MBeanSecurityJUnitTest {
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/ManagerMBeanAuthorizationJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/ManagerMBeanAuthorizationJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/ManagerMBeanAuthorizationJUnitTest.java
index 77f68c3..73ffe97 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/ManagerMBeanAuthorizationJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/ManagerMBeanAuthorizationJUnitTest.java
@@ -15,9 +15,20 @@
package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
+import java.lang.management.ManagementFactory;
+
+import javax.management.ObjectName;
+
+import org.assertj.core.api.SoftAssertions;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.management.ManagerMXBean;
import org.apache.geode.management.internal.beans.ManagerMBean;
import org.apache.geode.security.TestSecurityManager;
@@ -26,15 +37,6 @@ import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.lang.management.ManagementFactory;
-import javax.management.ObjectName;
@Category({IntegrationTest.class, SecurityTest.class})
public class ManagerMBeanAuthorizationJUnitTest {
@@ -76,10 +78,14 @@ public class ManagerMBeanAuthorizationJUnitTest {
@Test
@ConnectionConfiguration(user = "data-admin", password = "1234567")
public void testSomeAccess() throws Exception {
- assertThatThrownBy(() -> managerMXBean.start())
+ SoftAssertions softly = new SoftAssertions();
+
+ softly.assertThatThrownBy(() -> managerMXBean.start())
.hasMessageContaining(TestCommand.clusterManage.toString());
- assertThatThrownBy(() -> managerMXBean.getPulseURL())
+ softly.assertThatThrownBy(() -> managerMXBean.getPulseURL())
.hasMessageContaining(TestCommand.clusterWrite.toString());
+
+ softly.assertAll();
managerMXBean.isRunning();
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/MemberMBeanSecurityJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/MemberMBeanSecurityJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/MemberMBeanSecurityJUnitTest.java
index 77ddcc9..e6b50d2 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/MemberMBeanSecurityJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/MemberMBeanSecurityJUnitTest.java
@@ -17,6 +17,13 @@ package org.apache.geode.management.internal.security;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import org.assertj.core.api.SoftAssertions;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.contrib.java.lang.system.RestoreSystemProperties;
+import org.junit.experimental.categories.Category;
+
import org.apache.geode.management.MemberMXBean;
import org.apache.geode.security.TestSecurityManager;
import org.apache.geode.test.dunit.rules.ConnectionConfiguration;
@@ -24,11 +31,6 @@ import org.apache.geode.test.dunit.rules.MBeanServerConnectionRule;
import org.apache.geode.test.dunit.rules.ServerStarterRule;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.contrib.java.lang.system.RestoreSystemProperties;
-import org.junit.experimental.categories.Category;
@Category({IntegrationTest.class, SecurityTest.class})
public class MemberMBeanSecurityJUnitTest {
@@ -67,7 +69,6 @@ public class MemberMBeanSecurityJUnitTest {
bean.isCacheServer();
bean.isServer();
bean.listConnectedGatewayReceivers();
- // bean.processCommand("create region --name=Region_A");
bean.showJVMMetrics();
bean.status();
}
@@ -75,8 +76,7 @@ public class MemberMBeanSecurityJUnitTest {
@Test
@ConnectionConfiguration(user = "cluster-admin", password = "1234567")
public void testClusterAdmin() throws Exception {
- assertThatThrownBy(() -> bean.compactAllDiskStores())
- .hasMessageContaining(TestCommand.dataManage.toString());
+ bean.compactAllDiskStores();
bean.shutDownMember();
bean.createManager();
bean.fetchJvmThreads();
@@ -93,7 +93,8 @@ public class MemberMBeanSecurityJUnitTest {
@Test
@ConnectionConfiguration(user = "data-admin", password = "1234567")
public void testDataAdmin() throws Exception {
- bean.compactAllDiskStores();
+ assertThatThrownBy(() -> bean.compactAllDiskStores())
+ .hasMessageContaining(TestCommand.clusterManageDisk.toString());
assertThatThrownBy(() -> bean.shutDownMember())
.hasMessageContaining(TestCommand.clusterManage.toString());
assertThatThrownBy(() -> bean.createManager())
@@ -105,31 +106,35 @@ public class MemberMBeanSecurityJUnitTest {
@Test
@ConnectionConfiguration(user = "data-user", password = "1234567")
public void testDataUser() throws Exception {
- assertThatThrownBy(() -> bean.shutDownMember())
+ SoftAssertions softly = new SoftAssertions();
+
+ softly.assertThatThrownBy(() -> bean.shutDownMember())
.hasMessageContaining(TestCommand.clusterManage.toString());
- assertThatThrownBy(() -> bean.createManager())
+ softly.assertThatThrownBy(() -> bean.createManager())
.hasMessageContaining(TestCommand.clusterManage.toString());
- assertThatThrownBy(() -> bean.compactAllDiskStores())
- .hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.fetchJvmThreads())
+ softly.assertThatThrownBy(() -> bean.compactAllDiskStores())
+ .hasMessageContaining(TestCommand.clusterManageDisk.toString());
+ softly.assertThatThrownBy(() -> bean.fetchJvmThreads())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getName())
+ softly.assertThatThrownBy(() -> bean.getName())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.getDiskStores())
+ softly.assertThatThrownBy(() -> bean.getDiskStores())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.hasGatewayReceiver())
+ softly.assertThatThrownBy(() -> bean.hasGatewayReceiver())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.isCacheServer())
+ softly.assertThatThrownBy(() -> bean.isCacheServer())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.isServer())
+ softly.assertThatThrownBy(() -> bean.isServer())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.listConnectedGatewayReceivers())
+ softly.assertThatThrownBy(() -> bean.listConnectedGatewayReceivers())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.processCommand("create region --name=Region_A"))
+ softly.assertThatThrownBy(() -> bean.processCommand("create region --name=Region_A"))
.hasMessageContaining(TestCommand.dataManage.toString());
- assertThatThrownBy(() -> bean.showJVMMetrics())
+ softly.assertThatThrownBy(() -> bean.showJVMMetrics())
.hasMessageContaining(TestCommand.clusterRead.toString());
- assertThatThrownBy(() -> bean.status())
+ softly.assertThatThrownBy(() -> bean.status())
.hasMessageContaining(TestCommand.clusterRead.toString());
+
+ softly.assertAll();
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/MultiUserDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/MultiUserDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/MultiUserDUnitTest.java
index 255048d..e3fe173 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/MultiUserDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/MultiUserDUnitTest.java
@@ -18,12 +18,21 @@ import static org.apache.geode.distributed.ConfigurationProperties.NAME;
import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
+import org.awaitility.Awaitility;
+import org.json.JSONException;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.HeadlessGfsh;
-import org.apache.geode.management.internal.cli.commands.CliCommandTestBase;
import org.apache.geode.management.internal.cli.result.CommandResult;
import org.apache.geode.management.internal.cli.result.ErrorResultData;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
@@ -32,67 +41,62 @@ import org.apache.geode.test.dunit.AsyncInvocation;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.IgnoredException;
import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.GfshShellConnectionRule;
+import org.apache.geode.test.dunit.rules.GfshShellConnectionRule.PortType;
+import org.apache.geode.test.dunit.rules.LocatorServerStartupRule;
+import org.apache.geode.test.dunit.rules.Member;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.FlakyTest;
import org.apache.geode.test.junit.categories.SecurityTest;
-import org.awaitility.Awaitility;
-import org.json.JSONException;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
@Category({DistributedTest.class, SecurityTest.class})
-public class MultiUserDUnitTest extends CliCommandTestBase {
+public class MultiUserDUnitTest {
- @Category(FlakyTest.class) // GEODE-1579
- @Test
- public void testMultiUser() throws IOException, JSONException, InterruptedException {
- IgnoredException.addIgnoredException("java.util.zip.ZipException: zip file is empty");
+ @Rule
+ public LocatorServerStartupRule lsRule = new LocatorServerStartupRule();
+
+ private Member server;
+ @Before
+ public void setup() throws Exception {
Properties properties = new Properties();
properties.put(NAME, MultiUserDUnitTest.class.getSimpleName());
properties.put(SECURITY_MANAGER, TestSecurityManager.class.getName());
-
- // set up vm_0 the secure jmx manager
- Object[] results = setUpJMXManagerOnVM(0, properties,
+ properties.put("security-json",
"org/apache/geode/management/internal/security/cacheServer.json");
- String gfshDir = this.gfshDir;
+ server = lsRule.startServerAsJmxManager(0, properties);
+ }
+
+ @Category(FlakyTest.class) // GEODE-1579
+ @Test
+ public void testMultiUser() throws IOException, JSONException, InterruptedException {
+
+ IgnoredException.addIgnoredException("java.util.zip.ZipException: zip file is empty");
+ int jmxPort = server.getJmxPort();
// set up vm_1 as a gfsh vm, data-reader will login and log out constantly in this vm until the
// test is done.
VM vm1 = Host.getHost(0).getVM(1);
AsyncInvocation vm1Invoke = vm1.invokeAsync("run as data-reader", () -> {
- String shellId = getClass().getSimpleName() + "_vm1";
- HeadlessGfsh shell = new HeadlessGfsh(shellId, 30, gfshDir);
- while (true) {
- connect((String) results[0], (Integer) results[1], (Integer) results[2], shell,
- "data-reader", "1234567");
- Awaitility.waitAtMost(5, TimeUnit.MILLISECONDS);
- shell.executeCommand("disconnect");
- }
+ GfshShellConnectionRule gfsh = new GfshShellConnectionRule();
+ gfsh.secureConnectAndVerify(jmxPort, PortType.jmxManger, "data-reader", "1234567");
+
+ Awaitility.waitAtMost(5, TimeUnit.MILLISECONDS);
+ gfsh.close();
});
VM vm2 = Host.getHost(0).getVM(2);
// set up vm_2 as a gfsh vm, and then connect as "stranger" and try to execute the commands and
// assert errors comes back are NotAuthorized
AsyncInvocation vm2Invoke = vm2.invokeAsync("run as guest", () -> {
- String shellId = getClass().getSimpleName() + "_vm2";
- HeadlessGfsh shell = new HeadlessGfsh(shellId, 30, gfshDir);
- connect((String) results[0], (Integer) results[1], (Integer) results[2], shell, "stranger",
- "1234567");
+ GfshShellConnectionRule gfsh = new GfshShellConnectionRule();
+ gfsh.secureConnectAndVerify(jmxPort, PortType.jmxManger, "stranger", "1234567");
- List<TestCommand> allCommands = TestCommand.getCommands();
+ List<TestCommand> allCommands = TestCommand.getOnlineCommands();
for (TestCommand command : allCommands) {
LogService.getLogger().info("executing: " + command.getCommand());
- if (command.getPermission() == null) {
- continue;
- }
- CommandResult result = executeCommand(shell, command.getCommand());
+ CommandResult result = gfsh.executeCommand(command.getCommand());
int errorCode = ((ErrorResultData) result.getResultData()).getErrorCode();
@@ -106,11 +110,9 @@ public class MultiUserDUnitTest extends CliCommandTestBase {
assertEquals("Not an expected result: " + result.toString(),
ResultBuilder.ERRORCODE_UNAUTHORIZED,
((ErrorResultData) result.getResultData()).getErrorCode());
- String resultMessage = result.getContent().toString();
- String permString = command.getPermission().toString();
- assertTrue(resultMessage + " does not contain " + permString,
- resultMessage.contains(permString));
+
}
+ gfsh.close();
LogService.getLogger().info("vm 2 done!");
});
@@ -123,28 +125,22 @@ public class MultiUserDUnitTest extends CliCommandTestBase {
// set up vm_3 as another gfsh vm, and then connect as "super-user" and try to execute the
// commands and assert we don't get a NotAuthorized Exception
AsyncInvocation vm3Invoke = vm3.invokeAsync("run as superUser", () -> {
- String shellId = getClass().getSimpleName() + "_vm3";
- HeadlessGfsh shell = new HeadlessGfsh(shellId, 30, gfshDir);
- connect((String) results[0], (Integer) results[1], (Integer) results[2], shell, "super-user",
- "1234567");
+ GfshShellConnectionRule gfsh = new GfshShellConnectionRule();
+ gfsh.secureConnectAndVerify(jmxPort, PortType.jmxManger, "super-user", "1234567");
- List<TestCommand> allCommands = TestCommand.getCommands();
+ List<TestCommand> allCommands = TestCommand.getOnlineCommands();
for (TestCommand command : allCommands) {
LogService.getLogger().info("executing: " + command.getCommand());
- if (command.getPermission() == null) {
- continue;
- }
- CommandResult result = executeCommand(shell, command.getCommand());
+ CommandResult result = gfsh.executeCommand(command.getCommand());
if (result.getResultData().getStatus() == Status.OK) {
continue;
}
-
assertNotEquals("Did not expect an Unauthorized exception: " + result.toString(),
ResultBuilder.ERRORCODE_UNAUTHORIZED,
((ErrorResultData) result.getResultData()).getErrorCode());
}
-
+ gfsh.close();
LogService.getLogger().info("vm 3 done!");
});
http://git-wip-us.apache.org/repos/asf/geode/blob/451d12e8/geode-core/src/test/java/org/apache/geode/management/internal/security/ResourcePermissionTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/ResourcePermissionTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/ResourcePermissionTest.java
index 51f8c5e..54db58e 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/ResourcePermissionTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/ResourcePermissionTest.java
@@ -16,18 +16,17 @@ package org.apache.geode.management.internal.security;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+
+import org.apache.shiro.authz.permission.WildcardPermission;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
import org.apache.geode.security.ResourcePermission;
-import org.apache.geode.security.ResourcePermission.Target;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
import org.apache.geode.test.junit.categories.SecurityTest;
import org.apache.geode.test.junit.categories.UnitTest;
-import org.apache.shiro.authz.permission.WildcardPermission;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
@Category({UnitTest.class, SecurityTest.class})
public class ResourcePermissionTest {
@@ -110,7 +109,7 @@ public class ResourcePermissionTest {
}
@Test
- public void testImples() {
+ public void testImplies() {
WildcardPermission role = new WildcardPermission("*:read");
role.implies(new ResourcePermission(Resource.DATA, Operation.READ));
role.implies(new ResourcePermission(Resource.CLUSTER, Operation.READ));