Refactor all samples to use the Spring Test for Apache Geode project.

Add appropriate synchronization/coordination between the client and server.
This commit is contained in:
John Blum
2018-08-15 01:03:39 -07:00
parent fbf5044930
commit 1454a81ade
15 changed files with 59 additions and 332 deletions

View File

@@ -83,11 +83,12 @@ task runGemFireServer() {
dependsOn runGemFireServer
doFirst {
def port = reservePort()
systemProperties['management.port'] = 0
systemProperties['server.port'] = port
//systemProperties['gemfire.log-file'] = "gemfire-client.log"
//systemProperties['gemfire.log-level'] = "config"
systemProperties['management.port'] = 0
systemProperties['server.port'] = port
systemProperties['spring.data.gemfire.cache.server.port'] = runGemFireServer.port
systemProperties['spring.data.gemfire.pool.servers'] = "localhost[" + runGemFireServer.port + "]"
}
doLast {
println 'Stopping Apache Geode Server...'

View File

@@ -27,9 +27,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.tests.integration.config.ClientServerIntegrationTestsConfiguration;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
@@ -70,10 +68,9 @@ public class Application {
SpringApplication.run(Application.class, args);
}
@ClientCacheApplication(name = "SpringSessionDataGeodeClientWithScopedProxiesBootSample", logLevel = "error",
@ClientCacheApplication(name = "SpringSessionDataGeodeBootSampleWithScopedProxiesClient", logLevel = "error",
pingInterval = 5000L, readTimeout = 15000, retryAttempts = 1, subscriptionEnabled = true) // <3>
@EnableGemFireHttpSession(poolName = "DEFAULT") // <4>
@Import(ClientServerIntegrationTestsConfiguration.class)
static class ClientCacheConfiguration { }
@Configuration

View File

@@ -20,7 +20,6 @@ import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.data.gemfire.config.annotation.CacheServerApplication;
import org.springframework.data.gemfire.tests.integration.config.ClientServerIntegrationTestsConfiguration;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
/**
@@ -34,12 +33,11 @@ import org.springframework.session.data.gemfire.config.annotation.web.http.Enabl
* @see org.apache.geode.cache.Cache
* @since 1.2.1
*/
@SuppressWarnings("unused")
// tag::class[]
@SpringBootApplication // <1>
@CacheServerApplication(name = "SpringSessionDataGeodeServerWithScopedProxiesBootSample", logLevel = "error") // <2>
@CacheServerApplication(name = "SpringSessionDataGeodeBootSampleWithScopedProxiesServer", logLevel = "error") // <2>
@EnableGemFireHttpSession(maxInactiveIntervalInSeconds = 10) // <3>
public class GemFireServer extends ClientServerIntegrationTestsConfiguration {
public class GemFireServer {
public static void main(String[] args) {

View File

@@ -84,11 +84,12 @@ integrationTest {
dependsOn runGemFireServer
doFirst {
def port = reservePort()
systemProperties['management.port'] = 0
systemProperties['server.port'] = port
//systemProperties['gemfire.log-file'] = "gemfire-client.log"
//systemProperties['gemfire.log-level'] = "config"
systemProperties['management.port'] = 0
systemProperties['server.port'] = port
systemProperties['spring.data.gemfire.cache.server.port'] = runGemFireServer.port
systemProperties['spring.data.gemfire.pool.servers'] = "localhost[${runGemFireServer.port}]"
}
doLast {
println 'Stopping Apache Geode Server...'

View File

@@ -26,13 +26,14 @@ import java.util.Optional;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.tests.integration.config.SubscriptionEnabledClientServerIntegrationTestsConfiguration;
import org.springframework.data.gemfire.config.annotation.ClientCacheConfigurer;
import org.springframework.data.gemfire.tests.integration.ClientServerIntegrationTestsSupport;
import org.springframework.data.gemfire.util.CollectionUtils;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
import org.springframework.stereotype.Controller;
@@ -74,14 +75,21 @@ public class Application {
SpringApplication.run(Application.class, args);
}
@ClientCacheApplication(name = "SpringSessionDataGeodeClientBootSample", logLevel = "error",
pingInterval = 5000L, readTimeout = 15000, retryAttempts = 1, subscriptionEnabled = true) // <3>
@ClientCacheApplication(name = "SpringSessionDataGeodeBootSampleClient", logLevel = "error",
readTimeout = 15000, retryAttempts = 1, subscriptionEnabled = true) // <3>
@EnableGemFireHttpSession(poolName = "DEFAULT") // <4>
@Import(SubscriptionEnabledClientServerIntegrationTestsConfiguration.class)
static class ClientCacheConfiguration { }
static class ClientCacheConfiguration extends ClientServerIntegrationTestsSupport {
@Bean
ClientCacheConfigurer gemfireServerReadyConfigurer( // <5>
@Value("${spring.data.gemfire.cache.server.port:40404}") int cacheServerPort) {
return (beanName, clientCacheFactoryBean) -> waitForServerToStart("localhost", cacheServerPort);
}
}
@Configuration
static class SpringWebMvcConfiguration { // <5>
static class SpringWebMvcConfiguration { // <6>
@Bean
public WebMvcConfigurer webMvcConfig() {

View File

@@ -20,7 +20,6 @@ import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.data.gemfire.config.annotation.CacheServerApplication;
import org.springframework.data.gemfire.tests.integration.config.ClientServerIntegrationTestsConfiguration;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
/**
@@ -34,12 +33,11 @@ import org.springframework.session.data.gemfire.config.annotation.web.http.Enabl
* @see org.apache.geode.cache.Cache
* @since 1.2.1
*/
@SuppressWarnings("unused")
// tag::class[]
@SpringBootApplication // <1>
@CacheServerApplication(name = "SpringSessionDataGeodeServerBootSample", logLevel = "error") // <2>
@CacheServerApplication(name = "SpringSessionDataGeodeBootSampleServer", logLevel = "config") // <2>
@EnableGemFireHttpSession(maxInactiveIntervalInSeconds = 20) // <3>
public class GemFireServer extends ClientServerIntegrationTestsConfiguration {
public class GemFireServer {
public static void main(String[] args) {

View File

@@ -58,5 +58,4 @@ public class AttributeTests {
assertThat(home.attributes()).extracting("attributeName").containsOnly("a");
assertThat(home.attributes()).extracting("attributeValue").containsOnly("b");
}
}

View File

@@ -16,17 +16,24 @@
package sample;
import org.springframework.context.annotation.Import;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.tests.integration.config.SubscriptionEnabledClientServerIntegrationTestsConfiguration;
import org.springframework.data.gemfire.config.annotation.ClientCacheConfigurer;
import org.springframework.data.gemfire.tests.integration.ClientServerIntegrationTestsSupport;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
// tag::class[]
@ClientCacheApplication(name = "SpringSessionDataGeodeClientJavaConfigSample", logLevel = "error",
pingInterval = 5000L, readTimeout = 15000, retryAttempts = 1, subscriptionEnabled = true) // <1>
@ClientCacheApplication(name = "SpringSessionDataGeodeJavaConfigSampleClient", logLevel = "error",
readTimeout = 15000, retryAttempts = 1, subscriptionEnabled = true) // <1>
@EnableGemFireHttpSession(maxInactiveIntervalInSeconds = 30, poolName = "DEFAULT") // <2>
@Import(SubscriptionEnabledClientServerIntegrationTestsConfiguration.class) // <3>
public class ClientConfig extends IntegrationTestConfig {
public class ClientConfig extends ClientServerIntegrationTestsSupport {
@Bean
ClientCacheConfigurer gemfireServerReadyConfigurer( // <3>
@Value("${spring.data.gemfire.cache.server.port:40404}") int cacheServerPort) {
return (beanName, clientCacheFactoryBean) -> waitForServerToStart("localhost", cacheServerPort);
}
}
// end::class[]

View File

@@ -1,168 +0,0 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.management.membership.ClientMembership;
import org.apache.geode.management.membership.ClientMembershipEvent;
import org.apache.geode.management.membership.ClientMembershipListenerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.data.gemfire.config.annotation.ClientCacheConfigurer;
import org.springframework.data.gemfire.config.xml.GemfireConstants;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration;
import org.springframework.util.Assert;
/**
* The IntegrationTestConfig class...
*
* @author John Blum
* @since 1.0.0
*/
public abstract class IntegrationTestConfig {
static final long DEFAULT_TIMEOUT = TimeUnit.SECONDS.toMillis(60);
static final CountDownLatch LATCH = new CountDownLatch(1);
static final String GEMFIRE_DEFAULT_POOL_NAME = "DEFAULT";
@Bean
BeanPostProcessor clientServerReadyBeanPostProcessor(
@Value("${spring.session.data.geode.cache.server.port:40404}") int port) { // <5>
return new BeanPostProcessor() {
private final AtomicBoolean checkGemFireServerIsRunning = new AtomicBoolean(true);
private final AtomicReference<Pool> defaultPool = new AtomicReference<>(null);
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (shouldCheckWhetherGemFireServerIsRunning(bean, beanName)) {
try {
validateCacheClientNotified();
validateCacheClientSubscriptionQueueConnectionEstablished();
}
catch (InterruptedException cause) {
Thread.currentThread().interrupt();
}
}
return bean;
}
private boolean shouldCheckWhetherGemFireServerIsRunning(Object bean, String beanName) {
return (isGemFireRegion(bean, beanName)
? checkGemFireServerIsRunning.compareAndSet(true, false)
: whenGemFireCache(bean, beanName));
}
private boolean isGemFireRegion(Object bean, String beanName) {
return (GemFireHttpSessionConfiguration.DEFAULT_SESSION_REGION_NAME.equals(beanName)
|| bean instanceof Region);
}
private boolean whenGemFireCache(Object bean, String beanName) {
if (bean instanceof ClientCache) {
defaultPool.compareAndSet(null, ((ClientCache) bean).getDefaultPool());
}
return false;
}
private void validateCacheClientNotified() throws InterruptedException {
boolean didNotTimeout = LATCH.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
Assert.state(didNotTimeout, String.format(
"Apache Geode Cache Server failed to start on host [%s] and port [%d]", "localhost", port));
}
@SuppressWarnings("all")
private void validateCacheClientSubscriptionQueueConnectionEstablished() throws InterruptedException {
boolean cacheClientSubscriptionQueueConnectionEstablished = false;
Pool pool = defaultIfNull(this.defaultPool.get(), GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME,
GEMFIRE_DEFAULT_POOL_NAME);
if (pool instanceof PoolImpl) {
long timeout = (System.currentTimeMillis() + DEFAULT_TIMEOUT);
while (System.currentTimeMillis() < timeout && !((PoolImpl) pool).isPrimaryUpdaterAlive()) {
synchronized (pool) {
TimeUnit.MILLISECONDS.timedWait(pool, 500L);
}
}
cacheClientSubscriptionQueueConnectionEstablished |= ((PoolImpl) pool).isPrimaryUpdaterAlive();
}
Assert.state(cacheClientSubscriptionQueueConnectionEstablished,
String.format("Cache client subscription queue connection not established; Apache Geode Pool was [%s];"
+ " Apache Geode Pool configuration was [locators = %s, servers = %s]",
pool, pool.getLocators(), pool.getServers()));
}
private Pool defaultIfNull(Pool pool, String... poolNames) {
for (String poolName : poolNames) {
pool = (pool != null ? pool : PoolManager.find(poolName));
}
return pool;
}
};
}
ConnectionEndpoint newConnectionEndpoint(String host, int port) {
return new ConnectionEndpoint(host, port);
}
@Bean
ClientCacheConfigurer registerClientMembershipListener() {
return (beanName, bean) -> {
ClientMembership.registerClientMembershipListener(new ClientMembershipListenerAdapter() {
@Override
public void memberJoined(ClientMembershipEvent event) {
LATCH.countDown();
}
});
};
}
}

View File

@@ -19,21 +19,17 @@ package sample;
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.data.gemfire.config.annotation.CacheServerApplication;
import org.springframework.data.gemfire.tests.integration.config.ClientServerIntegrationTestsConfiguration;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
// tag::class[]
@CacheServerApplication(name = "SpringSessionSampleJavaConfigGemFireClientServer", logLevel = "error") // <1>
@CacheServerApplication(name = "SpringSessionDataGeodeJavaConfigSampleServer", logLevel = "error") // <1>
@EnableGemFireHttpSession(maxInactiveIntervalInSeconds = 30) // <2>
@Import(ClientServerIntegrationTestsConfiguration.class) // <3>
public class ServerConfig {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
new AnnotationConfigApplicationContext(ServerConfig.class).registerShutdownHook();
}
}
// end::class[]

View File

@@ -7,6 +7,7 @@ dependencies {
compile project(':spring-session-data-geode')
compile "org.springframework:spring-web"
compile "org.springframework.data:spring-data-geode-test"
compile "org.webjars:bootstrap"
compile "org.webjars:webjars-taglib"
compile jstlDependencies

View File

@@ -16,139 +16,28 @@
package sample;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.management.membership.ClientMembership;
import org.apache.geode.management.membership.ClientMembershipEvent;
import org.apache.geode.management.membership.ClientMembershipListenerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.data.gemfire.config.xml.GemfireConstants;
import org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration;
import org.springframework.util.Assert;
import org.springframework.data.gemfire.client.ClientCacheFactoryBean;
import org.springframework.data.gemfire.tests.integration.ClientServerIntegrationTestsSupport;
public class ClientServerReadyBeanPostProcessor implements BeanPostProcessor {
@SuppressWarnings("unused")
public class ClientServerReadyBeanPostProcessor extends ClientServerIntegrationTestsSupport
implements BeanPostProcessor {
private static final long DEFAULT_TIMEOUT = TimeUnit.SECONDS.toMillis(60);
private static final CountDownLatch LATCH = new CountDownLatch(1);
private static final String GEMFIRE_DEFAULT_POOL_NAME = "DEFAULT";
static {
ClientMembership.registerClientMembershipListener(
new ClientMembershipListenerAdapter() {
@Override
public void memberJoined(ClientMembershipEvent event) {
LATCH.countDown();
}
}
);
}
@Value("${spring.session.data.geode.cache.server.port:${application.geode.client-server.port:40404}}")
@Value("${spring.session.data.geode.cache.server.port:${spring.data.gemfire.cache.server.port:40404}}")
private int port;
@Value("${application.geode.client-server.host:localhost}")
@Value("${spring.session.data.geode.cache.server.host:${spring.data.gemfire.cache.server.host:localhost}}")
private String host;
private final AtomicBoolean checkGemFireServerIsRunning = new AtomicBoolean(true);
private final AtomicReference<Pool> gemfirePool = new AtomicReference<Pool>(null);
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (shouldCheckWhetherGemFireServerIsRunning(bean, beanName)) {
try {
validateCacheClientNotified();
validateCacheClientSubscriptionQueueConnectionEstablished();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (bean instanceof ClientCacheFactoryBean) {
waitForServerToStart(host, port);
}
return bean;
}
private boolean shouldCheckWhetherGemFireServerIsRunning(Object bean, String beanName) {
return (isGemFireRegion(bean, beanName)
? this.checkGemFireServerIsRunning.compareAndSet(true, false)
: whenGemFirePool(bean, beanName));
}
private boolean isGemFireRegion(Object bean, String beanName) {
return (GemFireHttpSessionConfiguration.DEFAULT_SESSION_REGION_NAME.equals(beanName)
|| bean instanceof Region);
}
private boolean whenGemFirePool(Object bean, String beanName) {
if (bean instanceof Pool) {
this.gemfirePool.compareAndSet(null, (Pool) bean);
}
return false;
}
private void validateCacheClientNotified() throws InterruptedException {
boolean didNotTimeout = LATCH.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
Assert.state(didNotTimeout, String.format(
"Apache Geode Cache Server failed to start on host [%s] and port [%d]", this.host, this.port));
}
@SuppressWarnings("all")
private void validateCacheClientSubscriptionQueueConnectionEstablished() throws InterruptedException {
boolean cacheClientSubscriptionQueueConnectionEstablished = false;
Pool pool = defaultIfNull(this.gemfirePool.get(),
GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME, GEMFIRE_DEFAULT_POOL_NAME);
if (pool instanceof PoolImpl) {
long timeout = (System.currentTimeMillis() + DEFAULT_TIMEOUT);
while (System.currentTimeMillis() < timeout && !((PoolImpl) pool).isPrimaryUpdaterAlive()) {
synchronized (pool) {
TimeUnit.MILLISECONDS.timedWait(pool, 500L);
}
}
cacheClientSubscriptionQueueConnectionEstablished |=
((PoolImpl) pool).isPrimaryUpdaterAlive();
}
Assert.state(cacheClientSubscriptionQueueConnectionEstablished,
String.format("Cache client subscription queue connection not established; Apache Geode Pool was [%s];"
+ " Apache Geode Pool configuration was [locators = %s, servers = %s]",
pool, pool.getLocators(), pool.getServers()));
}
private Pool defaultIfNull(Pool pool, String... poolNames) {
for (String poolName : poolNames) {
pool = (pool != null ? pool : PoolManager.find(poolName));
}
return pool;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}

View File

@@ -1,2 +1,2 @@
application.geode.client-server.host=localhost
application.geode.client-server.port=40404
spring.data.gemfire.cache.server..host=localhost
spring.data.gemfire.cache.server.port=42424

View File

@@ -19,7 +19,7 @@
<!--1-->
<util:properties id="gemfireProperties">
<prop key="name">SpringSessionSampleXmlGemFireClientServer</prop>
<prop key="name">SpringSessionDataGeodeXmlSampleServer</prop>
<prop key="log-level">${spring.session.data.gemfire.log-level:error}</prop>
</util:properties>
@@ -28,9 +28,9 @@
<!--3-->
<gfe:cache-server auto-startup="true"
bind-address="${application.geode.client-server.host:localhost}"
host-name-for-clients="${application.geode.client-server.host:localhost}"
port="${spring.session.data.geode.cache.server.port:${application.geode.client-server.port:40404}}"/>
bind-address="${spring.session.data.geode.cache.server.host:${spring.data.gemfire.cache.server.host:localhost}}"
host-name-for-clients="${spring.session.data.geode.cache.server.host:${spring.data.gemfire.cache.server.host:localhost}}"
port="${spring.session.data.geode.cache.server.port:${spring.data.gemfire.cache.server.port:40404}}"/>
<!--4-->
<bean class="org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration"

View File

@@ -28,9 +28,9 @@
<gfe:client-cache properties-ref="gemfireProperties" pool-name="gemfirePool"/>
<!--3-->
<gfe:pool ping-interval="5000" read-timeout="15000" retry-attempts="1" subscription-enabled="true">
<gfe:server host="${application.geode.client-server.host}"
port="${spring.session.data.geode.cache.server.port:${application.geode.client-server.port:40404}}"/>
<gfe:pool read-timeout="15000" retry-attempts="1" subscription-enabled="true">
<gfe:server host="${spring.session.data.geode.cache.server.host:${spring.data.gemfire.cache.server.host:localhost}}"
port="${spring.session.data.geode.cache.server.port:${spring.data.gemfire.cache.server.port:40404}}"/>
</gfe:pool>
<!--4-->