You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by bs...@apache.org on 2016/05/13 17:50:36 UTC
[1/3] incubator-geode git commit: Revert "GEODE-1376: Cleaned up
server port to be '0'."
Repository: incubator-geode
Updated Branches:
refs/heads/develop a881e9cb1 -> d1a0748ba
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorLoadBalancingDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorLoadBalancingDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorLoadBalancingDUnitTest.java
index 176fbea..9ef87d2 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorLoadBalancingDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorLoadBalancingDUnitTest.java
@@ -16,6 +16,17 @@
*/
package com.gemstone.gemfire.cache.client.internal;
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Assert;
+
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.client.PoolManager;
import com.gemstone.gemfire.cache.client.internal.locator.ClientConnectionRequest;
@@ -39,31 +50,24 @@ import com.gemstone.gemfire.internal.logging.LocalLogWriter;
import com.gemstone.gemfire.test.dunit.Host;
import com.gemstone.gemfire.test.dunit.LogWriterUtils;
import com.gemstone.gemfire.test.dunit.NetworkUtils;
+import com.gemstone.gemfire.test.dunit.SerializableRunnable;
+import com.gemstone.gemfire.test.dunit.SerializableRunnableIF;
import com.gemstone.gemfire.test.dunit.VM;
-import com.jayway.awaitility.Awaitility;
-import org.junit.Assert;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.net.InetAddress;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
+import com.gemstone.gemfire.test.dunit.Wait;
+import com.gemstone.gemfire.test.dunit.WaitCriterion;
/**
*
*/
public class LocatorLoadBalancingDUnitTest extends LocatorTestBase {
-
+
/**
* The number of connections that we can be off by in the balancing tests
* We need this little fudge factor, because the locator can receive an update
* from the bridge server after it has made incremented its counter for a client
* connection, but the client hasn't connected yet. This wipes out the estimation
* on the locator. This means that we may be slighly off in our balance.
- * <p>
+ *
* TODO grid fix this hole in the locator.
*/
private static final int ALLOWABLE_ERROR_IN_COUNT = 1;
@@ -74,144 +78,149 @@ public class LocatorLoadBalancingDUnitTest extends LocatorTestBase {
}
/**
- * Test the locator discovers a bridge server and is initialized with
+ * Test the locator discovers a bridge server and is initialized with
* the correct load for that bridge server.
*/
public void testDiscovery() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
-
+ VM vm2 = host.getVM(2);
+// vm0.invoke(new SerializableRunnable() {
+// public void run() {
+// System.setProperty("gemfire.DistributionAdvisor.VERBOSE", "true");
+// }
+// });
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
-
+ startLocatorInVM(vm0, locatorPort, "");
+
String locators = getLocatorString(host, locatorPort);
-
- int serverPort = vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a", "b" }, locators));
-
+
+ int serverPort = startBridgeServerInVM(vm1, new String[] {"a", "b"}, locators);
+
ServerLoad expectedLoad = new ServerLoad(0f, 1 / 800.0f, 0f, 1f);
ServerLocation expectedLocation = new ServerLocation(NetworkUtils.getServerHostName(vm0
.getHost()), serverPort);
Map expected = new HashMap();
expected.put(expectedLocation, expectedLoad);
-
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
-
- int serverPort2 = vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a", "b" }, locators));
-
+
+ checkLocatorLoad(vm0, expected);
+
+ int serverPort2 = startBridgeServerInVM(vm2, new String[] {"a", "b"}, locators);
+
ServerLocation expectedLocation2 = new ServerLocation(NetworkUtils.getServerHostName(vm0
.getHost()), serverPort2);
-
+
expected.put(expectedLocation2, expectedLoad);
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
+ checkLocatorLoad(vm0, expected);
}
-
+
/**
* Test that the locator will properly estimate the load for servers when
- * it receives connection requests.
+ * it receives connection requests.
*/
- public void testEstimation() throws IOException, ClassNotFoundException {
+ public void testEstimation() throws UnknownHostException, IOException, ClassNotFoundException {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
+ startLocatorInVM(vm0, locatorPort, "");
String locators = getLocatorString(host, locatorPort);
-
- int serverPort = vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a", "b" }, locators));
-
- ServerLoad expectedLoad = new ServerLoad(2 / 800f, 1 / 800.0f, 0f, 1f);
+
+ int serverPort = startBridgeServerInVM(vm1, new String[] {"a", "b"}, locators);
+
+ ServerLoad expectedLoad = new ServerLoad(2/800f, 1 / 800.0f, 0f, 1f);
ServerLocation expectedLocation = new ServerLocation(NetworkUtils.getServerHostName(host), serverPort);
Map expected = new HashMap();
expected.put(expectedLocation, expectedLoad);
-
+
ClientConnectionResponse response;
response = (ClientConnectionResponse) TcpClient.requestToServer(InetAddress
- .getByName(NetworkUtils.getServerHostName(host)), locatorPort,
+ .getByName(NetworkUtils.getServerHostName(host)), locatorPort,
new ClientConnectionRequest(Collections.EMPTY_SET, null), 10000);
Assert.assertEquals(expectedLocation, response.getServer());
-
+
response = (ClientConnectionResponse) TcpClient.requestToServer(InetAddress
- .getByName(NetworkUtils.getServerHostName(host)), locatorPort,
+ .getByName(NetworkUtils.getServerHostName(host)), locatorPort,
new ClientConnectionRequest(Collections.EMPTY_SET, null), 10000, true);
Assert.assertEquals(expectedLocation, response.getServer());
-
+
//we expect that the connection load load will be 2 * the loadPerConnection
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
-
+ checkLocatorLoad(vm0, expected);
+
QueueConnectionResponse response2;
response2 = (QueueConnectionResponse) TcpClient.requestToServer(InetAddress
- .getByName(NetworkUtils.getServerHostName(host)), locatorPort,
+ .getByName(NetworkUtils.getServerHostName(host)), locatorPort,
new QueueConnectionRequest(null, 2,
Collections.EMPTY_SET, null, false), 10000, true);
Assert.assertEquals(Collections.singletonList(expectedLocation), response2.getServers());
-
+
response2 = (QueueConnectionResponse) TcpClient
.requestToServer(InetAddress.getByName(NetworkUtils.getServerHostName(host)),
locatorPort, new QueueConnectionRequest(null, 5, Collections.EMPTY_SET, null,
false), 10000, true);
-
+
Assert.assertEquals(Collections.singletonList(expectedLocation), response2.getServers());
//we expect that the queue load will increase by 2
expectedLoad.setSubscriptionConnectionLoad(2f);
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
+ checkLocatorLoad(vm0, expected);
}
-
+
/**
* Test to make sure the bridge servers communicate
* their updated load to the controller when the load
* on the bridge server changes.
- *
- * @throws Exception
+ * @throws Exception
*/
public void testLoadMessaging() throws Exception {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
+ startLocatorInVM(vm0, locatorPort, "");
String locators = getLocatorString(host, locatorPort);
-
- final int serverPort = vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a", "b" }, locators));
-
+
+ final int serverPort = startBridgeServerInVM(vm1, new String[] {"a", "b"}, locators);
+
//We expect 0 load
Map expected = new HashMap();
ServerLocation expectedLocation = new ServerLocation(NetworkUtils.getServerHostName(host), serverPort);
ServerLoad expectedLoad = new ServerLoad(0f, 1 / 800.0f, 0f, 1f);
expected.put(expectedLocation, expectedLoad);
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
-
+ checkLocatorLoad(vm0, expected);
+
PoolFactoryImpl pf = new PoolFactoryImpl(null);
pf.addServer(NetworkUtils.getServerHostName(host), serverPort);
pf.setMinConnections(8);
pf.setMaxConnections(8);
pf.setSubscriptionEnabled(true);
- vm2.invoke("StartBridgeClient", () -> startBridgeClient(pf.getPoolAttributes(), new String[] { REGION_NAME }));
-
+ startBridgeClientInVM(vm2, pf.getPoolAttributes(), new String[] {REGION_NAME});
+
//We expect 8 client to server connections. The queue requires
//an additional client to server connection, but that shouldn't show up here.
- expectedLoad = new ServerLoad(8 / 800f, 1 / 800.0f, 1f, 1f);
+ expectedLoad = new ServerLoad(8/800f, 1 / 800.0f, 1f, 1f);
expected.put(expectedLocation, expectedLoad);
-
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
-
+
+
+ checkLocatorLoad(vm0, expected);
+
stopBridgeMemberVM(vm2);
-
+
//Now we expect 0 load
expectedLoad = new ServerLoad(0f, 1 / 800.0f, 0f, 1f);
expected.put(expectedLocation, expectedLoad);
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
+ checkLocatorLoad(vm0, expected);
}
-
+
/**
* Test to make sure that the locator
* balancing load between two servers.
- *
- * @throws Exception
+ * @throws Exception
*/
public void testBalancing() throws Exception {
final Host host = Host.getHost(0);
@@ -219,60 +228,87 @@ public class LocatorLoadBalancingDUnitTest extends LocatorTestBase {
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
+ startLocatorInVM(vm0, locatorPort, "");
String locators = getLocatorString(host, locatorPort);
-
- vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a", "b" }, locators));
- vm2.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a", "b" }, locators));
-
+
+ startBridgeServerInVM(vm1, new String[] {"a", "b"}, locators);
+ startBridgeServerInVM(vm2, new String[] {"a", "b"}, locators);
+
PoolFactoryImpl pf = new PoolFactoryImpl(null);
pf.addLocator(NetworkUtils.getServerHostName(host), locatorPort);
pf.setMinConnections(80);
pf.setMaxConnections(80);
pf.setSubscriptionEnabled(false);
pf.setIdleTimeout(-1);
- vm3.invoke("StartBridgeClient", () -> startBridgeClient(pf.getPoolAttributes(), new String[] { REGION_NAME }));
-
- vm3.invoke("waitForPrefilledConnections", () -> waitForPrefilledConnections(80));
-
- vm1.invoke("check connection count", () -> checkConnectionCount(40));
- vm2.invoke("check connection count", () -> checkConnectionCount(40));
+ startBridgeClientInVM(vm3, pf.getPoolAttributes(), new String[] {REGION_NAME});
+
+ waitForPrefilledConnections(vm3, 80);
+
+ checkConnectionCount(vm1, 40);
+ checkConnectionCount(vm2, 40);
}
- private void checkConnectionCount(final int count) {
- Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
- final CacheServerImpl server = (CacheServerImpl)
- cache.getCacheServers().get(0);
- Awaitility.await().pollDelay(100, TimeUnit.MILLISECONDS).pollInterval(100, TimeUnit.MILLISECONDS)
- .timeout(300, TimeUnit.SECONDS).until(() -> {
- int sz = server.getAcceptor().getStats().getCurrentClientConnections();
- if (Math.abs(sz - count) <= ALLOWABLE_ERROR_IN_COUNT) {
- return true;
+ private void checkConnectionCount(VM vm, final int count) {
+ SerializableRunnableIF checkConnectionCount = new SerializableRunnable("checkConnectionCount") {
+ public void run() {
+ Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
+ final CacheServerImpl server = (CacheServerImpl)
+ cache.getCacheServers().get(0);
+ WaitCriterion wc = new WaitCriterion() {
+ String excuse;
+ public boolean done() {
+ int sz = server.getAcceptor().getStats()
+ .getCurrentClientConnections();
+ if (Math.abs(sz - count) <= ALLOWABLE_ERROR_IN_COUNT) {
+ return true;
+ }
+ excuse = "Found " + sz + " connections, expected " + count;
+ return false;
+ }
+ public String description() {
+ return excuse;
+ }
+ };
+ Wait.waitForCriterion(wc, 5 * 60 * 1000, 1000, true);
}
- System.out.println("Found " + sz + " connections, expected " + count);
- return false;
- });
+ };
+
+ vm.invoke(checkConnectionCount);
}
-
- private void waitForPrefilledConnections(final int count) throws Exception {
- waitForPrefilledConnections(count, POOL_NAME);
+
+ private void waitForPrefilledConnections(VM vm, final int count) throws Exception {
+ waitForPrefilledConnections(vm, count, POOL_NAME);
}
- private void waitForPrefilledConnections(final int count, final String poolName) throws Exception {
- final PoolImpl pool = (PoolImpl) PoolManager.getAll().get(poolName);
- Awaitility.await().pollDelay(100, TimeUnit.MILLISECONDS).pollInterval(100, TimeUnit.MILLISECONDS)
- .timeout(300, TimeUnit.SECONDS).until(() -> pool.getConnectionCount() >= count);
+ private void waitForPrefilledConnections(VM vm, final int count, final String poolName) throws Exception {
+ SerializableRunnable runnable = new SerializableRunnable("waitForPrefilledConnections") {
+ public void run() {
+ final PoolImpl pool = (PoolImpl) PoolManager.getAll().get(poolName);
+ WaitCriterion ev = new WaitCriterion() {
+ public boolean done() {
+ return pool.getConnectionCount() >= count;
+ }
+ public String description() {
+ return "connection count never reached " + count;
+ }
+ };
+ Wait.waitForCriterion(ev, MAX_WAIT, 200, true);
+ }
+ };
+ if(vm == null) {
+ runnable.run();
+ } else {
+ vm.invoke(runnable);
+ }
}
-
- /**
- * Test that the locator balances load between
+
+ /** Test that the locator balances load between
* three servers with intersecting server groups.
* Server: 1 2 3
* Groups: a a,b b
- *
- * @throws Exception
+ * @throws Exception
*/
public void testIntersectingServerGroups() throws Exception {
final Host host = Host.getHost(0);
@@ -280,158 +316,175 @@ public class LocatorLoadBalancingDUnitTest extends LocatorTestBase {
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
+ startLocatorInVM(vm0, locatorPort, "");
String locators = getLocatorString(host, locatorPort);
-
- int serverPort1 = vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a" }, locators));
- vm2.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "a", "b" }, locators));
- vm3.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "b" }, locators));
-
+
+ int serverPort1 = startBridgeServerInVM(vm1, new String[] {"a"}, locators);
+ startBridgeServerInVM(vm2, new String[] {"a", "b"}, locators);
+ startBridgeServerInVM(vm3, new String[] {"b"}, locators);
+
PoolFactoryImpl pf = new PoolFactoryImpl(null);
pf.addLocator(NetworkUtils.getServerHostName(host), locatorPort);
pf.setMinConnections(12);
pf.setSubscriptionEnabled(false);
pf.setServerGroup("a");
pf.setIdleTimeout(-1);
- startBridgeClient(pf.getPoolAttributes(), new String[] { REGION_NAME });
- waitForPrefilledConnections(12);
-
- vm1.invoke("Check Connection Count", () -> checkConnectionCount(6));
- vm2.invoke("Check Connection Count", () -> checkConnectionCount(6));
- vm3.invoke("Check Connection Count", () -> checkConnectionCount(0));
-
+ startBridgeClientInVM(null, pf.getPoolAttributes(), new String[] {REGION_NAME});
+ waitForPrefilledConnections(null, 12);
+
+ checkConnectionCount(vm1, 6);
+ checkConnectionCount(vm2, 6);
+ checkConnectionCount(vm3, 0);
+
LogWriterUtils.getLogWriter().info("pool1 prefilled");
-
+
PoolFactoryImpl pf2 = (PoolFactoryImpl) PoolManager.createFactory();
pf2.init(pf.getPoolAttributes());
pf2.setServerGroup("b");
- PoolImpl pool2 = (PoolImpl) pf2.create("testPool2");
- waitForPrefilledConnections(12, "testPool2");
+ PoolImpl pool2= (PoolImpl) pf2.create("testPool2");
+ waitForPrefilledConnections(null, 12, "testPool2");
// The load will not be perfect, because we created all of the connections
//for group A first.
- vm1.invoke("Check Connection Count", () -> checkConnectionCount(6));
- vm2.invoke("Check Connection Count", () -> checkConnectionCount(9));
- vm3.invoke("Check Connection Count", () -> checkConnectionCount(9));
-
+ checkConnectionCount(vm1, 6);
+ checkConnectionCount(vm2, 9);
+ checkConnectionCount(vm3, 9);
+
LogWriterUtils.getLogWriter().info("pool2 prefilled");
-
+
ServerLocation location1 = new ServerLocation(NetworkUtils.getServerHostName(host), serverPort1);
PoolImpl pool1 = (PoolImpl) PoolManager.getAll().get(POOL_NAME);
Assert.assertEquals("a", pool1.getServerGroup());
-
+
//Use up all of the pooled connections on pool1, and acquire 3 more
- for (int i = 0; i < 15; i++) {
+ for(int i = 0; i < 15; i++) {
pool1.acquireConnection();
}
-
+
LogWriterUtils.getLogWriter().info("aquired 15 connections in pool1");
-
+
//now the load should be equal
- vm1.invoke("Check Connection Count", () -> checkConnectionCount(9));
- vm2.invoke("Check Connection Count", () -> checkConnectionCount(9));
- vm3.invoke("Check Connection Count", () -> checkConnectionCount(9));
-
+ checkConnectionCount(vm1, 9);
+ checkConnectionCount(vm2, 9);
+ checkConnectionCount(vm3, 9);
+
//use up all of the pooled connections on pool2
- for (int i = 0; i < 12; i++) {
+ for(int i = 0; i < 12; i++) {
pool2.acquireConnection();
}
-
+
LogWriterUtils.getLogWriter().info("aquired 12 connections in pool2");
-
+
//interleave creating connections in both pools
- for (int i = 0; i < 6; i++) {
+ for(int i = 0; i < 6; i++) {
pool1.acquireConnection();
pool2.acquireConnection();
}
-
+
LogWriterUtils.getLogWriter().info("interleaved 6 connections from pool1 with 6 connections from pool2");
-
+
//The load should still be balanced
- vm1.invoke("Check Connection Count", () -> checkConnectionCount(13));
- vm2.invoke("Check Connection Count", () -> checkConnectionCount(13));
- vm3.invoke("Check Connection Count", () -> checkConnectionCount(13));
-
+ checkConnectionCount(vm1, 13);
+ checkConnectionCount(vm2, 13);
+ checkConnectionCount(vm3, 13);
+
}
-
+
public void testCustomLoadProbe() throws Exception {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
- // VM vm3 = host.getVM(3);
-
+// VM vm3 = host.getVM(3);
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
+ startLocatorInVM(vm0, locatorPort, "");
String locators = getLocatorString(host, locatorPort);
-
- final ServerLoad load1 = new ServerLoad(.3f, .01f, .44f, 4564f);
- final ServerLoad load2 = new ServerLoad(23.2f, 1.1f, 22.3f, .3f);
- int serverPort1 = vm1.invoke("Start BridgeServer", () -> startBridgeServer(null, locators, new String[] { REGION_NAME }, new MyLoadProbe(load1)));
- int serverPort2 = vm2.invoke("Start BridgeServer", () -> startBridgeServer(null, locators, new String[] { REGION_NAME }, new MyLoadProbe(load2)));
-
+
+ ServerLoad load1= new ServerLoad(.3f, .01f, .44f, 4564f);
+ ServerLoad load2= new ServerLoad(23.2f, 1.1f, 22.3f, .3f);
+ int serverPort1 = startBridgeServerInVM(vm1, null, locators, new String[] {REGION_NAME}, new MyLoadProbe(load1 ));
+ int serverPort2 = startBridgeServerInVM(vm2, null, locators, new String[] {REGION_NAME}, new MyLoadProbe(load2 ));
+
HashMap expected = new HashMap();
ServerLocation l1 = new ServerLocation(NetworkUtils.getServerHostName(host), serverPort1);
ServerLocation l2 = new ServerLocation(NetworkUtils.getServerHostName(host), serverPort2);
expected.put(l1, load1);
expected.put(l2, load2);
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
-
+ checkLocatorLoad(vm0, expected);
+
load1.setConnectionLoad(25f);
- vm1.invoke("changeLoad", () -> changeLoad(load1));
+ changeLoad(vm1, load1);
load2.setSubscriptionConnectionLoad(3.5f);
- vm2.invoke("changeLoad", () -> changeLoad(load2));
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
-
- final ServerLoad load1Updated = new ServerLoad(1f, .1f, 0f, 1f);
- final ServerLoad load2Updated = new ServerLoad(2f, 5f, 0f, 2f);
- expected.put(l1, load1Updated);
- expected.put(l2, load2Updated);
- vm1.invoke("changeLoad", () -> changeLoad(load1Updated));
- vm2.invoke("changeLoad", () -> changeLoad(load2Updated));
- vm0.invoke("check Locator Load", () -> checkLocatorLoad(expected));
-
+ changeLoad(vm2, load2);
+ checkLocatorLoad(vm0, expected);
+
+ load1 = new ServerLoad(1f, .1f, 0f, 1f);
+ load2 = new ServerLoad(2f, 5f, 0f, 2f);
+ expected.put(l1, load1);
+ expected.put(l2, load2);
+ changeLoad(vm1, load1);
+ changeLoad(vm2, load2);
+ checkLocatorLoad(vm0, expected);
+
PoolFactoryImpl pf = new PoolFactoryImpl(null);
pf.addLocator(NetworkUtils.getServerHostName(host), locatorPort);
pf.setMinConnections(20);
pf.setSubscriptionEnabled(true);
pf.setIdleTimeout(-1);
- startBridgeClient(pf.getPoolAttributes(), new String[] { REGION_NAME });
- waitForPrefilledConnections(20);
-
+ startBridgeClientInVM(null, pf.getPoolAttributes(), new String[] {REGION_NAME});
+ waitForPrefilledConnections(null, 20);
+
//The first 10 connection should to go vm1, then 1 to vm2, then another 9 to vm1
//because have unequal values for loadPerConnection
- vm1.invoke("Check Connection Count", () -> checkConnectionCount(19));
- vm2.invoke("Check Connection Count", () -> checkConnectionCount(1));
+ checkConnectionCount(vm1, 19);
+ checkConnectionCount(vm2, 1);
}
-
- public void checkLocatorLoad(final Map expected) {
- List locators = Locator.getLocators();
- Assert.assertEquals(1, locators.size());
- InternalLocator locator = (InternalLocator) locators.get(0);
- final ServerLocator sl = locator.getServerLocatorAdvisee();
- InternalLogWriter log = new LocalLogWriter(InternalLogWriter.FINEST_LEVEL, System.out);
- sl.getDistributionAdvisor().dumpProfiles("PROFILES= ");
- Awaitility.await().pollDelay(100, TimeUnit.MILLISECONDS).pollInterval(100, TimeUnit.MILLISECONDS)
- .timeout(300, TimeUnit.SECONDS).until(() -> expected.equals(sl.getLoadMap()));
+
+ public void checkLocatorLoad(VM vm, final Map expected) {
+ vm.invoke(new SerializableRunnable() {
+ public void run() {
+ List locators = Locator.getLocators();
+ Assert.assertEquals(1, locators.size());
+ InternalLocator locator = (InternalLocator) locators.get(0);
+ final ServerLocator sl = locator.getServerLocatorAdvisee();
+ InternalLogWriter log = new LocalLogWriter(InternalLogWriter.FINEST_LEVEL, System.out);
+ sl.getDistributionAdvisor().dumpProfiles("PROFILES= ");
+ WaitCriterion ev = new WaitCriterion() {
+ public boolean done() {
+ return expected.equals(sl.getLoadMap());
+ }
+ public String description() {
+ return "load map never became equal to " + expected;
+ }
+ };
+ Wait.waitForCriterion(ev, MAX_WAIT, 200, true);
+ }
+ });
}
-
- private void changeLoad(final ServerLoad newLoad) {
- Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
- CacheServer server = cache.getCacheServers().get(0);
- MyLoadProbe probe = (MyLoadProbe) server.getLoadProbe();
- probe.setLoad(newLoad);
+
+ private void changeLoad(VM vm, final ServerLoad newLoad) {
+ vm.invoke(new SerializableRunnable() {
+
+ public void run() {
+ Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
+ CacheServer server = (CacheServer) cache.getCacheServers().get(0);
+ MyLoadProbe probe = (MyLoadProbe) server.getLoadProbe();
+ probe.setLoad(newLoad);
+ }
+
+ });
}
-
+
private static class MyLoadProbe extends ServerLoadProbeAdapter implements Serializable {
private ServerLoad load;
-
+
public MyLoadProbe(ServerLoad load) {
this.load = load;
}
-
+
public ServerLoad getLoad(ServerMetrics metrics) {
float connectionLoad = load.getConnectionLoad()
+ metrics.getConnectionCount() * load.getLoadPerConnection();
@@ -440,7 +493,7 @@ public class LocatorLoadBalancingDUnitTest extends LocatorTestBase {
return new ServerLoad(connectionLoad, load.getLoadPerConnection(),
queueLoad, load.getLoadPerSubscriptionConnection());
}
-
+
public void setLoad(ServerLoad load) {
this.load = load;
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorTestBase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorTestBase.java b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorTestBase.java
index af5ba9c..2207e1d 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorTestBase.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/LocatorTestBase.java
@@ -16,35 +16,52 @@
*/
package com.gemstone.gemfire.cache.client.internal;
-import com.gemstone.gemfire.cache.*;
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import com.gemstone.gemfire.cache.AttributesFactory;
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.CacheFactory;
+import com.gemstone.gemfire.cache.DataPolicy;
+import com.gemstone.gemfire.cache.RegionAttributes;
+import com.gemstone.gemfire.cache.Scope;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.cache.client.PoolManager;
-import com.gemstone.gemfire.cache.server.CacheServer;
import com.gemstone.gemfire.cache.server.ServerLoadProbe;
+import com.gemstone.gemfire.cache.server.CacheServer;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.distributed.Locator;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.AvailablePortHelper;
import com.gemstone.gemfire.internal.cache.PoolFactoryImpl;
-import com.gemstone.gemfire.test.dunit.*;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.*;
+import com.gemstone.gemfire.test.dunit.Assert;
+import com.gemstone.gemfire.test.dunit.DistributedTestCase;
+import com.gemstone.gemfire.test.dunit.Host;
+import com.gemstone.gemfire.test.dunit.Invoke;
+import com.gemstone.gemfire.test.dunit.LogWriterUtils;
+import com.gemstone.gemfire.test.dunit.NetworkUtils;
+import com.gemstone.gemfire.test.dunit.SerializableCallable;
+import com.gemstone.gemfire.test.dunit.SerializableRunnable;
+import com.gemstone.gemfire.test.dunit.VM;
/**
*
*/
-public abstract class LocatorTestBase extends DistributedTestCase {
+public abstract class LocatorTestBase extends DistributedTestCase {
protected static final String CACHE_KEY = "CACHE";
protected static final String LOCATOR_KEY = "LOCATOR";
protected static final String REGION_NAME = "A_REGION";
protected static final String POOL_NAME = "daPool";
protected static final Object CALLBACK_KEY = "callback";
- /**
- * A map for storing temporary objects in a remote VM so that they can be used
+ /** A map for storing temporary objects in a remote VM so that they can be used
* between calls. Cleared after each test.
*/
protected static final HashMap remoteObjects = new HashMap();
@@ -52,211 +69,264 @@ public abstract class LocatorTestBase extends DistributedTestCase {
public LocatorTestBase(String name) {
super(name);
}
-
+
@Override
public final void preTearDown() throws Exception {
-
+
SerializableRunnable tearDown = new SerializableRunnable("tearDown") {
public void run() {
Locator locator = (Locator) remoteObjects.get(LOCATOR_KEY);
- if (locator != null) {
+ if(locator != null) {
try {
locator.stop();
- } catch (Exception e) {
+ } catch(Exception e) {
//do nothing
}
}
-
+
Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
- if (cache != null) {
+ if(cache != null) {
try {
cache.close();
- } catch (Exception e) {
+ } catch(Exception e) {
//do nothing
}
}
remoteObjects.clear();
-
+
}
};
//We seem to like leaving the DS open if we can for
//speed, but lets at least destroy our cache and locator.
Invoke.invokeInEveryVM(tearDown);
tearDown.run();
-
+
postTearDownLocatorTestBase();
}
-
+
protected void postTearDownLocatorTestBase() throws Exception {
}
+
+ protected void startLocatorInVM(final VM vm, final int locatorPort, final String otherLocators) {
+ vm.invoke(new SerializableRunnable("Create Locator") {
- protected void startLocator(final Host vmHost, final int locatorPort, final String otherLocators) {
- disconnectFromDS();
- Properties props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
- props.setProperty(DistributionConfig.LOCATORS_NAME, otherLocators);
- props.setProperty(DistributionConfig.LOG_LEVEL_NAME, LogWriterUtils.getDUnitLogLevel());
- props.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
- File logFile = new File(getUniqueName() + "-locator" + locatorPort + ".log");
- try {
- InetAddress bindAddress = InetAddress.getByName(NetworkUtils.getServerHostName(vmHost));
- Locator locator = Locator.startLocatorAndDS(locatorPort, logFile, bindAddress, props);
- remoteObjects.put(LOCATOR_KEY, locator);
- } catch (UnknownHostException uhe) {
- Assert.fail("While resolving bind address ", uhe);
- } catch (IOException ex) {
- Assert.fail("While starting locator on port " + locatorPort, ex);
- }
+ final String testName= getUniqueName();
+ public void run() {
+ disconnectFromDS();
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
+ props.setProperty(DistributionConfig.LOCATORS_NAME, otherLocators);
+ props.setProperty(DistributionConfig.LOG_LEVEL_NAME, LogWriterUtils.getDUnitLogLevel());
+ props.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+ try {
+ File logFile = new File(testName + "-locator" + locatorPort
+ + ".log");
+ InetAddress bindAddr = null;
+ try {
+ bindAddr = InetAddress.getByName(NetworkUtils.getServerHostName(vm.getHost()));
+ } catch (UnknownHostException uhe) {
+ Assert.fail("While resolving bind address ", uhe);
+ }
+ Locator locator = Locator.startLocatorAndDS(locatorPort, logFile, bindAddr, props);
+ remoteObjects.put(LOCATOR_KEY, locator);
+ } catch (IOException ex) {
+ Assert.fail("While starting locator on port " + locatorPort, ex);
+ }
+ }
+ });
}
-
- protected void stopLocator() {
- Locator locator = (Locator) remoteObjects.remove(LOCATOR_KEY);
- locator.stop();
+
+
+
+ protected void stopLocatorInVM(VM vm) {
+ vm.invoke(new SerializableRunnable("Stop Locator") {
+ public void run() {
+ Locator locator = (Locator) remoteObjects.remove(LOCATOR_KEY);
+ locator.stop();
+ }
+ });
}
-
- protected int startBridgeServer(String[] groups, String locators) throws IOException {
- return startBridgeServer(groups, locators, new String[] { REGION_NAME });
+
+ protected int startBridgeServerInVM(VM vm, String[] groups, String locators) {
+ return startBridgeServerInVM(vm, groups, locators, new String[] {REGION_NAME});
}
+
+ protected int addCacheServerInVM(VM vm, final String[] groups) {
+ SerializableCallable connect =
+ new SerializableCallable("Add Bridge server") {
- protected int addCacheServer(final String[] groups) throws IOException {
- Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
- CacheServer server = cache.addCacheServer();
- server.setPort(0);
- server.setGroups(groups);
- server.start();
- return new Integer(server.getPort());
+ public Object call() throws Exception {
+ Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
+ CacheServer server = cache.addCacheServer();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ server.setPort(serverPort);
+ server.setGroups(groups);
+ server.start();
+ return new Integer(serverPort);
+ }
+ };
+ Integer port = (Integer) vm.invoke(connect);
+ return port.intValue();
}
-
- protected int startBridgeServer(final String[] groups, final String locators, final String[] regions) throws IOException {
- return startBridgeServer(groups, locators, regions, CacheServer.DEFAULT_LOAD_PROBE);
+
+ protected int startBridgeServerInVM(VM vm, final String[] groups, final String locators, final String[] regions) {
+ return startBridgeServerInVM(vm, groups, locators, regions, CacheServer.DEFAULT_LOAD_PROBE);
}
-
- protected int startBridgeServer(final String[] groups, final String locators, final String[] regions, final ServerLoadProbe probe) throws IOException {
- Properties props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
- props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
- DistributedSystem ds = getSystem(props);
- Cache cache = CacheFactory.create(ds);
- AttributesFactory factory = new AttributesFactory();
- factory.setScope(Scope.DISTRIBUTED_ACK);
- factory.setEnableBridgeConflation(true);
- factory.setDataPolicy(DataPolicy.REPLICATE);
- RegionAttributes attributes = factory.create();
- for (int i = 0; i < regions.length; i++) {
- cache.createRegion(regions[i], attributes);
- }
- CacheServer server = cache.addCacheServer();
- server.setPort(0);
- server.setGroups(groups);
- server.setLoadProbe(probe);
- server.start();
-
- remoteObjects.put(CACHE_KEY, cache);
-
- return new Integer(server.getPort());
+
+ protected int startBridgeServerInVM(VM vm, final String[] groups, final String locators, final String[] regions, final ServerLoadProbe probe) {
+ SerializableCallable connect =
+ new SerializableCallable("Start bridge server") {
+ public Object call() throws IOException {
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
+ props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+ DistributedSystem ds = getSystem(props);
+ Cache cache = CacheFactory.create(ds);
+ AttributesFactory factory = new AttributesFactory();
+ factory.setScope(Scope.DISTRIBUTED_ACK);
+ factory.setEnableBridgeConflation(true);
+ factory.setDataPolicy(DataPolicy.REPLICATE);
+ RegionAttributes attrs = factory.create();
+ for(int i = 0; i < regions.length; i++) {
+ cache.createRegion(regions[i], attrs);
+ }
+ CacheServer server = cache.addCacheServer();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ server.setPort(serverPort);
+ server.setGroups(groups);
+ server.setLoadProbe(probe);
+ server.start();
+
+ remoteObjects.put(CACHE_KEY, cache);
+
+ return new Integer(serverPort);
+ }
+ };
+ Integer port = (Integer) vm.invoke(connect);
+ return port.intValue();
}
-
- protected int startBridgeServerWithEmbeddedLocator(final String[] groups, final String locators, final String[] regions, final ServerLoadProbe probe)
- throws IOException {
- Properties props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
- props.setProperty(DistributionConfig.START_LOCATOR_NAME, locators);
- props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
- DistributedSystem ds = getSystem(props);
- Cache cache = CacheFactory.create(ds);
- AttributesFactory factory = new AttributesFactory();
- factory.setScope(Scope.DISTRIBUTED_ACK);
- factory.setEnableBridgeConflation(true);
- factory.setDataPolicy(DataPolicy.REPLICATE);
- RegionAttributes attrs = factory.create();
- for (int i = 0; i < regions.length; i++) {
- cache.createRegion(regions[i], attrs);
- }
- CacheServer server = cache.addCacheServer();
- server.setGroups(groups);
- server.setLoadProbe(probe);
- server.setPort(0);
- server.start();
-
- remoteObjects.put(CACHE_KEY, cache);
-
- return new Integer(server.getPort());
+
+ protected int startBridgeServerWithEmbeddedLocator(VM vm, final String[] groups, final String locators, final String[] regions, final ServerLoadProbe probe) {
+ SerializableCallable connect =
+ new SerializableCallable("Start bridge server") {
+ public Object call() throws IOException {
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
+ props.setProperty(DistributionConfig.START_LOCATOR_NAME, locators);
+ props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+ DistributedSystem ds = getSystem(props);
+ Cache cache = CacheFactory.create(ds);
+ AttributesFactory factory = new AttributesFactory();
+ factory.setScope(Scope.DISTRIBUTED_ACK);
+ factory.setEnableBridgeConflation(true);
+ factory.setDataPolicy(DataPolicy.REPLICATE);
+ RegionAttributes attrs = factory.create();
+ for(int i = 0; i < regions.length; i++) {
+ cache.createRegion(regions[i], attrs);
+ }
+ CacheServer server = cache.addCacheServer();
+ server.setGroups(groups);
+ server.setLoadProbe(probe);
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ server.setPort(serverPort);
+ server.start();
+
+ remoteObjects.put(CACHE_KEY, cache);
+
+ return new Integer(serverPort);
+ }
+ };
+ Integer port = (Integer) vm.invoke(connect);
+ return port.intValue();
}
-
- protected void startBridgeClient(final String group, final String host, final int port) throws Exception {
- startBridgeClient(group, host, port, new String[] { REGION_NAME });
+
+ protected void startBridgeClientInVM(VM vm, final String group, final String host, final int port) throws Exception {
+ startBridgeClientInVM(vm, group, host, port, new String[] {REGION_NAME});
}
+
- protected void startBridgeClient(final String group, final String host, final int port, final String[] regions) throws Exception {
+ protected void startBridgeClientInVM(VM vm, final String group, final String host, final int port, final String[] regions) throws Exception {
PoolFactoryImpl pf = new PoolFactoryImpl(null);
pf.addLocator(host, port)
- .setServerGroup(group)
- .setPingInterval(200)
- .setSubscriptionEnabled(true)
- .setSubscriptionRedundancy(-1);
- startBridgeClient(pf.getPoolAttributes(), regions);
+ .setServerGroup(group)
+ .setPingInterval(200)
+ .setSubscriptionEnabled(true)
+ .setSubscriptionRedundancy(-1);
+ startBridgeClientInVM(vm, pf.getPoolAttributes(), regions);
}
-
- protected void startBridgeClient(final Pool pool, final String[] regions) throws Exception {
- Properties props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
- props.setProperty(DistributionConfig.LOCATORS_NAME, "");
- DistributedSystem ds = getSystem(props);
- Cache cache = CacheFactory.create(ds);
- AttributesFactory factory = new AttributesFactory();
- factory.setScope(Scope.LOCAL);
- // factory.setEnableBridgeConflation(true);
- // factory.setDataPolicy(DataPolicy.NORMAL);
- factory.setPoolName(POOL_NAME);
- PoolFactoryImpl pf = (PoolFactoryImpl) PoolManager.createFactory();
- pf.init(pool);
- LocatorDiscoveryCallback locatorCallback = new MyLocatorCallback();
- remoteObjects.put(CALLBACK_KEY, locatorCallback);
- pf.setLocatorDiscoveryCallback(locatorCallback);
- pf.create(POOL_NAME);
-
- RegionAttributes attrs = factory.create();
- for (int i = 0; i < regions.length; i++) {
- cache.createRegion(regions[i], attrs);
+
+ protected void startBridgeClientInVM(VM vm, final Pool pool, final String[] regions) throws Exception {
+ SerializableRunnable connect =
+ new SerializableRunnable("Start bridge client") {
+ public void run() {
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
+ props.setProperty(DistributionConfig.LOCATORS_NAME, "");
+ DistributedSystem ds = getSystem(props);
+ Cache cache = CacheFactory.create(ds);
+ AttributesFactory factory = new AttributesFactory();
+ factory.setScope(Scope.LOCAL);
+// factory.setEnableBridgeConflation(true);
+// factory.setDataPolicy(DataPolicy.NORMAL);
+ factory.setPoolName(POOL_NAME);
+ PoolFactoryImpl pf= (PoolFactoryImpl) PoolManager.createFactory();
+ pf.init(pool);
+ LocatorDiscoveryCallback locatorCallback = new MyLocatorCallback();
+ remoteObjects.put(CALLBACK_KEY, locatorCallback);
+ pf.setLocatorDiscoveryCallback(locatorCallback);
+ pf.create(POOL_NAME);
+
+
+ RegionAttributes attrs = factory.create();
+ for(int i = 0; i < regions.length; i++) {
+ cache.createRegion(regions[i], attrs);
+ }
+
+ remoteObjects.put(CACHE_KEY, cache);
+ }
+ };
+
+ if(vm == null) {
+ connect.run();
+ } else {
+ vm.invoke(connect);
}
-
- remoteObjects.put(CACHE_KEY, cache);
}
-
+
protected void stopBridgeMemberVM(VM vm) {
- vm.invoke(new SerializableRunnable("Stop bridge member") {
- public void run() {
- Cache cache = (Cache) remoteObjects.remove(CACHE_KEY);
- cache.close();
- disconnectFromDS();
- }
- });
+ vm.invoke(new SerializableRunnable("Stop bridge member") {
+ public void run() {
+ Cache cache = (Cache) remoteObjects.remove(CACHE_KEY);
+ cache.close();
+ disconnectFromDS();
+ }
+ });
}
-
+
public String getLocatorString(Host host, int locatorPort) {
- return getLocatorString(host, new int[] { locatorPort });
+ return getLocatorString(host, new int[] {locatorPort});
}
-
+
public String getLocatorString(Host host, int[] locatorPorts) {
StringBuffer str = new StringBuffer();
- for (int i = 0; i < locatorPorts.length; i++) {
+ for(int i = 0; i < locatorPorts.length; i++) {
str.append(NetworkUtils.getServerHostName(host))
.append("[")
.append(locatorPorts[i])
.append("]");
- if (i < locatorPorts.length - 1) {
+ if(i < locatorPorts.length - 1) {
str.append(",");
}
}
-
+
return str.toString();
}
-
+
protected static class MyLocatorCallback extends LocatorDiscoveryCallbackAdapter {
private final Set discoveredLocators = new HashSet();
private final Set removedLocators = new HashSet();
-
+
public synchronized void locatorsDiscovered(List locators) {
discoveredLocators.addAll(locators);
notifyAll();
@@ -266,29 +336,29 @@ public abstract class LocatorTestBase extends DistributedTestCase {
removedLocators.addAll(locators);
notifyAll();
}
-
+
public boolean waitForDiscovery(InetSocketAddress locator, long time) throws InterruptedException {
return waitFor(discoveredLocators, locator, time);
}
-
+
public boolean waitForRemove(InetSocketAddress locator, long time) throws InterruptedException {
return waitFor(removedLocators, locator, time);
}
-
+
private synchronized boolean waitFor(Set set, InetSocketAddress locator, long time) throws InterruptedException {
long remaining = time;
long endTime = System.currentTimeMillis() + time;
- while (!set.contains(locator) && remaining >= 0) {
+ while(!set.contains(locator) && remaining >= 0) {
wait(remaining);
- remaining = endTime - System.currentTimeMillis();
+ remaining = endTime - System.currentTimeMillis();
}
return set.contains(locator);
}
-
+
public synchronized Set getDiscovered() {
return new HashSet(discoveredLocators);
}
-
+
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/Bug47667DUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/Bug47667DUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/Bug47667DUnitTest.java
index 0f08456..de43c29 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/Bug47667DUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/Bug47667DUnitTest.java
@@ -56,11 +56,11 @@ public class Bug47667DUnitTest extends LocatorTestBase {
final int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
final String locatorHost = NetworkUtils.getServerHostName(host);
- locator.invoke("Start Locator",() ->startLocator(locator.getHost(), locatorPort, ""));
+ startLocatorInVM(locator, locatorPort, "");
String locString = getLocatorString(host, locatorPort);
- server1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] {"R1"}, locString, new String[] {"R1"}));
- server2.invoke("Start BridgeServer", () -> startBridgeServer(new String[] {"R2"}, locString, new String[] {"R2"}));
+ startBridgeServerInVM(server1, new String[] {"R1"}, locString, new String[] {"R1"});
+ startBridgeServerInVM(server2, new String[] {"R2"}, locString, new String[] {"R2"});
client.invoke(new SerializableCallable() {
@Override
@@ -70,15 +70,15 @@ public class Bug47667DUnitTest extends LocatorTestBase {
ClientCache cache = ccf.create();
PoolManager.createFactory().addLocator(locatorHost, locatorPort).setServerGroup("R1").create("R1");
PoolManager.createFactory().addLocator(locatorHost, locatorPort).setServerGroup("R2").create("R2");
- Region region1 = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).setPoolName("R1").create("R1");
- Region region2 = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).setPoolName("R2").create("R2");
- CacheTransactionManager transactionManager = cache.getCacheTransactionManager();
- transactionManager.begin();
- region1.put(1, "value1");
- transactionManager.commit();
- transactionManager.begin();
- region2.put(2, "value2");
- transactionManager.commit();
+ Region r1 = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).setPoolName("R1").create("R1");
+ Region r2 = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).setPoolName("R2").create("R2");
+ CacheTransactionManager mgr = cache.getCacheTransactionManager();
+ mgr.begin();
+ r1.put(1, "value1");
+ mgr.commit();
+ mgr.begin();
+ r2.put(2, "value2");
+ mgr.commit();
return null;
}
});
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-cq/src/test/java/com/gemstone/gemfire/management/CacheServerManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/management/CacheServerManagementDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/management/CacheServerManagementDUnitTest.java
index 167cc3a..d784397 100644
--- a/geode-cq/src/test/java/com/gemstone/gemfire/management/CacheServerManagementDUnitTest.java
+++ b/geode-cq/src/test/java/com/gemstone/gemfire/management/CacheServerManagementDUnitTest.java
@@ -16,9 +16,26 @@
*/
package com.gemstone.gemfire.management;
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Collections;
+import java.util.Properties;
+
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanServer;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.client.internal.LocatorTestBase;
-import com.gemstone.gemfire.cache.query.*;
+import com.gemstone.gemfire.cache.query.IndexExistsException;
+import com.gemstone.gemfire.cache.query.IndexInvalidException;
+import com.gemstone.gemfire.cache.query.IndexNameConflictException;
+import com.gemstone.gemfire.cache.query.QueryService;
+import com.gemstone.gemfire.cache.query.RegionNotFoundException;
import com.gemstone.gemfire.cache.query.cq.dunit.CqQueryDUnitTest;
import com.gemstone.gemfire.cache.query.internal.cq.CqService;
import com.gemstone.gemfire.cache.server.CacheServer;
@@ -29,34 +46,37 @@ import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.internal.AvailablePortHelper;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.management.internal.JmxManagerLocatorRequest;
+import com.gemstone.gemfire.management.internal.JmxManagerLocatorResponse;
import com.gemstone.gemfire.management.internal.MBeanJMXAdapter;
import com.gemstone.gemfire.management.internal.SystemManagementService;
-import com.gemstone.gemfire.test.dunit.*;
-
-import javax.management.*;
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Collections;
-import java.util.Properties;
+import com.gemstone.gemfire.test.dunit.Assert;
+import com.gemstone.gemfire.test.dunit.Host;
+import com.gemstone.gemfire.test.dunit.LogWriterUtils;
+import com.gemstone.gemfire.test.dunit.NetworkUtils;
+import com.gemstone.gemfire.test.dunit.SerializableRunnable;
+import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.dunit.Wait;
+import com.gemstone.gemfire.test.dunit.WaitCriterion;
/**
* Cache Server related management test cases
+ *
+ *
*/
public class CacheServerManagementDUnitTest extends LocatorTestBase {
private static final long serialVersionUID = 1L;
-
- private static int CONNECT_LOCATOR_TIMEOUT_MS = 30000;
+
+ private static int CONNECT_LOCATOR_TIMEOUT_MS = 30000;
private ManagementTestBase helper;
private static final String queryName = "testClientWithFeederAndCQ_0";
private static final String indexName = "testIndex";
-
+
private static MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
+
protected CqQueryDUnitTest cqDUnitTest = new CqQueryDUnitTest(
"CqDataDUnitTest");
@@ -64,7 +84,7 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
public CacheServerManagementDUnitTest(String name) {
super(name);
this.helper = new ManagementTestBase(name);
-
+
}
@Override
@@ -78,6 +98,7 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
}
/**
+ *
* @throws Exception
*/
public void testCacheServerMBean() throws Exception {
@@ -91,11 +112,12 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
helper.startManagingNode(managingNode);
//helper.createCache(server);
int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
- cqDUnitTest.createServer(server, serverPort);
-
+ cqDUnitTest.createServer(server,serverPort);
+
+
DistributedMember member = helper.getMember(server);
-
- verifyCacheServer(server, serverPort);
+
+ verifyCacheServer(server,serverPort);
final int port = server.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server.getHost());
@@ -123,10 +145,10 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
// Close.
Wait.pause(2000);
- checkNavigation(managingNode, member, serverPort);
- verifyIndex(server, serverPort);
+ checkNavigation(managingNode,member,serverPort);
+ verifyIndex(server,serverPort);
// This will test all CQs and will close the cq in its final step
- verifyCacheServerRemote(managingNode, member, serverPort);
+ verifyCacheServerRemote(managingNode, member,serverPort);
verifyClosedCQ(server);
@@ -140,30 +162,30 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
/**
* Test for client server connection related management artifacts
- * like notifications
- *
+ * like notifications
* @throws Exception
*/
-
+
public void testCacheClient() throws Exception {
-
+
final Host host = Host.getHost(0);
VM locator = host.getVM(0);
VM server = host.getVM(1);
VM client = host.getVM(2);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- locator.invoke("Start Locator", () -> startLocator(locator.getHost(), locatorPort, ""));
-
- String locators = NetworkUtils.getServerHostName(locator.getHost()) + "[" + locatorPort + "]";
-
- int serverPort = server.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
-
- addClientNotifListener(server, serverPort);
+ startLocatorInVM(locator, locatorPort, "");
+
+ String locators = NetworkUtils.getServerHostName(locator.getHost())+ "[" + locatorPort + "]";
+
+
+ int serverPort = startBridgeServerInVM(server, null, locators);
+
+ addClientNotifListener(server,serverPort);
// Start a client and make sure that proper notification is received
- client.invoke("Start BridgeClient", () -> startBridgeClient(null, NetworkUtils.getServerHostName(locator.getHost()), locatorPort));
-
+ startBridgeClientInVM(client, null, NetworkUtils.getServerHostName(locator.getHost()), locatorPort);
+
//stop the client and make sure the bridge server notifies
stopBridgeMemberVM(client);
helper.closeCache(locator);
@@ -171,14 +193,13 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
helper.closeCache(client);
}
-
+
/**
* Intention of this test is to check if a node becomes manager after all the nodes are alive
* it should have all the information of all the members.
- * <p>
+ *
* Thats why used service.getLocalManager().runManagementTaskAdhoc() to make node
* ready for federation when manager node comes up
- *
* @throws Exception
*/
@@ -187,72 +208,96 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
final Host host = Host.getHost(0);
VM locator = host.getVM(0);
VM server = host.getVM(1);
-
+
//Step 1:
final int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- locator.invoke("Start Locator", () -> startLocator(locator.getHost(), locatorPort, ""));
-
- String locators = NetworkUtils.getServerHostName(locator.getHost()) + "[" + locatorPort + "]";
+ startLocator(locator, locatorPort, "");
+ String locators = NetworkUtils.getServerHostName(locator.getHost())+ "[" + locatorPort + "]";
+
//Step 2:
- server.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
-
+ int serverPort = startBridgeServerInVM(server, null, locators);
+
//Step 3:
- server.invoke("Check Server", () -> {
- Cache cache = GemFireCacheImpl.getInstance();
- assertNotNull(cache);
- SystemManagementService service = (SystemManagementService) ManagementService
- .getExistingManagementService(cache);
- assertNotNull(service);
- assertFalse(service.isManager());
- assertNotNull(service.getMemberMXBean());
- service.getLocalManager().runManagementTaskAdhoc();
+ server.invoke(new SerializableRunnable("Check Server") {
+
+ public void run() {
+ Cache cache = GemFireCacheImpl.getInstance();
+ assertNotNull(cache);
+ SystemManagementService service = (SystemManagementService)ManagementService
+ .getExistingManagementService(cache);
+ assertNotNull(service);
+ assertFalse(service.isManager());
+ assertNotNull(service.getMemberMXBean());
+ service.getLocalManager().runManagementTaskAdhoc();
+
+
+ }
});
+
+ //Step 4:
+ JmxManagerLocatorResponse locRes = JmxManagerLocatorRequest.send(locator
+ .getHost().getHostName(), locatorPort, CONNECT_LOCATOR_TIMEOUT_MS, Collections.<String, String> emptyMap());
+
+ //Step 5:
+ locator.invoke(new SerializableRunnable("Check locator") {
- //Step 4:
- JmxManagerLocatorRequest.send(locator
- .getHost().getHostName(), locatorPort, CONNECT_LOCATOR_TIMEOUT_MS, Collections.<String, String>emptyMap());
-
- //Step 5:
- locator.invoke("Check locator", () -> {
- Cache cache = GemFireCacheImpl.getInstance();
- assertNotNull(cache);
- ManagementService service = ManagementService
- .getExistingManagementService(cache);
- assertNotNull(service);
- assertTrue(service.isManager());
- LocatorMXBean bean = service.getLocalLocatorMXBean();
- assertEquals(locatorPort, bean.getPort());
- DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
-
- assertEquals(2, dsBean.listMemberObjectNames().length);
+ public void run() {
+ Cache cache = GemFireCacheImpl.getInstance();
+ assertNotNull(cache);
+ ManagementService service = ManagementService
+ .getExistingManagementService(cache);
+ assertNotNull(service);
+ assertTrue(service.isManager());
+ LocatorMXBean bean = service.getLocalLocatorMXBean();
+ assertEquals(locatorPort, bean.getPort());
+ DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
+ ObjectName[] names = dsBean.listMemberObjectNames();
+
+ assertEquals(2,dsBean.listMemberObjectNames().length);
+
+ }
});
+
+
helper.closeCache(locator);
helper.closeCache(server);
-
+
+
}
+
+
+ protected void startLocator(final VM vm, final int locatorPort, final String otherLocators) {
+ vm.invoke(new SerializableRunnable("Create Locator") {
- protected void startLocator(Host vmHost, final int locatorPort, final String otherLocators) {
- disconnectFromDS();
- Properties props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
- props.setProperty(DistributionConfig.LOCATORS_NAME, otherLocators);
- props.setProperty(DistributionConfig.LOG_LEVEL_NAME, LogWriterUtils.getDUnitLogLevel());
- props.setProperty(DistributionConfig.JMX_MANAGER_HTTP_PORT_NAME, "0");
- props.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
- File logFile = new File(getUniqueName() + "-locator" + locatorPort + ".log");
- try {
- InetAddress bindAddr = InetAddress.getByName(NetworkUtils.getServerHostName(vmHost));
- Locator locator = Locator.startLocatorAndDS(locatorPort, logFile, bindAddr, props);
- remoteObjects.put(LOCATOR_KEY, locator);
- } catch (UnknownHostException uhe) {
- Assert.fail("While resolving bind address ", uhe);
- } catch (IOException ex) {
- Assert.fail("While starting locator on port " + locatorPort, ex);
- }
+ final String testName= getUniqueName();
+ public void run() {
+ disconnectFromDS();
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
+ props.setProperty(DistributionConfig.LOCATORS_NAME, otherLocators);
+ props.setProperty(DistributionConfig.LOG_LEVEL_NAME, LogWriterUtils.getDUnitLogLevel());
+ props.setProperty(DistributionConfig.JMX_MANAGER_HTTP_PORT_NAME, "0");
+ props.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+ try {
+ File logFile = new File(testName + "-locator" + locatorPort
+ + ".log");
+ InetAddress bindAddr = null;
+ try {
+ bindAddr = InetAddress.getByName(NetworkUtils.getServerHostName(vm.getHost()));
+ } catch (UnknownHostException uhe) {
+ Assert.fail("While resolving bind address ", uhe);
+ }
+ Locator locator = Locator.startLocatorAndDS(locatorPort, logFile, bindAddr, props);
+ remoteObjects.put(LOCATOR_KEY, locator);
+ } catch (IOException ex) {
+ Assert.fail("While starting locator on port " + locatorPort, ex);
+ }
+ }
+ });
}
-
+
protected void checkNavigation(final VM vm,
final DistributedMember cacheServerMember, final int serverPort) {
SerializableRunnable checkNavigation = new SerializableRunnable(
@@ -282,14 +327,14 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
};
vm.invoke(checkNavigation);
}
-
+
/**
* Verify the Cache Server details
- *
+ *
* @param vm
*/
@SuppressWarnings("serial")
- protected void addClientNotifListener(final VM vm, final int serverPort) throws Exception {
+ protected void addClientNotifListener(final VM vm , final int serverPort) throws Exception {
SerializableRunnable addClientNotifListener = new SerializableRunnable(
"Add Client Notif Listener") {
public void run() {
@@ -314,19 +359,18 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
TestCacheServerNotif nt = new TestCacheServerNotif();
try {
mbeanServer.addNotificationListener(MBeanJMXAdapter
- .getClientServiceMBeanName(serverPort, cache.getDistributedSystem().getMemberId()), nt, null, null);
+ .getClientServiceMBeanName(serverPort,cache.getDistributedSystem().getMemberId()), nt, null, null);
} catch (InstanceNotFoundException e) {
fail("Failed With Exception " + e);
}
-
+
}
};
vm.invoke(addClientNotifListener);
}
-
/**
* Verify the closed CQ which is closed from Managing Node
- *
+ *
* @param vm
*/
@SuppressWarnings("serial")
@@ -361,7 +405,7 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
bean.removeIndex(indexName);
} catch (Exception e) {
fail("Failed With Exception " + e);
-
+
}
assertEquals(bean.getIndexCount(), 0);
@@ -372,7 +416,7 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
/**
* Verify the closed CQ which is closed from Managing Node
- *
+ *
* @param vm
*/
@SuppressWarnings("serial")
@@ -390,9 +434,11 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
vm.invoke(verifyClosedCQ);
}
+
+
/**
* Verify the Cache Server details
- *
+ *
* @param vm
*/
@SuppressWarnings("serial")
@@ -450,7 +496,7 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
/**
* Verify the Cache Server details
- *
+ *
* @param vm
*/
@SuppressWarnings("serial")
@@ -476,14 +522,14 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
LogWriterUtils.getLogWriter().info(
"<ExpectedString> Active Query Count "
+ bean.getActiveCQCount() + "</ExpectedString> ");
-
+
LogWriterUtils.getLogWriter().info(
"<ExpectedString> Registered Query Count "
+ bean.getRegisteredCQCount() + "</ExpectedString> ");
- assertTrue(bean.showAllClientStats()[0].getClientCQCount() == 1);
- int numQueues = bean.getNumSubscriptions();
- assertEquals(numQueues, 1);
+ assertTrue(bean.showAllClientStats()[0].getClientCQCount() == 1);
+ int numQueues = bean.getNumSubscriptions();
+ assertEquals(numQueues, 1);
// test for client connection Count
/* @TODO */
@@ -506,9 +552,11 @@ public class CacheServerManagementDUnitTest extends LocatorTestBase {
};
vm.invoke(verifyCacheServerRemote);
}
-
+
/**
* Notification handler
+ *
+ *
*/
private static class TestCacheServerNotif implements
NotificationListener {
[2/3] incubator-geode git commit: Revert "GEODE-1376: Cleaned up
server port to be '0'."
Posted by bs...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsWithSSLDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsWithSSLDUnitTest.java b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsWithSSLDUnitTest.java
index 692ff19..2e80ebf 100644
--- a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsWithSSLDUnitTest.java
+++ b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsWithSSLDUnitTest.java
@@ -19,6 +19,7 @@ package com.gemstone.gemfire.rest.internal.web.controllers;
import com.gemstone.gemfire.cache.*;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
+import com.gemstone.gemfire.cache.client.ClientRegionFactory;
import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
import com.gemstone.gemfire.cache.client.internal.LocatorTestBase;
import com.gemstone.gemfire.cache.server.CacheServer;
@@ -30,10 +31,7 @@ import com.gemstone.gemfire.internal.AvailablePortHelper;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.management.ManagementException;
import com.gemstone.gemfire.management.ManagementTestBase;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.IgnoredException;
-import com.gemstone.gemfire.test.dunit.NetworkUtils;
-import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.dunit.*;
import com.gemstone.gemfire.util.test.TestUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
@@ -49,12 +47,13 @@ import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.BindException;
import java.security.KeyStore;
-import java.util.Date;
+import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
+ *
* @since 8.0
*/
public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
@@ -64,13 +63,13 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
private ManagementTestBase helper;
private final String PEOPLE_REGION_NAME = "People";
-
+
private File jks;
public RestAPIsWithSSLDUnitTest(String name) {
super(name);
this.helper = new ManagementTestBase(name);
- this.jks = findTrustedJKS();
+ this.jks = findTrustedJKS();
}
@@ -86,22 +85,32 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
}
private File findTrustedJKS() {
- if (jks == null) {
+ if(jks == null){
jks = new File(TestUtil.getResourcePath(RestAPIsWithSSLDUnitTest.class, "/ssl/trusted.keystore"));
}
return jks;
}
+ public String startBridgeServerWithRestServiceOnInVM(final VM vm, final String locators, final String[] regions,
+ final Properties sslProperties, final boolean clusterLevel) {
+
+ final String hostName = vm.getHost().getHostName();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ vm.invoke("startBridge", () -> startBridgeServer(hostName,serverPort,locators,regions,sslProperties,clusterLevel));
+ return "https://" + hostName + ":" + serverPort + "/gemfire-api/v1";
+
+ }
+
@SuppressWarnings("deprecation")
- protected int startBridgeServer(String hostName, int restServicePort, final String locators, final String[] regions,
+ protected int startBridgeServer(String hostName, int restServicerPort, final String locators, final String[] regions,
final Properties sslProperties, boolean clusterLevel) {
Properties props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
props.setProperty(DistributionConfig.START_DEV_REST_API_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_BIND_ADDRESS_NAME, hostName);
- props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(restServicePort));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(restServicerPort));
System.setProperty("javax.net.debug", "ssl,handshake");
configureSSL(props, sslProperties, clusterLevel);
@@ -109,8 +118,8 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
DistributedSystem ds = getSystem(props);
Cache cache = CacheFactory.create(ds);
((GemFireCacheImpl) cache).setReadSerialized(true);
-
AttributesFactory factory = new AttributesFactory();
+
factory.setEnableBridgeConflation(true);
factory.setDataPolicy(DataPolicy.REPLICATE);
RegionAttributes attrs = factory.create();
@@ -119,45 +128,81 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
}
CacheServer server = cache.addCacheServer();
- server.setPort(0);
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ server.setPort(serverPort);
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
}
remoteObjects.put(CACHE_KEY, cache);
- return new Integer(server.getPort());
+ return new Integer(serverPort);
}
public void doPutsInClientCache() {
- ClientCache clientCache = ClientCacheFactory.getAnyInstance();
- assertNotNull(clientCache);
- Region<String, Object> region = clientCache.getRegion(PEOPLE_REGION_NAME);
+ ClientCache cache = GemFireCacheImpl.getInstance();
+ assertNotNull(cache);
+ Region<String, Object> region = cache.getRegion(PEOPLE_REGION_NAME);
// put person object
- region.put("1", new Person(101L, "Mithali", "Dorai", "Raj", new Date(), Gender.FEMALE));
- region.put("2", new Person(102L, "Sachin", "Ramesh", "Tendulkar", new Date(), Gender.MALE));
- region.put("3", new Person(103L, "Saurabh", "Baburav", "Ganguly", new Date(), Gender.MALE));
- region.put("4", new Person(104L, "Rahul", "subrymanyam", "Dravid", new Date(), Gender.MALE));
- region.put("5", new Person(105L, "Jhulan", "Chidambaram", "Goswami", new Date(), Gender.FEMALE));
+ final Person person1 = new Person(101L, "Mithali", "Dorai", "Raj", DateTimeUtils.createDate(1982,
+ Calendar.DECEMBER, 4), Gender.FEMALE);
+ final Person person2 = new Person(102L, "Sachin", "Ramesh", "Tendulkar", DateTimeUtils.createDate(1975,
+ Calendar.DECEMBER, 14), Gender.MALE);
+ final Person person3 = new Person(103L, "Saurabh", "Baburav", "Ganguly", DateTimeUtils.createDate(1972,
+ Calendar.AUGUST, 29), Gender.MALE);
+ final Person person4 = new Person(104L, "Rahul", "subrymanyam", "Dravid", DateTimeUtils.createDate(1979,
+ Calendar.MARCH, 17), Gender.MALE);
+ final Person person5 = new Person(105L, "Jhulan", "Chidambaram", "Goswami", DateTimeUtils.createDate(1983,
+ Calendar.NOVEMBER, 25), Gender.FEMALE);
+
+ region.put("1", person1);
+ region.put("2", person2);
+ region.put("3", person3);
+ region.put("4", person4);
+ region.put("5", person5);
+
+ final Person person6 = new Person(101L, "Rahul", "Rajiv", "Gndhi",
+ DateTimeUtils.createDate(1970, Calendar.MAY, 14), Gender.MALE);
+ final Person person7 = new Person(102L, "Narendra", "Damodar", "Modi", DateTimeUtils.createDate(1945,
+ Calendar.DECEMBER, 24), Gender.MALE);
+ final Person person8 = new Person(103L, "Atal", "Bihari", "Vajpayee", DateTimeUtils.createDate(1920,
+ Calendar.AUGUST, 9), Gender.MALE);
+ final Person person9 = new Person(104L, "Soniya", "Rajiv", "Gandhi", DateTimeUtils.createDate(1929, Calendar.MARCH,
+ 27), Gender.FEMALE);
+ final Person person10 = new Person(104L, "Priyanka", "Robert", "Gandhi", DateTimeUtils.createDate(1973,
+ Calendar.APRIL, 15), Gender.FEMALE);
+
+ final Person person11 = new Person(104L, "Murali", "Manohar", "Joshi", DateTimeUtils.createDate(1923,
+ Calendar.APRIL, 25), Gender.MALE);
+ final Person person12 = new Person(104L, "Lalkrishna", "Parmhansh", "Advani", DateTimeUtils.createDate(1910,
+ Calendar.JANUARY, 01), Gender.MALE);
+ final Person person13 = new Person(104L, "Shushma", "kumari", "Swaraj", DateTimeUtils.createDate(1943,
+ Calendar.AUGUST, 10), Gender.FEMALE);
+ final Person person14 = new Person(104L, "Arun", "raman", "jetly", DateTimeUtils.createDate(1942, Calendar.OCTOBER,
+ 27), Gender.MALE);
+ final Person person15 = new Person(104L, "Amit", "kumar", "shah", DateTimeUtils.createDate(1958, Calendar.DECEMBER,
+ 21), Gender.MALE);
+ final Person person16 = new Person(104L, "Shila", "kumari", "Dixit", DateTimeUtils.createDate(1927,
+ Calendar.FEBRUARY, 15), Gender.FEMALE);
Map<String, Object> userMap = new HashMap<String, Object>();
- userMap.put("6", new Person(101L, "Rahul", "Rajiv", "Gndhi", new Date(), Gender.MALE));
- userMap.put("7", new Person(102L, "Narendra", "Damodar", "Modi", new Date(), Gender.MALE));
- userMap.put("8", new Person(103L, "Atal", "Bihari", "Vajpayee", new Date(), Gender.MALE));
- userMap.put("9", new Person(104L, "Soniya", "Rajiv", "Gandhi", new Date(), Gender.FEMALE));
- userMap.put("10", new Person(104L, "Priyanka", "Robert", "Gandhi", new Date(), Gender.FEMALE));
- userMap.put("11", new Person(104L, "Murali", "Manohar", "Joshi", new Date(), Gender.MALE));
- userMap.put("12", new Person(104L, "Lalkrishna", "Parmhansh", "Advani", new Date(), Gender.MALE));
- userMap.put("13", new Person(104L, "Shushma", "kumari", "Swaraj", new Date(), Gender.FEMALE));
- userMap.put("14", new Person(104L, "Arun", "raman", "jetly", new Date(), Gender.MALE));
- userMap.put("15", new Person(104L, "Amit", "kumar", "shah", new Date(), Gender.MALE));
- userMap.put("16", new Person(104L, "Shila", "kumari", "Dixit", new Date(), Gender.FEMALE));
+ userMap.put("6", person6);
+ userMap.put("7", person7);
+ userMap.put("8", person8);
+ userMap.put("9", person9);
+ userMap.put("10", person10);
+ userMap.put("11", person11);
+ userMap.put("12", person12);
+ userMap.put("13", person13);
+ userMap.put("14", person14);
+ userMap.put("15", person15);
+ userMap.put("16", person16);
region.putAll(userMap);
- if (clientCache != null)
- clientCache.getLogger().info("Gemfire Cache Client: Puts successfully done");
+ if (cache != null)
+ cache.getLogger().info("Gemfire Cache Client: Puts successfully done");
}
@@ -172,30 +217,24 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
// start locator
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- locator.invoke("Start Locator", () -> startLocator(locator.getHost(), locatorPort, ""));
+ startLocatorInVM(locator, locatorPort, "");
// find locators
String locators = NetworkUtils.getServerHostName(locator.getHost()) + "[" + locatorPort + "]";
// start manager (peer cache)
- manager.invoke("StartManager", () -> startManager(locators, new String[] { REGION_NAME }, sslProperties));
+ startManagerInVM(manager, locators, new String[] { REGION_NAME }, sslProperties);
// start startBridgeServer With RestService enabled
- String restEndpoint = server.invoke("startBridgeServerWithRestServiceOnInVM", () -> {
- final String hostName = server.getHost().getHostName();
- final int restServicePort = AvailablePortHelper.getRandomAvailableTCPPort();
- startBridgeServer(hostName, restServicePort, locators, new String[] { REGION_NAME }, sslProperties, clusterLevel);
- return "https://" + hostName + ":" + restServicePort + "/gemfire-api/v1";
- });
+ String restEndpoint = startBridgeServerWithRestServiceOnInVM(server, locators, new String[] { REGION_NAME },
+ sslProperties, clusterLevel);
// create a client cache
- client.invoke("Create ClientCache", () -> new ClientCacheFactory()
- .setPdxReadSerialized(true)
- .addPoolLocator(NetworkUtils.getServerHostName(locator.getHost()), locatorPort).create());
+ createClientCacheInVM(client, NetworkUtils.getServerHostName(locator.getHost()), locatorPort);
// create region in Manager, peer cache and Client cache nodes
- manager.invoke("createRegionInManager", () -> createRegionInCache());
- server.invoke("createRegionInPeerServer", () -> createRegionInCache());
+ manager.invoke("createRegionInManager",() -> createRegionInManager());
+ server.invoke("createRegionInPeerServer", () -> createRegionInPeerServer());
client.invoke("createRegionInClientCache", () -> createRegionInClientCache());
// do some person puts from clientcache
@@ -221,114 +260,191 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
helper.closeCache(client);
}
- private void sslPropertyConverter(Properties properties, Properties newProperties, String propertyName, String newPropertyName) {
- String property = properties.getProperty(propertyName);
- if (property != null) {
- newProperties.setProperty((newPropertyName != null ? newPropertyName : propertyName), property);
+ private void createClientCacheInVM(VM vm, final String host, final int port) throws Exception {
+ SerializableRunnable connect = new SerializableRunnable("Start Cache client") {
+ public void run() {
+ // Connect using the GemFire locator and create a Caching_Proxy cache
+ ClientCache clientCache = new ClientCacheFactory().setPdxReadSerialized(true).addPoolLocator(host, port).create();
+ clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(REGION_NAME);
+ }
+ };
+
+ if (vm == null) {
+ connect.run();
+ } else {
+ vm.invoke(connect);
}
}
private void configureSSL(Properties props, Properties sslProperties, boolean clusterLevel) {
- if (clusterLevel) {
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, DistributionConfig.CLUSTER_SSL_ENABLED_NAME);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, DistributionConfig.CLUSTER_SSL_KEYSTORE_NAME);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME,
- DistributionConfig.CLUSTER_SSL_KEYSTORE_PASSWORD_NAME);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME, DistributionConfig.CLUSTER_SSL_KEYSTORE_TYPE_NAME);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, DistributionConfig.CLUSTER_SSL_PROTOCOLS_NAME);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME,
- DistributionConfig.CLUSTER_SSL_REQUIRE_AUTHENTICATION_NAME);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME, DistributionConfig.CLUSTER_SSL_TRUSTSTORE_NAME);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME,
- DistributionConfig.CLUSTER_SSL_TRUSTSTORE_PASSWORD_NAME);
- } else {
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, null);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, null);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, null);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME, null);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, null);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME, null);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME, null);
- sslPropertyConverter(sslProperties, props, DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME, null);
+ if(clusterLevel){
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME) != null) {
+ props.setProperty(DistributionConfig.CLUSTER_SSL_ENABLED_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME) != null) {
+ props.setProperty(DistributionConfig.CLUSTER_SSL_KEYSTORE_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME) != null) {
+ props.setProperty(DistributionConfig.CLUSTER_SSL_KEYSTORE_PASSWORD_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME) != null) {
+ props.setProperty(DistributionConfig.CLUSTER_SSL_KEYSTORE_TYPE_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME) != null) {
+ props.setProperty(DistributionConfig.CLUSTER_SSL_PROTOCOLS_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME) != null) {
+ props.setProperty(DistributionConfig.CLUSTER_SSL_REQUIRE_AUTHENTICATION_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME) != null) {
+ props.setProperty(DistributionConfig.CLUSTER_SSL_TRUSTSTORE_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME) != null) {
+ props.setProperty(DistributionConfig.CLUSTER_SSL_TRUSTSTORE_PASSWORD_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME));
+ }
+
+ }else{
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME) != null) {
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME) != null) {
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME) != null) {
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME) != null) {
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME) != null) {
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME) != null) {
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME) != null) {
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME));
+ }
+ if (sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME) != null) {
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME,
+ sslProperties.getProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME));
+ }
+
}
+
+
}
- private void startManager(final String locators, final String[] regions, final Properties sslProperties) throws IOException {
-
+ private int startManagerInVM(VM vm, final String locators, final String[] regions, final Properties sslProperties) {
+
IgnoredException.addIgnoredException("java.net.BindException");
IgnoredException.addIgnoredException("java.rmi.server.ExportException");
IgnoredException.addIgnoredException("com.gemstone.gemfire.management.ManagementException");
-
- Properties props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
- props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
- props.setProperty("jmx-manager", "true");
- props.setProperty("jmx-manager-start", "true");
-
- Cache cache = null;
- configureSSL(props, sslProperties, false);
- while (true) {
- try {
- DistributedSystem ds = getSystem(props);
- System.out.println("Creating cache with http-service-port " + props.getProperty("http-service-port", "7070")
- + " and jmx-manager-port " + props.getProperty("jmx-manager-port", "1099"));
- cache = CacheFactory.create(ds);
- System.out.println("Successfully created cache.");
- break;
- } catch (ManagementException ex) {
- if ((ex.getCause() instanceof BindException)
- || (ex.getCause() != null && ex.getCause().getCause() instanceof BindException)) {
- //close cache and disconnect
- GemFireCacheImpl existingInstance = GemFireCacheImpl.getInstance();
- if (existingInstance != null) {
- existingInstance.close();
+
+ SerializableCallable connect = new SerializableCallable("Start Manager ") {
+ public Object call() throws IOException {
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
+ props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+ props.setProperty("jmx-manager", "true");
+ props.setProperty("jmx-manager-start", "true");
+
+ Cache cache = null;
+ while (true) {
+ try {
+ configureSSL(props, sslProperties, false);
+ DistributedSystem ds = getSystem(props);
+ System.out.println("Creating cache with http-service-port " + props.getProperty("http-service-port", "7070")
+ + " and jmx-manager-port " + props.getProperty("jmx-manager-port", "1099"));
+ cache = CacheFactory.create(ds);
+ System.out.println("Successfully created cache.");
+ break;
}
- InternalDistributedSystem ids = InternalDistributedSystem
- .getConnectedInstance();
- if (ids != null) {
- ids.disconnect();
+ catch (ManagementException ex) {
+ if ((ex.getCause() instanceof BindException)
+ || (ex.getCause() != null && ex.getCause().getCause() instanceof BindException)) {
+ //close cache and disconnect
+ GemFireCacheImpl existingInstance = GemFireCacheImpl.getInstance();
+ if (existingInstance != null) {
+ existingInstance.close();
+ }
+ InternalDistributedSystem ids = InternalDistributedSystem
+ .getConnectedInstance();
+ if (ids != null) {
+ ids.disconnect();
+ }
+ //try a different port
+ int httpServicePort = AvailablePortHelper.getRandomAvailableTCPPort();
+ int jmxManagerPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ props.setProperty("http-service-port", Integer.toString(httpServicePort));
+ props.setProperty("jmx-manager-port", Integer.toString(jmxManagerPort));
+ System.out.println("Try a different http-service-port " + httpServicePort);
+ System.out.println("Try a different jmx-manager-port " + jmxManagerPort);
+ }
+ else {
+ throw ex;
+ }
}
- //try a different port
- int httpServicePort = AvailablePortHelper.getRandomAvailableTCPPort();
- int jmxManagerPort = AvailablePortHelper.getRandomAvailableTCPPort();
- props.setProperty("http-service-port", Integer.toString(httpServicePort));
- props.setProperty("jmx-manager-port", Integer.toString(jmxManagerPort));
- System.out.println("Try a different http-service-port " + httpServicePort);
- System.out.println("Try a different jmx-manager-port " + jmxManagerPort);
- } else {
- throw ex;
+ }
+ AttributesFactory factory = new AttributesFactory();
+
+ factory.setEnableBridgeConflation(true);
+ factory.setDataPolicy(DataPolicy.REPLICATE);
+ RegionAttributes attrs = factory.create();
+ for (int i = 0; i < regions.length; i++) {
+ cache.createRegion(regions[i], attrs);
}
- }
- }
- AttributesFactory factory = new AttributesFactory();
+ CacheServer server = cache.addCacheServer();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ server.setPort(serverPort);
+ server.start();
- factory.setEnableBridgeConflation(true);
- factory.setDataPolicy(DataPolicy.REPLICATE);
- RegionAttributes attrs = factory.create();
- for (int i = 0; i < regions.length; i++) {
- cache.createRegion(regions[i], attrs);
- }
- CacheServer server = cache.addCacheServer();
- server.setPort(0);
- server.start();
+ return new Integer(serverPort);
+ }
+ };
+ Integer port = (Integer) vm.invoke(connect);
+ return port.intValue();
}
private void createRegionInClientCache() {
- ClientCache clientCache = ClientCacheFactory.getAnyInstance();
- assertNotNull(clientCache);
- clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(PEOPLE_REGION_NAME);
- clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(REGION_NAME);
+ ClientCache cache = GemFireCacheImpl.getInstance();
+ assertNotNull(cache);
+ ClientRegionFactory<String, Object> crf = cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
+ crf.create(PEOPLE_REGION_NAME);
}
- private void createRegionInCache() {
+ private void createRegionInManager() {
Cache cache = GemFireCacheImpl.getInstance();
assertNotNull(cache);
- RegionFactory<String, Object> regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
- regionFactory.create(PEOPLE_REGION_NAME);
+ RegionFactory<String, Object> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
+ rf.create(PEOPLE_REGION_NAME);
}
- private CloseableHttpClient getSSLBasedHTTPClient() throws Exception {
+ private void createRegionInPeerServer() {
+ Cache cache = GemFireCacheImpl.getInstance();
+ assertNotNull(cache);
+ RegionFactory<String, Object> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
+ rf.create(PEOPLE_REGION_NAME);
+ }
+
+ private CloseableHttpClient getSSLBasedHTTPClient(String algo) throws Exception {
+
File jks = findTrustedJKS();
KeyStore clientKeys = KeyStore.getInstance("JKS");
@@ -338,7 +454,7 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(clientKeys, new TrustSelfSignedStrategy())
.loadKeyMaterial(clientKeys, "password".toCharArray())
- .build();
+ .build();
// Host checking is disabled here , as tests might run on multiple hosts and
// host entries can not be assumed
@@ -350,7 +466,7 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
return httpclient;
}
- private void validateConnection(String restEndpoint) {
+ private void validateConnection(String restEndpoint, String algo) {
try {
// 1. Get on key="1" and validate result.
@@ -359,7 +475,8 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
get.addHeader("Content-Type", "application/json");
get.addHeader("Accept", "application/json");
- CloseableHttpClient httpclient = getSSLBasedHTTPClient();
+
+ CloseableHttpClient httpclient = getSSLBasedHTTPClient(algo);
CloseableHttpResponse response = httpclient.execute(get);
HttpEntity entity = response.getEntity();
@@ -384,7 +501,7 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
throw new RuntimeException("unexpected exception", e);
}
}
-
+
// Actual Tests starts here.
public void testSimpleSSL() throws Exception {
@@ -394,80 +511,90 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME, "JKS");
- validateConnection(startInfraWithSSL(props, false));
+ String restEndpoint = startInfraWithSSL(props,false);
+ validateConnection(restEndpoint, "SSL");
}
-
+
public void testSSLWithoutKeyStoreType() throws Exception {
+
+
Properties props = new Properties();
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "SSL");
- validateConnection(startInfraWithSSL(props, false));
}
-
+
public void testSSLWithSSLProtocol() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "SSL");
-
- validateConnection(startInfraWithSSL(props, false));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,"SSL");
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "SSL");
}
-
+
public void testSSLWithTLSProtocol() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "TLS");
-
- validateConnection(startInfraWithSSL(props, false));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,"TLS");
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "TLS");
}
-
+
public void testSSLWithTLSv11Protocol() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "TLSv1.1");
-
- validateConnection(startInfraWithSSL(props, false));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,"TLSv1.1");
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "TLSv1.1");
}
-
+
public void testSSLWithTLSv12Protocol() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "TLSv1.2");
-
- validateConnection(startInfraWithSSL(props, false));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,"TLSv1.2");
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "TLSv1.2");
}
-
+
public void testWithMultipleProtocol() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "SSL,TLSv1.2");
-
- validateConnection(startInfraWithSSL(props, false));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,"SSL,TLSv1.2");
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "TLSv1.2");
}
-
+
public void testSSLWithCipherSuite() throws Exception {
System.setProperty("javax.net.debug", "ssl");
@@ -475,51 +602,57 @@ public class RestAPIsWithSSLDUnitTest extends LocatorTestBase {
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "TLSv1.2");
-
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,"TLSv1.2");
+
SSLContext ssl = SSLContext.getInstance("TLSv1.2");
-
+
ssl.init(null, null, new java.security.SecureRandom());
String[] cipherSuites = ssl.getSocketFactory().getSupportedCipherSuites();
-
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_CIPHERS_NAME, cipherSuites[0]);
-
- validateConnection(startInfraWithSSL(props, false));
+
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_CIPHERS_NAME,cipherSuites[0]);
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "TLSv1.2");
}
-
+
public void testSSLWithMultipleCipherSuite() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "TLSv1.2");
-
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,"TLSv1.2");
+
SSLContext ssl = SSLContext.getInstance("TLSv1.2");
-
+
ssl.init(null, null, new java.security.SecureRandom());
String[] cipherSuites = ssl.getSocketFactory().getSupportedCipherSuites();
-
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_CIPHERS_NAME, cipherSuites[0] + "," + cipherSuites[1]);
-
- validateConnection(startInfraWithSSL(props, false));
+
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_CIPHERS_NAME,cipherSuites[0]+","+cipherSuites[1]);
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "TLSv1.2");
}
-
+
+
public void testMutualAuthentication() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "SSL");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME, "true");
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME,"SSL");
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION_NAME,"true");
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME, jks.getCanonicalPath());
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_NAME,jks.getCanonicalPath());
- props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME, "password");
- validateConnection(startInfraWithSSL(props, false));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME,"password");
+
+ String restEndpoint = startInfraWithSSL(props, false);
+ validateConnection(restEndpoint, "SSL");
}
+
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceDUnitTest.java
index ad578c5..cfcff5e 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceDUnitTest.java
@@ -16,6 +16,15 @@
*/
package com.gemstone.gemfire.cache.client.internal;
+import java.io.Serializable;
+import java.net.BindException;
+import java.net.InetSocketAddress;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+import junit.framework.Assert;
+
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.client.NoAvailableLocatorsException;
@@ -28,23 +37,22 @@ import com.gemstone.gemfire.internal.AvailablePortHelper;
import com.gemstone.gemfire.management.membership.ClientMembership;
import com.gemstone.gemfire.management.membership.ClientMembershipEvent;
import com.gemstone.gemfire.management.membership.ClientMembershipListenerAdapter;
-import com.gemstone.gemfire.test.dunit.*;
-import org.junit.Assert;
-
-import java.io.Serializable;
-import java.net.BindException;
-import java.net.InetSocketAddress;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
+import com.gemstone.gemfire.test.dunit.Host;
+import com.gemstone.gemfire.test.dunit.IgnoredException;
+import com.gemstone.gemfire.test.dunit.NetworkUtils;
+import com.gemstone.gemfire.test.dunit.SerializableCallable;
+import com.gemstone.gemfire.test.dunit.SerializableRunnable;
+import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.dunit.Wait;
/**
* Tests cases that are particular for the auto connection source
- * - dynamically discovering servers, locators, handling
+ * - dynamically discovering servers, locators, handling
* locator disappearance, etc.
+ *
*/
public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
-
+
protected static final Object BRIDGE_LISTENER = "BRIDGE_LISTENER";
private static final long MAX_WAIT = 60000;
@@ -56,85 +64,84 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
public AutoConnectionSourceDUnitTest(String name) {
super(name);
}
-
+
public void testDiscoverBridgeServers() throws Exception {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
-
- String locators = NetworkUtils.getServerHostName(vm0.getHost()) + "[" + locatorPort + "]";
+ startLocatorInVM(vm0, locatorPort, "");
+
+ String locators = NetworkUtils.getServerHostName(vm0.getHost())+ "[" + locatorPort + "]";
+
+ startBridgeServerInVM(vm1, null, locators);
- vm1.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
-
- vm2.invoke("StartBridgeClient", () -> startBridgeClient(null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort));
+ startBridgeClientInVM(vm2, null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort);
putAndWaitForSuccess(vm2, REGION_NAME, "key", "value");
-
+
Assert.assertEquals("value", getInVM(vm1, "key"));
}
public void testNoLocators() {
-
+
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
-
+
try {
- vm0.invoke("StartBridgeClient", () -> startBridgeClient(null, NetworkUtils.getServerHostName(vm0.getHost())
- , AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET)));
+ startBridgeClientInVM(vm0, null, NetworkUtils.getServerHostName(vm0.getHost()), AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET));
putInVM(vm0, "key", "value");
fail("Client cache should not have been able to start");
- } catch (Exception e) {
+ } catch(Exception e) {
//expected an exception
}
}
-
+
public void testNoBridgeServer() {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
- try {
- vm1.invoke("StartBridgeClient", () -> startBridgeClient(null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort));
+ startLocatorInVM(vm0, locatorPort, "");
+ try {
+ startBridgeClientInVM(vm1, null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort);
putInVM(vm0, "key", "value");
fail("Client cache should not have been able to start");
- } catch (Exception e) {
+ } catch(Exception e) {
//expected an exception
}
}
-
- public void testDynamicallyFindBridgeServer() throws Exception {
+
+ public void testDynamicallyFindBridgeServer() throws Exception {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
-
+ startLocatorInVM(vm0, locatorPort, "");
+
String locators = NetworkUtils.getServerHostName(vm0.getHost()) + "[" + locatorPort + "]";
-
- vm1.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
-
- vm2.invoke("StartBridgeClient", () -> startBridgeClient(null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort));
-
+
+ startBridgeServerInVM(vm1, null, locators);
+
+ startBridgeClientInVM(vm2, null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort);
+
putAndWaitForSuccess(vm2, REGION_NAME, "key", "value");
-
- vm3.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
-
+
+ startBridgeServerInVM(vm3, null, locators);
+
stopBridgeMemberVM(vm1);
-
+
putAndWaitForSuccess(vm2, REGION_NAME, "key2", "value2");
-
+
Assert.assertEquals("value2", getInVM(vm3, "key2"));
}
-
+
public void testDynamicallyFindLocators() throws Exception {
try {
final Host host = Host.getHost(0);
@@ -143,60 +150,59 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
-
+
int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(3);
-
+
final int locatorPort0 = ports[0];
final int locatorPort1 = ports[1];
final int locatorPort3 = ports[2];
- String locators = getLocatorString(host, new int[] { locatorPort0, locatorPort1, locatorPort3 });
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort0, locators));
- vm1.invoke("Start Locator", () -> startLocator(vm1.getHost(), locatorPort1, locators));
-
- vm2.invoke("StartBridgeClient", () -> startBridgeClient(null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort0));
-
- InetSocketAddress locatorToWaitFor = new InetSocketAddress(hostName, locatorPort1);
+ String locators = getLocatorString(host, new int[] { locatorPort0, locatorPort1, locatorPort3});
+ startLocatorInVM(vm0, locatorPort0, locators);
+
+ startLocatorInVM(vm1, locatorPort1, locators);
+ startBridgeClientInVM(vm2, null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort0);
+
+ InetSocketAddress locatorToWaitFor= new InetSocketAddress(hostName, locatorPort1);
waitForLocatorDiscovery(vm2, locatorToWaitFor);
-
- vm0.invoke("Stop Locator", () -> stopLocator());
- vm0.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
-
+
+ stopLocatorInVM(vm0);
+ startBridgeServerInVM(vm0, null, locators);
+
putAndWaitForSuccess(vm2, REGION_NAME, "key", "value");
Assert.assertEquals("value", getInVM(vm0, "key"));
-
- vm3.invoke("Start Locator", () -> startLocator(vm3.getHost(), locatorPort3, locators));
+
+ startLocatorInVM(vm3, locatorPort3, locators);
stopBridgeMemberVM(vm0);
- locatorToWaitFor = new InetSocketAddress(hostName, locatorPort3);
+ locatorToWaitFor= new InetSocketAddress(hostName, locatorPort3);
waitForLocatorDiscovery(vm2, locatorToWaitFor);
- vm1.invoke("Stop Locator", () -> stopLocator());
- vm1.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
+ stopLocatorInVM(vm1);
+ startBridgeServerInVM(vm1, null, locators);
putAndWaitForSuccess(vm2, REGION_NAME, "key2", "value2");
Assert.assertEquals("value2", getInVM(vm1, "key2"));
- } catch (Exception ec) {
- if (ec.getCause() != null && (ec.getCause().getCause() instanceof BindException))
+ }catch(Exception ec) {
+ if(ec.getCause() != null && (ec.getCause().getCause() instanceof BindException))
return;//BindException let it pass
throw ec;
}
}
-
- public void testEmbeddedLocator() throws Exception {
+
+ public void testEmbeddedLocator() throws Exception {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-
+
String locators = NetworkUtils.getServerHostName(vm0.getHost()) + "[" + locatorPort + "]";
-
- vm0.invoke("Start BridgeServer", () -> startBridgeServerWithEmbeddedLocator(null, locators, new String[] { REGION_NAME }
- , CacheServer.DEFAULT_LOAD_PROBE));
-
- vm2.invoke("StartBridgeClient", () -> startBridgeClient(null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort));
-
+
+ startBridgeServerWithEmbeddedLocator(vm0, null, locators, new String[] {REGION_NAME}, CacheServer.DEFAULT_LOAD_PROBE);
+
+ startBridgeClientInVM(vm2, null, NetworkUtils.getServerHostName(vm0.getHost()), locatorPort);
+
putAndWaitForSuccess(vm2, REGION_NAME, "key", "value");
-
+
Assert.assertEquals("value", getInVM(vm2, "key"));
}
@@ -205,7 +211,7 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
vm.invoke(new SerializableCallable() {
public Object call() throws InterruptedException {
MyLocatorCallback callback = (MyLocatorCallback) remoteObjects.get(CALLBACK_KEY);
-
+
boolean discovered = callback.waitForDiscovery(locatorToWaitFor, MAX_WAIT);
Assert.assertTrue("Waited " + MAX_WAIT + " for " + locatorToWaitFor
+ " to be discovered on client. List is now: "
@@ -214,89 +220,85 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
+
public void testServerGroups() throws Exception {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
-
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
-
+ startLocatorInVM(vm0, locatorPort, "");
+
String locators = NetworkUtils.getServerHostName(vm0.getHost()) + "[" + locatorPort + "]";
+
+ startBridgeServerInVM(vm1, new String[] {"group1", "group2"} , locators, new String[] {"A", "B"});
+ startBridgeServerInVM(vm2, new String[] {"group2", "group3"}, locators, new String[] {"B", "C"});
- vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "group1", "group2" }, locators, new String[] { "A", "B" }));
- vm2.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "group2", "group3" }, locators, new String[] { "B", "C" }));
-
- vm3.invoke("StartBridgeClient", () -> startBridgeClient("group1", NetworkUtils.getServerHostName(vm0.getHost())
- , locatorPort, new String[] { "A", "B", "C" }));
+
+ startBridgeClientInVM(vm3, "group1", NetworkUtils.getServerHostName(vm0.getHost()), locatorPort, new String [] {"A", "B", "C"});
putAndWaitForSuccess(vm3, "A", "key", "value");
Assert.assertEquals("value", getInVM(vm1, "A", "key"));
try {
putInVM(vm3, "C", "key2", "value2");
fail("Should not have been able to find Region C on the server");
- } catch (Exception expected) {
- }
-
+ } catch(Exception expected) {}
+
stopBridgeMemberVM(vm3);
-
- vm3.invoke("StartBridgeClient", () -> startBridgeClient("group3", NetworkUtils.getServerHostName(vm0.getHost()),
- locatorPort, new String[] { "A", "B", "C" }));
+
+ startBridgeClientInVM(vm3, "group3", NetworkUtils.getServerHostName(vm0.getHost()), locatorPort, new String [] {"A", "B", "C"});
try {
putInVM(vm3, "A", "key3", "value");
fail("Should not have been able to find Region A on the server");
- } catch (Exception expected) {
- }
+ } catch(Exception expected) {}
putInVM(vm3, "C", "key4", "value");
Assert.assertEquals("value", getInVM(vm2, "C", "key4"));
-
+
stopBridgeMemberVM(vm3);
-
- vm3.invoke("StartBridgeClient", () -> startBridgeClient("group2", NetworkUtils.getServerHostName(vm0.getHost()),
- locatorPort, new String[] { "A", "B", "C" }));
+
+ startBridgeClientInVM(vm3, "group2", NetworkUtils.getServerHostName(vm0.getHost()), locatorPort, new String [] {"A", "B", "C"});
putInVM(vm3, "B", "key5", "value");
Assert.assertEquals("value", getInVM(vm1, "B", "key5"));
Assert.assertEquals("value", getInVM(vm2, "B", "key5"));
-
+
stopBridgeMemberVM(vm1);
putInVM(vm3, "B", "key6", "value");
Assert.assertEquals("value", getInVM(vm2, "B", "key6"));
- vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "group1", "group2" }, locators, new String[] { "A", "B" }));
+ startBridgeServerInVM(vm1, new String[] {"group1", "group2"} , locators, new String[] {"A", "B"});
stopBridgeMemberVM(vm2);
-
+
putInVM(vm3, "B", "key7", "value");
Assert.assertEquals("value", getInVM(vm1, "B", "key7"));
}
-
+
public void testTwoServersInSameVM() throws Exception {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
- // VM vm3 = host.getVM(3);
-
+// VM vm3 = host.getVM(3);
+
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-
- vm0.invoke("Start Locator", () -> startLocator(vm0.getHost(), locatorPort, ""));
-
+
+ startLocatorInVM(vm0, locatorPort, "");
+
final String locators = NetworkUtils.getServerHostName(vm0.getHost()) + "[" + locatorPort + "]";
-
- final int serverPort1 = vm1.invoke("Start BridgeServer", () -> startBridgeServer(new String[] { "group1" }, locators));
- final int serverPort2 = vm1.invoke("Start CacheServer", () -> addCacheServer(new String[] { "group2" }));
-
- vm2.invoke("StartBridgeClient", () -> startBridgeClient("group2", NetworkUtils.getServerHostName(vm0.getHost()), locatorPort));
-
- checkEndpoints(vm2, new int[] { serverPort2 });
-
+
+ final int serverPort1 =startBridgeServerInVM(vm1, new String[] {"group1"}, locators);
+ final int serverPort2 =addCacheServerInVM(vm1, new String[] {"group2"});
+
+ startBridgeClientInVM(vm2, "group2", NetworkUtils.getServerHostName(vm0.getHost()), locatorPort);
+
+ checkEndpoints(vm2, new int[] {serverPort2});
+
stopBridgeMemberVM(vm2);
- vm2.invoke("StartBridgeClient", () -> startBridgeClient("group1", NetworkUtils.getServerHostName(vm0.getHost()), locatorPort));
-
- checkEndpoints(vm2, new int[] { serverPort1 });
+ startBridgeClientInVM(vm2, "group1", NetworkUtils.getServerHostName(vm0.getHost()), locatorPort);
+
+ checkEndpoints(vm2, new int[] {serverPort1});
}
-
+
public void testClientMembershipListener() throws Exception {
final Host host = Host.getHost(0);
VM locatorVM = host.getVM(0);
@@ -304,20 +306,19 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
VM bridge2VM = host.getVM(2);
VM clientVM = host.getVM(3);
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- locatorVM.invoke("Start Locator", () -> startLocator(locatorVM.getHost(), locatorPort, ""));
-
+ startLocatorInVM(locatorVM, locatorPort, "");
String locators = NetworkUtils.getServerHostName(locatorVM.getHost()) + "[" + locatorPort + "]";
//start a bridge server with a listener
addBridgeListener(bridge1VM);
- int serverPort1 = bridge1VM.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
+ int serverPort1 = startBridgeServerInVM(bridge1VM, null, locators);
//start a bridge client with a listener
addBridgeListener(clientVM);
- clientVM.invoke("StartBridgeClient", () -> startBridgeClient(null, NetworkUtils.getServerHostName(locatorVM.getHost()), locatorPort));
+ startBridgeClientInVM(clientVM, null, NetworkUtils.getServerHostName(locatorVM.getHost()), locatorPort);
// wait for client to connect
- checkEndpoints(clientVM, new int[] { serverPort1 });
-
+ checkEndpoints(clientVM, new int[] {serverPort1});
+
//make sure the client and bridge server both noticed each other
waitForJoin(bridge1VM);
MyListener serverListener = getBridgeListener(bridge1VM);
@@ -325,48 +326,48 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
Assert.assertEquals(0, serverListener.getDepartures());
Assert.assertEquals(1, serverListener.getJoins());
resetBridgeListener(bridge1VM);
-
+
waitForJoin(clientVM);
- MyListener clientListener = getBridgeListener(clientVM);
+ MyListener clientListener= getBridgeListener(clientVM);
Assert.assertEquals(0, clientListener.getCrashes());
Assert.assertEquals(0, clientListener.getDepartures());
Assert.assertEquals(1, clientListener.getJoins());
resetBridgeListener(clientVM);
-
- checkEndpoints(clientVM, new int[] { serverPort1 });
+
+ checkEndpoints(clientVM, new int[] {serverPort1});
//start another bridge server and make sure it is detected by the client
- int serverPort2 = bridge2VM.invoke("Start BridgeServer", () -> startBridgeServer(null, locators));
-
- checkEndpoints(clientVM, new int[] { serverPort1, serverPort2 });
+ int serverPort2 = startBridgeServerInVM(bridge2VM, null, locators);
+
+ checkEndpoints(clientVM, new int[] {serverPort1, serverPort2});
serverListener = getBridgeListener(bridge1VM);
Assert.assertEquals(0, serverListener.getCrashes());
Assert.assertEquals(0, serverListener.getDepartures());
Assert.assertEquals(0, serverListener.getJoins());
resetBridgeListener(bridge1VM);
waitForJoin(clientVM);
- clientListener = getBridgeListener(clientVM);
+ clientListener= getBridgeListener(clientVM);
Assert.assertEquals(0, clientListener.getCrashes());
Assert.assertEquals(0, clientListener.getDepartures());
Assert.assertEquals(1, clientListener.getJoins());
resetBridgeListener(clientVM);
-
+
//stop the second bridge server and make sure it is detected by the client
stopBridgeMemberVM(bridge2VM);
-
- checkEndpoints(clientVM, new int[] { serverPort1 });
+
+ checkEndpoints(clientVM, new int[] {serverPort1});
serverListener = getBridgeListener(bridge1VM);
Assert.assertEquals(0, serverListener.getCrashes());
Assert.assertEquals(0, serverListener.getDepartures());
Assert.assertEquals(0, serverListener.getJoins());
resetBridgeListener(bridge1VM);
waitForCrash(clientVM);
- clientListener = getBridgeListener(clientVM);
+ clientListener= getBridgeListener(clientVM);
Assert.assertEquals(1, clientListener.getCrashes());
Assert.assertEquals(0, clientListener.getDepartures());
Assert.assertEquals(0, clientListener.getJoins());
resetBridgeListener(clientVM);
-
+
//stop the client and make sure the bridge server notices
stopBridgeMemberVM(clientVM);
waitForDeparture(bridge1VM);
@@ -379,7 +380,7 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
protected Object getInVM(VM vm, final Serializable key) {
return getInVM(vm, REGION_NAME, key);
}
-
+
protected Object getInVM(VM vm, final String regionName, final Serializable key) {
return vm.invoke(new SerializableCallable("Get in VM") {
public Object call() throws Exception {
@@ -389,22 +390,23 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
- protected void putAndWaitForSuccess(VM vm, final String regionName, final Serializable key, final Serializable value) throws InterruptedException {
+
+ protected void putAndWaitForSuccess(VM vm, final String regionName, final Serializable key, final Serializable value) throws InterruptedException
+ {
long endTime = System.currentTimeMillis() + MAX_WAIT;
long remaining = MAX_WAIT;
int i = 0;
- while (true) {
+ while(true) {
try {
System.err.println("Attempt: " + (i++));
putInVM(vm, regionName, key, value);
break;
} catch (NoAvailableLocatorsException | com.gemstone.gemfire.test.dunit.RMIException e) {
- if (!(e instanceof NoAvailableLocatorsException)
+ if( !(e instanceof NoAvailableLocatorsException)
&& !(e.getCause() instanceof NoAvailableServersException)) {
throw e;
}
- if (remaining <= 0) {
+ if(remaining <= 0) {
throw e;
}
Wait.pause(100);
@@ -416,8 +418,10 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
protected void putInVM(VM vm, final Serializable key, final Serializable value) {
putInVM(vm, REGION_NAME, key, value);
}
-
- protected void putInVM(VM vm, final String regionName, final Serializable key, final Serializable value) {
+
+
+
+ protected void putInVM(VM vm, final String regionName, final Serializable key, final Serializable value) {
vm.invoke(new SerializableCallable("Put in VM") {
public Object call() throws Exception {
Cache cache = (Cache) remoteObjects.get(CACHE_KEY);
@@ -426,12 +430,11 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
+
/**
* Assert that there is one endpoint with the given host in port
* on the client vm.
- *
- * @param vm - the vm the client is running in
+ * @param vm - the vm the client is running in
* @param expectedPorts - The server ports we expect the client to be connected to.
*/
protected void checkEndpoints(VM vm, final int[] expectedPorts) {
@@ -442,14 +445,14 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
List/*<ServerLocation>*/ endpoints;
HashSet actualEndpointPorts;
HashSet expectedEndpointPorts = new HashSet();
- for (int i = 0; i < expectedPorts.length; i++) {
+ for(int i = 0; i < expectedPorts.length; i++) {
expectedEndpointPorts.add(new Integer(expectedPorts[i]));
}
do {
endpoints = pool.getCurrentServers();
actualEndpointPorts = new HashSet();
- for (Iterator itr = endpoints.iterator(); itr.hasNext(); ) {
- ServerLocation sl = (ServerLocation) itr.next();
+ for(Iterator itr = endpoints.iterator(); itr.hasNext();) {
+ ServerLocation sl = (ServerLocation)itr.next();
actualEndpointPorts.add(new Integer(sl.getPort()));
}
if (expectedEndpointPorts.size() == actualEndpointPorts.size()) {
@@ -457,12 +460,12 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
} else {
Wait.pause(100);
}
- } while (retryCount-- > 0);
+ } while(retryCount-- > 0);
Assert.assertEquals(expectedEndpointPorts, actualEndpointPorts);
}
});
}
-
+
protected void addBridgeListener(VM vm) {
vm.invoke(new SerializableRunnable("Add membership listener") {
public void run() {
@@ -472,7 +475,7 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
+
protected void resetBridgeListener(VM vm) {
vm.invoke(new SerializableRunnable("Add membership listener") {
public void run() {
@@ -481,7 +484,7 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
+
private MyListener getBridgeListener(VM vm) {
return (MyListener) vm.invoke(new SerializableCallable("Add membership listener") {
public Object call() {
@@ -489,17 +492,17 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
+
private void waitForJoin(VM vm) {
vm.invoke(new SerializableRunnable() {
public void run() {
MyListener listener = (MyListener) remoteObjects.get(BRIDGE_LISTENER);
- synchronized (listener) {
+ synchronized(listener) {
long end = System.currentTimeMillis() + 10000;
while (listener.joins == 0) {
try {
long remaining = end - System.currentTimeMillis();
- if (remaining < 0) {
+ if(remaining < 0) {
break;
}
listener.wait(remaining);
@@ -511,17 +514,17 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
+
private void waitForCrash(VM vm) {
vm.invoke(new SerializableRunnable() {
public void run() {
MyListener listener = (MyListener) remoteObjects.get(BRIDGE_LISTENER);
- synchronized (listener) {
+ synchronized(listener) {
long end = System.currentTimeMillis() + 10000;
- while (listener.crashes == 0) {
+ while (listener.crashes== 0) {
try {
long remaining = end - System.currentTimeMillis();
- if (remaining < 0) {
+ if(remaining < 0) {
break;
}
listener.wait(remaining);
@@ -533,17 +536,17 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
+
private void waitForDeparture(VM vm) {
vm.invoke(new SerializableRunnable() {
public void run() {
MyListener listener = (MyListener) remoteObjects.get(BRIDGE_LISTENER);
- synchronized (listener) {
+ synchronized(listener) {
long end = System.currentTimeMillis() + 10000;
while (listener.departures == 0) {
try {
long remaining = end - System.currentTimeMillis();
- if (remaining < 0) {
+ if(remaining < 0) {
break;
}
listener.wait(remaining);
@@ -555,11 +558,11 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
}
});
}
-
+
public static class MyListener extends ClientMembershipListenerAdapter implements Serializable {
protected int crashes = 0;
protected int joins = 0;
- protected int departures = 0;
+ protected int departures= 0;
@Override
public synchronized void memberCrashed(ClientMembershipEvent event) {
@@ -593,7 +596,7 @@ public class AutoConnectionSourceDUnitTest extends LocatorTestBase {
return joins;
}
- public synchronized int getDepartures() {
+ public synchronized int getDepartures() {
return departures;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceImplJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceImplJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceImplJUnitTest.java
index 667af89..8deedc1 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceImplJUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/cache/client/internal/AutoConnectionSourceImplJUnitTest.java
@@ -144,22 +144,27 @@ public class AutoConnectionSourceImplJUnitTest {
@Test
public void testNoServers() throws Exception {
+
startFakeLocator();
handler.nextConnectionResponse = new ClientConnectionResponse(null);
+
assertEquals(null, source.findServer(null));
}
@Test
public void testDiscoverServers() throws Exception {
startFakeLocator();
+
ServerLocation loc1 = new ServerLocation("localhost", 4423);
handler.nextConnectionResponse = new ClientConnectionResponse(loc1);
+
assertEquals(loc1, source.findServer(null));
}
@Test
public void testDiscoverLocators() throws Exception {
startFakeLocator();
+
int secondPort = AvailablePortHelper.getRandomAvailableTCPPort();
TcpServer server2 = new TcpServer(secondPort, InetAddress.getLocalHost(), null, null, handler, new FakeHelper(), Thread.currentThread().getThreadGroup(), "tcp server");
server2.start();
[3/3] incubator-geode git commit: Revert "GEODE-1376: Cleaned up
server port to be '0'."
Posted by bs...@apache.org.
Revert "GEODE-1376: Cleaned up server port to be '0'."
This reverts commit c33efb60630fe8bed7613c60f941810a7574f16b, which caused
a number of REST test failures in build 467 due to removal/rename of
test methods.
https://builds.apache.org/job/Geode-nightly/467/testReport/
Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/d1a0748b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/d1a0748b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/d1a0748b
Branch: refs/heads/develop
Commit: d1a0748baf43c5cb5b2af46411d65d77778d1012
Parents: a881e9c
Author: Bruce Schuchardt <bs...@pivotal.io>
Authored: Fri May 13 10:29:28 2016 -0700
Committer: Bruce Schuchardt <bs...@pivotal.io>
Committed: Fri May 13 10:50:11 2016 -0700
----------------------------------------------------------------------
...stAPIOnRegionFunctionExecutionDUnitTest.java | 77 ++-
.../web/controllers/RestAPITestBase.java | 16 +-
.../RestAPIsAndInterOpsDUnitTest.java | 501 +++++++++++--------
...tAPIsOnGroupsFunctionExecutionDUnitTest.java | 6 +-
...APIsOnMembersFunctionExecutionDUnitTest.java | 19 +-
.../controllers/RestAPIsWithSSLDUnitTest.java | 495 +++++++++++-------
.../internal/AutoConnectionSourceDUnitTest.java | 345 ++++++-------
.../AutoConnectionSourceImplJUnitTest.java | 5 +
.../internal/LocatorLoadBalancingDUnitTest.java | 439 +++++++++-------
.../cache/client/internal/LocatorTestBase.java | 396 +++++++++------
.../internal/cache/Bug47667DUnitTest.java | 24 +-
.../CacheServerManagementDUnitTest.java | 260 ++++++----
12 files changed, 1500 insertions(+), 1083 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIOnRegionFunctionExecutionDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIOnRegionFunctionExecutionDUnitTest.java b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIOnRegionFunctionExecutionDUnitTest.java
index dc3986b..fedd119 100644
--- a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIOnRegionFunctionExecutionDUnitTest.java
+++ b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIOnRegionFunctionExecutionDUnitTest.java
@@ -36,7 +36,6 @@ import java.util.*;
/**
* Dunit Test to validate OnRegion function execution with REST APIs
- *
* @since 8.0
*/
@@ -59,22 +58,22 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
if (context instanceof RegionFunctionContext) {
RegionFunctionContext rfContext = (RegionFunctionContext) context;
rfContext.getDataSet().getCache().getLogger()
- .info("Executing function : SampleFunction.execute(hasResult=true) with filter: " + rfContext.getFilter() + " " + rfContext);
+ .info("Executing function : SampleFunction.execute(hasResult=true) with filter: " + rfContext.getFilter() + " " + rfContext);
if (rfContext.getArguments() instanceof Boolean) {
/* return rfContext.getArguments(); */
if (hasResult()) {
rfContext.getResultSender().lastResult(
- (Serializable) rfContext.getArguments());
+ (Serializable) rfContext.getArguments());
} else {
rfContext
- .getDataSet()
- .getCache()
- .getLogger()
- .info(
- "Executing function : SampleFunction.execute(hasResult=false) " + rfContext);
+ .getDataSet()
+ .getCache()
+ .getLogger()
+ .info(
+ "Executing function : SampleFunction.execute(hasResult=false) " + rfContext);
while (true && !rfContext.getDataSet().isDestroyed()) {
rfContext.getDataSet().getCache().getLogger()
- .info("For Bug43513 ");
+ .info("For Bug43513 ");
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
@@ -91,7 +90,7 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
Thread.sleep(2000);
} catch (InterruptedException e) {
rfContext.getDataSet().getCache().getLogger()
- .warning("Got Exception : Thread Interrupted" + e);
+ .warning("Got Exception : Thread Interrupted" + e);
}
}
if (PartitionRegionHelper.isPartitionedRegion(rfContext.getDataSet())) {
@@ -101,11 +100,11 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
* rfContext).get(key);
*/
rfContext.getResultSender().lastResult(
- (Serializable) PartitionRegionHelper.getLocalDataForContext(
- rfContext).get(key));
+ (Serializable) PartitionRegionHelper.getLocalDataForContext(
+ rfContext).get(key));
} else {
rfContext.getResultSender().lastResult(
- (Serializable) rfContext.getDataSet().get(key));
+ (Serializable) rfContext.getDataSet().get(key));
}
/* return (Serializable)rfContext.getDataSet().get(key); */
} else if (rfContext.getArguments() instanceof Set) {
@@ -113,7 +112,7 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
ArrayList vals = new ArrayList();
for (Object key : origKeys) {
Object val = PartitionRegionHelper
- .getLocalDataForContext(rfContext).get(key);
+ .getLocalDataForContext(rfContext).get(key);
if (val != null) {
vals.add(val);
}
@@ -137,10 +136,10 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
DistributedSystem ds = InternalDistributedSystem.getAnyInstance();
LogWriter logger = ds.getLogWriter();
logger.info("Executing in SampleFunction on Server : "
- + ds.getDistributedMember() + "with Context : " + context);
+ + ds.getDistributedMember() + "with Context : " + context);
while (ds.isConnected()) {
logger
- .fine("Just executing function in infinite loop for Bug43513");
+ .fine("Just executing function in infinite loop for Bug43513");
try {
Thread.sleep(250);
} catch (InterruptedException e) {
@@ -183,7 +182,7 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
private boolean createPeerWithPR() {
RegionAttributes ra = PartitionedRegionTestHelper.createRegionAttrsForPR(0,
- 10);
+ 10);
AttributesFactory raf = new AttributesFactory(ra);
PartitionAttributesImpl pa = new PartitionAttributesImpl();
pa.setAll(ra.getPartitionAttributes());
@@ -232,10 +231,10 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
}
private void createCacheAndRegisterFunction() {
- restURLs.add(vm0.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm0.getHost().getHostName(), null)));
- restURLs.add(vm1.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm1.getHost().getHostName(), null)));
- restURLs.add(vm2.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm2.getHost().getHostName(), null)));
- restURLs.add(vm3.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm3.getHost().getHostName(), null)));
+ restURLs.add(vm0.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm0, null)));
+ restURLs.add(vm1.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm1, null)));
+ restURLs.add(vm2.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm2, null)));
+ restURLs.add(vm3.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm3, null)));
vm0.invoke("registerFunction(new SampleFunction())", () -> FunctionService.registerFunction(new SampleFunction()));
vm1.invoke("registerFunction(new SampleFunction())", () -> FunctionService.registerFunction(new SampleFunction()));
@@ -284,7 +283,7 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
createPeersWithPR(vm0, vm1, vm2, vm3);
- vm3.invoke("populatePRRegion", () -> populatePRRegion());
+ vm3.invoke("populatePRRegion",() -> populatePRRegion());
CloseableHttpResponse response = executeFunctionThroughRestCall("SampleFunction", PR_REGION_NAME, "key2", null, null, null);
assertEquals(200, response.getStatusLine().getStatusCode());
@@ -306,16 +305,16 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
createPeersWithPR(vm0, vm1, vm2, vm3);
- vm3.invoke("populatePRRegion", () -> populatePRRegion());
+ vm3.invoke("populatePRRegion",() -> populatePRRegion());
String jsonBody = "["
- + "{\"@type\": \"double\",\"@value\": 210}"
- + ",{\"@type\":\"com.gemstone.gemfire.rest.internal.web.controllers.Item\","
- + "\"itemNo\":\"599\",\"description\":\"Part X Free on Bumper Offer\","
- + "\"quantity\":\"2\","
- + "\"unitprice\":\"5\","
- + "\"totalprice\":\"10.00\"}"
- + "]";
+ + "{\"@type\": \"double\",\"@value\": 210}"
+ + ",{\"@type\":\"com.gemstone.gemfire.rest.internal.web.controllers.Item\","
+ + "\"itemNo\":\"599\",\"description\":\"Part X Free on Bumper Offer\","
+ + "\"quantity\":\"2\","
+ + "\"unitprice\":\"5\","
+ + "\"totalprice\":\"10.00\"}"
+ + "]";
CloseableHttpResponse response = executeFunctionThroughRestCall("SampleFunction", PR_REGION_NAME, null, jsonBody, null, null);
assertEquals(200, response.getStatusLine().getStatusCode());
@@ -325,15 +324,15 @@ public class RestAPIOnRegionFunctionExecutionDUnitTest extends RestAPITestBase {
assertCorrectInvocationCount(4, vm0, vm1, vm2, vm3);
jsonBody = "["
- + "{\"@type\": \"double\",\"@value\": 220}"
- + ",{\"@type\":\"com.gemstone.gemfire.rest.internal.web.controllers.Item\","
- + "\"itemNo\":\"609\",\"description\":\"Part X Free on Bumper Offer\","
- + "\"quantity\":\"3\","
- + "\"unitprice\":\"9\","
- + "\"totalprice\":\"12.00\"}"
- + "]";
-
- resetInvocationCounts(vm0, vm1, vm2, vm3);
+ + "{\"@type\": \"double\",\"@value\": 220}"
+ + ",{\"@type\":\"com.gemstone.gemfire.rest.internal.web.controllers.Item\","
+ + "\"itemNo\":\"609\",\"description\":\"Part X Free on Bumper Offer\","
+ + "\"quantity\":\"3\","
+ + "\"unitprice\":\"9\","
+ + "\"totalprice\":\"12.00\"}"
+ + "]";
+
+ resetInvocationCounts(vm0,vm1,vm2,vm3);
response = executeFunctionThroughRestCall("SampleFunction", PR_REGION_NAME, "key2", jsonBody, null, null);
assertEquals(200, response.getStatusLine().getStatusCode());
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPITestBase.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPITestBase.java b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPITestBase.java
index 9e8086c..fc71fd8 100644
--- a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPITestBase.java
+++ b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPITestBase.java
@@ -66,6 +66,7 @@ public class RestAPITestBase extends DistributedTestCase {
if (agentUtil.findWarLocation("geode-web-api") == null) {
fail("unable to locate geode-web-api WAR file");
}
+ Wait.pause(1000); // TODO: replace this with Awaitility
final Host host = Host.getHost(0);
vm0 = host.getVM(0);
vm1 = host.getVM(1);
@@ -101,10 +102,11 @@ public class RestAPITestBase extends DistributedTestCase {
}
}
- public String createCacheWithGroups(final String hostName, final String groups) {
+ public String createCacheWithGroups(VM vm, final String groups) {
RestAPITestBase test = new RestAPITestBase(getTestMethodName());
- final int servicePort = AvailablePortHelper.getRandomAvailableTCPPort();
+ final String hostName = vm.getHost().getHostName();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
Properties props = new Properties();
@@ -114,12 +116,12 @@ public class RestAPITestBase extends DistributedTestCase {
props.setProperty(DistributionConfig.START_DEV_REST_API_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_BIND_ADDRESS_NAME, hostName);
- props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(servicePort));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(serverPort));
InternalDistributedSystem ds = test.getSystem(props);
cache = CacheFactory.create(ds);
- String restEndPoint = "http://" + hostName + ":" + servicePort + "/gemfire-api/v1";
+ String restEndPoint = "http://" + hostName + ":" + serverPort + "/gemfire-api/v1";
return restEndPoint;
}
@@ -130,7 +132,7 @@ public class RestAPITestBase extends DistributedTestCase {
protected CloseableHttpResponse executeFunctionThroughRestCall(String function, String regionName, String filter, String jsonBody, String groups,
String members) {
- System.out.println("Entering executeFunctionThroughRestCall");
+ LogWriterUtils.getLogWriter().info("Entering executeFunctionThroughRestCall");
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
Random randomGenerator = new Random();
@@ -138,7 +140,7 @@ public class RestAPITestBase extends DistributedTestCase {
HttpPost post = createHTTPPost(function, regionName, filter, restURLIndex, groups, members, jsonBody);
- System.out.println("Request: POST " + post.toString());
+ LogWriterUtils.getLogWriter().info("Request: POST " + post.toString());
return httpclient.execute(post);
} catch (Exception e) {
throw new RuntimeException("unexpected exception", e);
@@ -183,7 +185,7 @@ public class RestAPITestBase extends DistributedTestCase {
try {
String httpResponseString = processHttpResponse(response);
response.close();
- System.out.println("Response : " + httpResponseString);
+ LogWriterUtils.getLogWriter().info("Response : " + httpResponseString);
//verify function execution result
JSONArray resultArray = new JSONArray(httpResponseString);
assertEquals(resultArray.length(), expectedServerResponses);
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
index 0f4b2d3..5b0eb17 100644
--- a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
+++ b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
@@ -16,7 +16,38 @@
*/
package com.gemstone.gemfire.rest.internal.web.controllers;
-import com.gemstone.gemfire.cache.*;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import com.gemstone.gemfire.cache.AttributesFactory;
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.CacheFactory;
+import com.gemstone.gemfire.cache.DataPolicy;
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.RegionAttributes;
+import com.gemstone.gemfire.cache.RegionFactory;
+import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
import com.gemstone.gemfire.cache.client.ClientRegionFactory;
@@ -33,31 +64,17 @@ import com.gemstone.gemfire.management.ManagementTestBase;
import com.gemstone.gemfire.pdx.PdxInstance;
import com.gemstone.gemfire.test.dunit.Host;
import com.gemstone.gemfire.test.dunit.NetworkUtils;
+import com.gemstone.gemfire.test.dunit.SerializableCallable;
+import com.gemstone.gemfire.test.dunit.SerializableRunnable;
import com.gemstone.gemfire.test.dunit.VM;
-import org.apache.http.HttpEntity;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.methods.*;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.*;
/**
* Dunit Test containing inter - operations between REST Client and Gemfire cache client
- *
* @since 8.0
*/
public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
-
+
private static final long serialVersionUID = -254776154266339226L;
private ManagementTestBase helper;
@@ -72,7 +89,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
private static final String[] PARAM_QUERY_IDS_ARRAY = { "findAllPeople",
"filterByGender", "filterByLastName" };
-
+
final static String QUERY_ARGS = "["
+ "{"
+ "\"@type\": \"string\","
@@ -81,29 +98,29 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
+ "]";
final static String PERSON_AS_JSON_CAS = "{"
- + "\"@old\" :"
+ + "\"@old\" :"
+ "{"
+ "\"@type\": \"com.gemstone.gemfire.rest.internal.web.controllers.Person\","
+ "\"id\": 101," + " \"firstName\": \"Mithali\","
+ " \"middleName\": \"Dorai\"," + " \"lastName\": \"Raj\","
- + " \"birthDate\": \"12/04/1982\"," + "\"gender\": \"FEMALE\""
+ + " \"birthDate\": \"12/04/1982\"," + "\"gender\": \"FEMALE\""
+ "},"
- + "\"@new\" :"
+ + "\"@new\" :"
+ "{"
+ "\"@type\": \"com.gemstone.gemfire.rest.internal.web.controllers.Person\","
+ "\"id\": 1101," + " \"firstName\": \"Virat\","
+ " \"middleName\": \"Premkumar\"," + " \"lastName\": \"Kohli\","
- + " \"birthDate\": \"08/11/1988\"," + "\"gender\": \"MALE\""
+ + " \"birthDate\": \"08/11/1988\"," + "\"gender\": \"MALE\""
+ "}"
+ "}";
-
+
final static String PERSON_AS_JSON_REPLACE = "{"
+ "\"@type\": \"com.gemstone.gemfire.rest.internal.web.controllers.Person\","
+ "\"id\": 501," + " \"firstName\": \"Barack\","
+ " \"middleName\": \"Hussein\"," + " \"lastName\": \"Obama\","
- + " \"birthDate\": \"04/08/1961\"," + "\"gender\": \"MALE\""
+ + " \"birthDate\": \"04/08/1961\"," + "\"gender\": \"MALE\""
+ "}";
-
+
private static final String PERSON_LIST_AS_JSON = "[" + "{"
+ "\"@type\": \"com.gemstone.gemfire.rest.internal.web.controllers.Person\","
+ "\"id\": 3," + " \"firstName\": \"Nishka3\","
@@ -161,38 +178,86 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
protected final void postTearDownLocatorTestBase() throws Exception {
disconnectAllFromDS();
}
-
- public void doPutsInClientCache() {
+
+ public static String startBridgeServerWithRestServiceOnInVM(VM vm, final String[] groups, final String locators, final String[] regions, final ServerLoadProbe probe) {
+
+ final String hostName = vm.getHost().getHostName();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+
+ //create Cache of given VM and start HTTP service with REST APIs service
+ new RestAPIsAndInterOpsDUnitTest("temp").startBridgeServer(hostName, serverPort, groups, locators, regions, probe);
+
+ String restEndPoint = "http://" + hostName + ":" + serverPort + "/gemfire-api/v1";
+ return restEndPoint;
+ }
+
+ @SuppressWarnings("deprecation")
+ protected int startBridgeServer(String hostName, int restServicerPort, final String[] groups, final String locators, final String[] regions, final ServerLoadProbe probe) {
+
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
+ props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+ props.setProperty(DistributionConfig.START_DEV_REST_API_NAME, "true");
+ props.setProperty(DistributionConfig.HTTP_SERVICE_BIND_ADDRESS_NAME, hostName);
+ props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(restServicerPort));
+
+ DistributedSystem ds = getSystem(props);
+ Cache cache = CacheFactory.create(ds);
+ ((GemFireCacheImpl)cache).setReadSerialized(true);
+ AttributesFactory factory = new AttributesFactory();
+
+ factory.setEnableBridgeConflation(true);
+ factory.setDataPolicy(DataPolicy.REPLICATE);
+ RegionAttributes attrs = factory.create();
+ for(int i = 0; i < regions.length; i++) {
+ cache.createRegion(regions[i], attrs);
+ }
+
+ CacheServer server = cache.addCacheServer();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ server.setPort(serverPort);
+ server.setGroups(groups);
+ server.setLoadProbe(probe);
+ try {
+ server.start();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ remoteObjects.put(CACHE_KEY, cache);
+ return new Integer(serverPort);
+ }
+
+ public static void doPutsInClientCache() {
ClientCache cache = GemFireCacheImpl.getInstance();
assertNotNull(cache);
Region<String, Object> region = cache.getRegion(PEOPLE_REGION_NAME);
-
+
//put person object
final Person person1 = new Person(101L, "Mithali", "Dorai", "Raj", DateTimeUtils.createDate(1982, Calendar.DECEMBER, 4), Gender.FEMALE);
final Person person2 = new Person(102L, "Sachin", "Ramesh", "Tendulkar", DateTimeUtils.createDate(1975, Calendar.DECEMBER, 14), Gender.MALE);
final Person person3 = new Person(103L, "Saurabh", "Baburav", "Ganguly", DateTimeUtils.createDate(1972, Calendar.AUGUST, 29), Gender.MALE);
final Person person4 = new Person(104L, "Rahul", "subrymanyam", "Dravid", DateTimeUtils.createDate(1979, Calendar.MARCH, 17), Gender.MALE);
final Person person5 = new Person(105L, "Jhulan", "Chidambaram", "Goswami", DateTimeUtils.createDate(1983, Calendar.NOVEMBER, 25), Gender.FEMALE);
-
+
region.put("1", person1);
region.put("2", person2);
region.put("3", person3);
region.put("4", person4);
region.put("5", person5);
-
+
final Person person6 = new Person(101L, "Rahul", "Rajiv", "Gndhi", DateTimeUtils.createDate(1970, Calendar.MAY, 14), Gender.MALE);
final Person person7 = new Person(102L, "Narendra", "Damodar", "Modi", DateTimeUtils.createDate(1945, Calendar.DECEMBER, 24), Gender.MALE);
final Person person8 = new Person(103L, "Atal", "Bihari", "Vajpayee", DateTimeUtils.createDate(1920, Calendar.AUGUST, 9), Gender.MALE);
final Person person9 = new Person(104L, "Soniya", "Rajiv", "Gandhi", DateTimeUtils.createDate(1929, Calendar.MARCH, 27), Gender.FEMALE);
final Person person10 = new Person(104L, "Priyanka", "Robert", "Gandhi", DateTimeUtils.createDate(1973, Calendar.APRIL, 15), Gender.FEMALE);
-
+
final Person person11 = new Person(104L, "Murali", "Manohar", "Joshi", DateTimeUtils.createDate(1923, Calendar.APRIL, 25), Gender.MALE);
final Person person12 = new Person(104L, "Lalkrishna", "Parmhansh", "Advani", DateTimeUtils.createDate(1910, Calendar.JANUARY, 01), Gender.MALE);
final Person person13 = new Person(104L, "Shushma", "kumari", "Swaraj", DateTimeUtils.createDate(1943, Calendar.AUGUST, 10), Gender.FEMALE);
final Person person14 = new Person(104L, "Arun", "raman", "jetly", DateTimeUtils.createDate(1942, Calendar.OCTOBER, 27), Gender.MALE);
final Person person15 = new Person(104L, "Amit", "kumar", "shah", DateTimeUtils.createDate(1958, Calendar.DECEMBER, 21), Gender.MALE);
final Person person16 = new Person(104L, "Shila", "kumari", "Dixit", DateTimeUtils.createDate(1927, Calendar.FEBRUARY, 15), Gender.FEMALE);
-
+
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("6", person6);
userMap.put("7", person7);
@@ -205,15 +270,15 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
userMap.put("14", person14);
userMap.put("15", person15);
userMap.put("16", person16);
-
+
region.putAll(userMap);
-
+
if (cache != null)
cache.getLogger().info("Gemfire Cache Client: Puts successfully done");
-
+
}
- public void doQueryOpsUsingRestApis(String restEndpoint) {
+ public static void doQueryOpsUsingRestApis(String restEndpoint) {
String currentQueryOp = null;
try {
// Query TestCase-1 :: Prepare parameterized Queries
@@ -226,7 +291,8 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
CloseableHttpResponse createNamedQueryResponse = httpclient.execute(post);
assertEquals(createNamedQueryResponse.getStatusLine().getStatusCode(), 201);
assertNotNull(createNamedQueryResponse.getEntity());
- createNamedQueryResponse.close();
+ createNamedQueryResponse.close();
+
post = new HttpPost(restEndpoint + findPeopleByGenderQuery);
post.addHeader("Content-Type", "application/json");
@@ -235,6 +301,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
assertEquals(createNamedQueryResponse.getStatusLine().getStatusCode(), 201);
assertNotNull(createNamedQueryResponse.getEntity());
createNamedQueryResponse.close();
+
post = new HttpPost(restEndpoint + findPeopleByLastNameQuery);
post.addHeader("Content-Type", "application/json");
@@ -244,7 +311,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
assertNotNull(createNamedQueryResponse.getEntity());
createNamedQueryResponse.close();
}
-
+
// Query TestCase-2 :: List all parameterized queries
{
currentQueryOp = "listAllQueries";
@@ -253,7 +320,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
CloseableHttpResponse listAllQueriesResponse = httpclient.execute(get);
assertEquals(listAllQueriesResponse.getStatusLine().getStatusCode(), 200);
assertNotNull(listAllQueriesResponse.getEntity());
-
+
HttpEntity entity = listAllQueriesResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
@@ -264,19 +331,19 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
sb.append(line);
}
listAllQueriesResponse.close();
-
+
// Check whether received response contains expected query IDs.
JSONObject jsonObject = new JSONObject(sb.toString());
JSONArray jsonArray = jsonObject.getJSONArray("queries");
for (int i = 0; i < jsonArray.length(); i++) {
assertTrue(
- "PREPARE_PARAMETERIZED_QUERY: function IDs are not matched",
- Arrays.asList(PARAM_QUERY_IDS_ARRAY).contains(
- jsonArray.getJSONObject(i).getString("id")));
+ "PREPARE_PARAMETERIZED_QUERY: function IDs are not matched",
+ Arrays.asList(PARAM_QUERY_IDS_ARRAY).contains(
+ jsonArray.getJSONObject(i).getString("id")));
}
- }
-
+ }
+
// Query TestCase-3 :: Run the specified named query passing in scalar values for query parameters.
{
currentQueryOp = "filterByLastName";
@@ -284,35 +351,41 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
HttpPost post = new HttpPost(restEndpoint + "/queries/filterByLastName");
post.addHeader("Content-Type", "application/json");
post.addHeader("Accept", "application/json");
- StringEntity entity = new StringEntity(QUERY_ARGS);
+ StringEntity entity = new StringEntity(QUERY_ARGS);
post.setEntity(entity);
CloseableHttpResponse runNamedQueryResponse = httpclient.execute(post);
assertEquals(200, runNamedQueryResponse.getStatusLine().getStatusCode());
assertNotNull(runNamedQueryResponse.getEntity());
}
- } catch (Exception e) {
+ } catch ( Exception e ) {
throw new RuntimeException("unexpected exception", e);
}
}
-
- public void verifyUpdatesInClientCache() {
+
+ public static void verifyUpdatesInClientCache() {
ClientCache cache = GemFireCacheImpl.getInstance();
assertNotNull(cache);
Region<String, Object> region = cache.getRegion(PEOPLE_REGION_NAME);
-
+
{
- Person expectedPerson = new Person(3L, "Nishka3", "Nilkanth3", "Patel3", DateTimeUtils.createDate(2009, Calendar.JULY, 31), Gender.FEMALE);
+ Person expectedPerson = new Person(3L, "Nishka3", "Nilkanth3", "Patel3", DateTimeUtils.createDate(2009, Calendar.JULY, 31), Gender.FEMALE );
Object value = region.get("3");
if (value instanceof PdxInstance) {
- PdxInstance pi3 = (PdxInstance) value;
+ PdxInstance pi3 = (PdxInstance) value;
Person actualPerson = (Person) pi3.getObject();
- comparePersonObject(expectedPerson, actualPerson);
+ assertEquals(actualPerson.getId(), expectedPerson.getId());
+ assertEquals(actualPerson.getFirstName(), expectedPerson.getFirstName());
+ assertEquals(actualPerson.getMiddleName(), expectedPerson.getMiddleName());
+ assertEquals(actualPerson.getLastName(), expectedPerson.getLastName());
+ assertEquals(actualPerson.getBirthDate(), expectedPerson.getBirthDate());
+ assertEquals(actualPerson.getGender(), expectedPerson.getGender());
} else if (value instanceof Person) {
fail("VerifyUpdatesInClientCache, Get on key 3, Expected to get value of type PdxInstance ");
}
}
-
+
+
//TODO: uncomment it once following issue encountered in put?op=CAS is fixed or document the issue
// CAS functionality is not working in following test case
// step-1: Java client, Region.put("K", A);
@@ -331,47 +404,43 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
}
}
*/
-
+
//verify update on key "2"
{
- Person expectedPerson = new Person(501L, "Barack", "Hussein", "Obama", DateTimeUtils.createDate(1961, Calendar.APRIL, 8), Gender.MALE);
+ Person expectedPerson = new Person(501L, "Barack", "Hussein", "Obama", DateTimeUtils.createDate(1961, Calendar.APRIL, 8), Gender.MALE );
Object value = region.get("2");
if (value instanceof PdxInstance) {
- PdxInstance pi3 = (PdxInstance) value;
+ PdxInstance pi3 = (PdxInstance) value;
Person actualPerson = (Person) pi3.getObject();
- comparePersonObject(expectedPerson, actualPerson);
- } else {
+ assertEquals(actualPerson.getId(), expectedPerson.getId());
+ assertEquals(actualPerson.getFirstName(), expectedPerson.getFirstName());
+ assertEquals(actualPerson.getMiddleName(), expectedPerson.getMiddleName());
+ assertEquals(actualPerson.getLastName(), expectedPerson.getLastName());
+ assertEquals(actualPerson.getBirthDate(), expectedPerson.getBirthDate());
+ assertEquals(actualPerson.getGender(), expectedPerson.getGender());
+ }else {
fail("VerifyUpdatesInClientCache, Get on key 2, Expected to get value of type PdxInstance ");
}
}
-
+
//verify Deleted key "13"
{
Object obj = region.get("13");
assertEquals(obj, null);
-
+
obj = region.get("14");
assertEquals(obj, null);
-
+
obj = region.get("15");
assertEquals(obj, null);
-
+
obj = region.get("16");
assertEquals(obj, null);
}
-
+
}
-
- private void comparePersonObject(Person expectedPerson, Person actualPerson) {
- assertEquals(actualPerson.getId(), expectedPerson.getId());
- assertEquals(actualPerson.getFirstName(), expectedPerson.getFirstName());
- assertEquals(actualPerson.getMiddleName(), expectedPerson.getMiddleName());
- assertEquals(actualPerson.getLastName(), expectedPerson.getLastName());
- assertEquals(actualPerson.getBirthDate(), expectedPerson.getBirthDate());
- assertEquals(actualPerson.getGender(), expectedPerson.getGender());
- }
-
- public void doUpdatesUsingRestApis(String restEndpoint) {
+
+ public static void doUpdatesUsingRestApis(String restEndpoint) {
//UPdate keys using REST calls
{
@@ -388,7 +457,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
throw new RuntimeException("unexpected exception", e);
}
}
-
+
//Delete Single keys
{
try {
@@ -401,7 +470,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
throw new RuntimeException("unexpected exception", e);
}
}
-
+
//Delete set of keys
{
try {
@@ -414,7 +483,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
throw new RuntimeException("unexpected exception", e);
}
}
-
+
//REST put?op=CAS for key 1
/*
try {
@@ -430,15 +499,15 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
}catch (HttpServerErrorException se) {
fail("Caught HttpServerErrorException while doing put with op=cas");
}
- */
-
+ */
+
//REST put?op=REPLACE for key 2
{
/*HttpEntity<Object> entity = new HttpEntity<Object>(PERSON_AS_JSON_REPLACE, headers);
ResponseEntity<String> result = RestTestUtils.getRestTemplate().exchange(
restEndpoint + "/People/2?op=replace",
HttpMethod.PUT, entity, String.class);*/
-
+
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPut put = new HttpPut(restEndpoint
@@ -453,14 +522,14 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
}
}
}
-
- public void fetchRestServerEndpoints(String restEndpoint) {
+
+ public static void fetchRestServerEndpoints(String restEndpoint) {
HttpGet get = new HttpGet(restEndpoint + "/servers");
get.addHeader("Content-Type", "application/json");
get.addHeader("Accept", "application/json");
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response;
-
+
try {
response = httpclient.execute(get);
HttpEntity entity = response.getEntity();
@@ -472,18 +541,18 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
while ((line = reader.readLine()) != null) {
str.append(line);
}
-
+
//validate the satus code
assertEquals(response.getStatusLine().getStatusCode(), 200);
-
- if (response.getStatusLine().getStatusCode() == 200) {
+
+ if(response.getStatusLine().getStatusCode() == 200) {
JSONArray jsonArray = new JSONArray(str.toString());
-
+
//verify total number of REST service endpoints in DS
assertEquals(jsonArray.length(), 2);
}
-
- } catch (ClientProtocolException e) {
+
+ } catch (ClientProtocolException e) {
e.printStackTrace();
fail(" Rest Request should not have thrown ClientProtocolException!");
} catch (IOException e) {
@@ -493,26 +562,26 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
e.printStackTrace();
fail(" Rest Request should not have thrown JSONException!");
}
-
+
}
-
- public void doGetsUsingRestApis(String restEndpoint) {
-
+
+ public static void doGetsUsingRestApis(String restEndpoint) {
+
//HttpHeaders headers = setAcceptAndContentTypeHeaders();
String currentOperation = null;
JSONObject jObject;
JSONArray jArray;
- try {
+ try {
//1. Get on key="1" and validate result.
{
currentOperation = "GET on key 1";
-
+
HttpGet get = new HttpGet(restEndpoint + "/People/1");
get.addHeader("Content-Type", "application/json");
get.addHeader("Accept", "application/json");
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = httpclient.execute(get);
-
+
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
@@ -522,26 +591,27 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
while ((line = reader.readLine()) != null) {
str.append(line);
}
-
+
jObject = new JSONObject(str.toString());
-
+
assertEquals(jObject.get("id"), 101);
assertEquals(jObject.get("firstName"), "Mithali");
assertEquals(jObject.get("middleName"), "Dorai");
assertEquals(jObject.get("lastName"), "Raj");
assertEquals(jObject.get("gender"), Gender.FEMALE.name());
}
-
+
//2. Get on key="16" and validate result.
{
currentOperation = "GET on key 16";
+
HttpGet get = new HttpGet(restEndpoint + "/People/16");
get.addHeader("Content-Type", "application/json");
get.addHeader("Accept", "application/json");
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = httpclient.execute(get);
-
+
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
@@ -551,16 +621,17 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
while ((line = reader.readLine()) != null) {
str.append(line);
}
-
+
jObject = new JSONObject(str.toString());
-
+
+
assertEquals(jObject.get("id"), 104);
assertEquals(jObject.get("firstName"), "Shila");
assertEquals(jObject.get("middleName"), "kumari");
assertEquals(jObject.get("lastName"), "Dixit");
assertEquals(jObject.get("gender"), Gender.FEMALE.name());
}
-
+
//3. Get all (getAll) entries in Region
{
@@ -571,7 +642,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
CloseableHttpResponse result = httpclient.execute(get);
assertEquals(result.getStatusLine().getStatusCode(), 200);
assertNotNull(result.getEntity());
-
+
HttpEntity entity = result.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
@@ -582,16 +653,16 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
sb.append(line);
}
result.close();
-
+
try {
jObject = new JSONObject(sb.toString());
jArray = jObject.getJSONArray("People");
assertEquals(jArray.length(), 16);
} catch (JSONException e) {
- fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
+ fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
}
}
-
+
//4. GetAll?limit=10 (10 entries) and verify results
{
HttpGet get = new HttpGet(restEndpoint + "/People?limit=10");
@@ -601,7 +672,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
CloseableHttpResponse response = httpclient.execute(get);
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertNotNull(response.getEntity());
-
+
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
@@ -611,19 +682,19 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
while ((line = reader.readLine()) != null) {
str.append(line);
}
-
+
try {
jObject = new JSONObject(str.toString());
jArray = jObject.getJSONArray("People");
assertEquals(jArray.length(), 10);
} catch (JSONException e) {
- fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
+ fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
}
}
-
+
//5. Get keys - List all keys in region
- {
-
+ {
+
HttpGet get = new HttpGet(restEndpoint + "/People/keys");
get.addHeader("Content-Type", "application/json");
get.addHeader("Accept", "application/json");
@@ -631,7 +702,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
CloseableHttpResponse response = httpclient.execute(get);
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertNotNull(response.getEntity());
-
+
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
@@ -641,19 +712,19 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
while ((line = reader.readLine()) != null) {
str.append(line);
}
-
+
try {
jObject = new JSONObject(str.toString());
- jArray = jObject.getJSONArray("keys");
+ jArray = jObject.getJSONArray("keys");
assertEquals(jArray.length(), 16);
} catch (JSONException e) {
- fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
+ fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
}
- }
-
+ }
+
//6. Get data for specific keys
- {
-
+ {
+
HttpGet get = new HttpGet(restEndpoint + "/People/1,3,5,7,9,11");
get.addHeader("Content-Type", "application/json");
get.addHeader("Accept", "application/json");
@@ -661,7 +732,7 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
CloseableHttpResponse response = httpclient.execute(get);
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertNotNull(response.getEntity());
-
+
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
@@ -671,44 +742,53 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
while ((line = reader.readLine()) != null) {
str.append(line);
}
-
+
try {
jObject = new JSONObject(str.toString());
jArray = jObject.getJSONArray("People");
assertEquals(jArray.length(), 6);
-
+
} catch (JSONException e) {
- fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
+ fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException ");
}
- }
- } catch (Exception e) {
- throw new RuntimeException("unexpected exception", e);
+ }
+ }catch ( Exception e ) {
+ throw new RuntimeException("unexpected exception", e);
}
}
- public void createRegionInClientCache() {
+ public static void createRegionInClientCache() {
ClientCache cache = GemFireCacheImpl.getInstance();
assertNotNull(cache);
ClientRegionFactory<String, Object> crf = cache
.createClientRegionFactory(ClientRegionShortcut.PROXY);
- crf.create(PEOPLE_REGION_NAME);
+ Region<String, Object> region = crf.create(PEOPLE_REGION_NAME);
+
+ }
+
+ public static void createRegionInManager() {
+ Cache cache = GemFireCacheImpl.getInstance();
+ assertNotNull(cache);
+
+ RegionFactory<String, Object> rf = cache
+ .createRegionFactory(RegionShortcut.REPLICATE);
+ Region<String, Object> region = rf.create(PEOPLE_REGION_NAME);
}
- public void createRegion() {
+ public static void createRegionInPeerServer() {
Cache cache = GemFireCacheImpl.getInstance();
assertNotNull(cache);
- RegionFactory<String, Object> regionFactory = cache
+ RegionFactory<String, Object> rf = cache
.createRegionFactory(RegionShortcut.REPLICATE);
- regionFactory.create(PEOPLE_REGION_NAME);
+ Region<String, Object> region = rf.create(PEOPLE_REGION_NAME);
}
/**
- * InterOps Test between REST-client, Peer Cache Client and Client Cache
- *
+ * InterOps Test between REST-client, Peer Cache Client and Client Cache
* @throws Exception
*/
-
+
public void testInterOpsWithReplicatedRegion() throws Exception {
final Host host = Host.getHost(0);
@@ -719,46 +799,47 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
// start locator
int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-
- locator.invoke("Start Locator", () -> startLocator(locator.getHost(), locatorPort, ""));
-
+
+ startLocatorInVM(locator, locatorPort, "");
+
// find locators
String locators = NetworkUtils.getServerHostName(locator.getHost()) + "[" + locatorPort
+ "]";
// start manager (peer cache)
- manager.invoke("Start manager", () -> startManager(null, locators,
- new String[] { REGION_NAME }, CacheServer.DEFAULT_LOAD_PROBE));
-
+ int managerPort = startManagerInVM(manager,/* groups */null, locators,
+ new String[] {REGION_NAME}, CacheServer.DEFAULT_LOAD_PROBE);
+
//start startCacheServer With RestService enabled
- String restEndpoint = (String) server.invoke(RestAPIsAndInterOpsDUnitTest.class,
- "startBridgeServerWithRestServiceOnInVM", new Object[] { server, null, locators, new String[] { REGION_NAME }, CacheServer.DEFAULT_LOAD_PROBE });
-
+ String restEndpoint = (String)server.invoke(RestAPIsAndInterOpsDUnitTest.class,
+ "startBridgeServerWithRestServiceOnInVM", new Object[] { server , null, locators, new String[] {REGION_NAME}, CacheServer.DEFAULT_LOAD_PROBE });
+
// create a client cache
- client.invoke("Create Client", () -> createClientCache(NetworkUtils.getServerHostName(locator.getHost()), locatorPort));
-
+ createClientCacheInVM(client, NetworkUtils.getServerHostName(locator.getHost()),
+ locatorPort);
+
// create region in Manager, peer cache and Client cache nodes
- manager.invoke("create region", () -> createRegion());
- server.invoke("create region", () -> createRegion());
- client.invoke("create region", () -> createRegionInClientCache());
-
+ manager.invoke(() -> RestAPIsAndInterOpsDUnitTest.createRegionInManager());
+ server.invoke(() -> RestAPIsAndInterOpsDUnitTest.createRegionInPeerServer());
+ client.invoke(() -> RestAPIsAndInterOpsDUnitTest.createRegionInClientCache());
+
// do some person puts from clientcache
- client.invoke("doPutsInClientCache", () -> doPutsInClientCache());
+ client.invoke(() -> RestAPIsAndInterOpsDUnitTest.doPutsInClientCache());
//TEST: fetch all available REST endpoints
- fetchRestServerEndpoints(restEndpoint);
-
+ RestAPIsAndInterOpsDUnitTest.fetchRestServerEndpoints(restEndpoint);
+
// Controller VM - config REST Client and make HTTP calls
- doGetsUsingRestApis(restEndpoint);
-
+ RestAPIsAndInterOpsDUnitTest.doGetsUsingRestApis(restEndpoint);
+
//update Data using REST APIs
- doUpdatesUsingRestApis(restEndpoint);
-
- client.invoke("verifyUpdatesInClientCache", () -> verifyUpdatesInClientCache());
+ RestAPIsAndInterOpsDUnitTest.doUpdatesUsingRestApis(restEndpoint);
+
+ client.invoke(() -> RestAPIsAndInterOpsDUnitTest.verifyUpdatesInClientCache());
//Querying
- doQueryOpsUsingRestApis(restEndpoint);
-
+ RestAPIsAndInterOpsDUnitTest.doQueryOpsUsingRestApis(restEndpoint);
+
// stop the client and make sure the bridge server notifies
// stopBridgeMemberVM(client);
helper.closeCache(locator);
@@ -768,44 +849,66 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
}
- private void createClientCache(final String host, final int port) throws Exception {
- // Connect using the GemFire locator and create a Caching_Proxy cache
- ClientCache cache = new ClientCacheFactory().setPdxReadSerialized(true).addPoolLocator(host, port).create();
- cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(REGION_NAME);
- }
-
- private int startManager(final String[] groups,
- final String locators, final String[] regions, final ServerLoadProbe probe) throws IOException {
- Properties props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
- props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
-
- props.setProperty("jmx-manager", "true");
- props.setProperty("jmx-manager-start", "true");
- props.setProperty(DistributionConfig.JMX_MANAGER_PORT_NAME, "0");
-
- final int httpPort = AvailablePortHelper.getRandomAvailableTCPPort();
- //Set REST service related configuration
- props.setProperty(DistributionConfig.START_DEV_REST_API_NAME, "true");
- props.setProperty(DistributionConfig.HTTP_SERVICE_BIND_ADDRESS_NAME, "localhost");
- props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(httpPort));
-
- DistributedSystem ds = getSystem(props);
- Cache cache = CacheFactory.create(ds);
- AttributesFactory factory = new AttributesFactory();
+ private void createClientCacheInVM(VM vm, final String host, final int port) throws Exception {
+ SerializableRunnable connect = new SerializableRunnable(
+ "Start Cache client") {
+ public void run() {
+ // Connect using the GemFire locator and create a Caching_Proxy cache
+ ClientCache c = new ClientCacheFactory().setPdxReadSerialized(true).addPoolLocator(host, port)
+ .create();
+
+ Region r = c.createClientRegionFactory(
+ ClientRegionShortcut.PROXY).create(REGION_NAME);
+ }
+ };
- factory.setEnableBridgeConflation(true);
- factory.setDataPolicy(DataPolicy.REPLICATE);
- RegionAttributes attrs = factory.create();
- for (int i = 0; i < regions.length; i++) {
- cache.createRegion(regions[i], attrs);
+ if (vm == null) {
+ connect.run();
+ } else {
+ vm.invoke(connect);
}
- CacheServer server = cache.addCacheServer();
- server.setPort(0);
- server.setGroups(groups);
- server.setLoadProbe(probe);
- server.start();
+ }
- return new Integer(server.getPort());
+ private int startManagerInVM(VM vm, final String[] groups,
+ final String locators, final String[] regions, final ServerLoadProbe probe) {
+ SerializableCallable connect = new SerializableCallable("Start Manager ") {
+ public Object call() throws IOException {
+ Properties props = new Properties();
+ props
+ .setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
+ props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+
+ props.setProperty("jmx-manager", "true");
+ props.setProperty("jmx-manager-start", "true");
+ props.setProperty(DistributionConfig.JMX_MANAGER_PORT_NAME, "0");
+
+ final int httpPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ //Set REST service related configuration
+ props.setProperty(DistributionConfig.START_DEV_REST_API_NAME, "true");
+ props.setProperty(DistributionConfig.HTTP_SERVICE_BIND_ADDRESS_NAME, "localhost");
+ props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(httpPort));
+
+ DistributedSystem ds = getSystem(props);
+ Cache cache = CacheFactory.create(ds);
+ AttributesFactory factory = new AttributesFactory();
+
+ factory.setEnableBridgeConflation(true);
+ factory.setDataPolicy(DataPolicy.REPLICATE);
+ RegionAttributes attrs = factory.create();
+ for (int i = 0; i < regions.length; i++) {
+ cache.createRegion(regions[i], attrs);
+ }
+ CacheServer server = cache.addCacheServer();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ server.setPort(serverPort);
+ server.setGroups(groups);
+ server.setLoadProbe(probe);
+ server.start();
+
+ return new Integer(serverPort);
+ }
+ };
+ Integer port = (Integer) vm.invoke(connect);
+ return port.intValue();
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnGroupsFunctionExecutionDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnGroupsFunctionExecutionDUnitTest.java b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnGroupsFunctionExecutionDUnitTest.java
index a567700..61e0925 100644
--- a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnGroupsFunctionExecutionDUnitTest.java
+++ b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnGroupsFunctionExecutionDUnitTest.java
@@ -39,9 +39,9 @@ public class RestAPIsOnGroupsFunctionExecutionDUnitTest extends RestAPITestBase
}
private void setupCacheWithGroupsAndFunction() {
- restURLs.add(vm0.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm0.getHost().getHostName(), "g0,gm")));
- restURLs.add(vm1.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm1.getHost().getHostName(), "g1")));
- restURLs.add(vm2.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm2.getHost().getHostName(), "g0,g1")));
+ restURLs.add(vm0.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm0, "g0,gm")));
+ restURLs.add(vm1.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm1, "g1")));
+ restURLs.add(vm2.invoke("createCacheWithGroups", () -> createCacheWithGroups(vm2, "g0,g1")));
vm0.invoke("registerFunction(new OnGroupsFunction())", () -> FunctionService.registerFunction(new OnGroupsFunction()));
vm1.invoke("registerFunction(new OnGroupsFunction())", () -> FunctionService.registerFunction(new OnGroupsFunction()));
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d1a0748b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnMembersFunctionExecutionDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnMembersFunctionExecutionDUnitTest.java b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnMembersFunctionExecutionDUnitTest.java
index fd6b312..ca01830 100644
--- a/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnMembersFunctionExecutionDUnitTest.java
+++ b/geode-assembly/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestAPIsOnMembersFunctionExecutionDUnitTest.java
@@ -44,7 +44,7 @@ public class RestAPIsOnMembersFunctionExecutionDUnitTest extends RestAPITestBase
@Override
public void execute(FunctionContext context) {
- System.out.println("SWAP:1:executing OnMembersFunction:" + invocationCount);
+ LogWriterUtils.getLogWriter().fine("SWAP:1:executing OnMembersFunction:" + invocationCount);
invocationCount++;
context.getResultSender().lastResult(Boolean.TRUE);
@@ -71,14 +71,15 @@ public class RestAPIsOnMembersFunctionExecutionDUnitTest extends RestAPITestBase
}
}
- private String createCacheAndRegisterFunction(String hostName, String memberName) {
- final int servicePort = AvailablePortHelper.getRandomAvailableTCPPort();
+ private String createCacheAndRegisterFunction(VM vm, String memberName) {
+ final String hostName = vm.getHost().getHostName();
+ final int serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
Properties props = new Properties();
props.setProperty(DistributionConfig.NAME_NAME, memberName);
props.setProperty(DistributionConfig.START_DEV_REST_API_NAME, "true");
props.setProperty(DistributionConfig.HTTP_SERVICE_BIND_ADDRESS_NAME, hostName);
- props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(servicePort));
+ props.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(serverPort));
Cache c = null;
try {
@@ -90,7 +91,7 @@ public class RestAPIsOnMembersFunctionExecutionDUnitTest extends RestAPITestBase
c = CacheFactory.create(new RestAPIsOnMembersFunctionExecutionDUnitTest("temp").getSystem(props));
FunctionService.registerFunction(new OnMembersFunction());
- String restEndPoint = "http://" + hostName + ":" + servicePort + "/gemfire-api/v1";
+ String restEndPoint = "http://" + hostName + ":" + serverPort + "/gemfire-api/v1";
return restEndPoint;
}
@@ -114,10 +115,10 @@ public class RestAPIsOnMembersFunctionExecutionDUnitTest extends RestAPITestBase
}
private void createCacheForVMs() {
- restURLs.add(vm0.invoke("createCacheAndRegisterFunction",() -> createCacheAndRegisterFunction(vm0.getHost().getHostName(), "m1")));
- restURLs.add(vm1.invoke("createCacheAndRegisterFunction",() -> createCacheAndRegisterFunction(vm1.getHost().getHostName(), "m2")));
- restURLs.add(vm2.invoke("createCacheAndRegisterFunction",() -> createCacheAndRegisterFunction(vm2.getHost().getHostName(), "m3")));
- restURLs.add(vm3.invoke("createCacheAndRegisterFunction",() -> createCacheAndRegisterFunction(vm3.getHost().getHostName(), "m4")));
+ restURLs.add(vm0.invoke(() -> createCacheAndRegisterFunction(vm0, "m1")));
+ restURLs.add(vm1.invoke(() -> createCacheAndRegisterFunction(vm1, "m2")));
+ restURLs.add(vm2.invoke(() -> createCacheAndRegisterFunction(vm2, "m3")));
+ restURLs.add(vm3.invoke(() -> createCacheAndRegisterFunction(vm3, "m4")));
}
public void testFunctionExecutionEOnSelectedMembers() {