DATAGEODE-13 - Introduce well-known, documented properties for Annotation config attributes.

This commit is contained in:
John Blum
2017-06-02 15:23:00 -07:00
parent 5ce738c2b0
commit 0ee6c6ed49
61 changed files with 3796 additions and 1204 deletions

View File

@@ -54,7 +54,7 @@ import org.springframework.data.gemfire.support.ConnectionEndpointList;
import org.springframework.data.gemfire.test.support.ClientServerIntegrationTestsSupport;
import org.springframework.data.gemfire.util.PropertiesBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import lombok.Data;
import lombok.NonNull;
@@ -75,11 +75,15 @@ import lombok.RequiredArgsConstructor;
* with the data of interest are targeted.
*
* @author John Blum
* @see org.junit.Test
* @see org.junit.runner.RunWith
* @see org.springframework.data.gemfire.GemfireTemplate
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringRunner
* @see <a href="https://jira.spring.io/browse/SGF-555">Repository queries on client Regions associated with a Pool configured with a specified server group can lead to a RegionNotFoundException.</a>
* @since 1.9.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration(classes =
GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationTests.GemFireClientCacheConfiguration.class)
@SuppressWarnings("unused")
@@ -147,6 +151,7 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
static class GemFireClientCacheConfiguration {
Properties gemfireProperties() {
return PropertiesBuilder.create()
.setProperty("name", applicationName())
.setProperty("log-level", logLevel())
@@ -163,6 +168,7 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
@Bean
ClientCacheFactoryBean gemfireCache() {
ClientCacheFactoryBean gemfireCache = new ClientCacheFactoryBean();
gemfireCache.setClose(true);
@@ -174,6 +180,7 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
@Bean(name = "ServerOnePool")
PoolFactoryBean serverOnePool() {
PoolFactoryBean serverOnePool = new PoolFactoryBean();
serverOnePool.setMaxConnections(2);
@@ -188,6 +195,7 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
@Bean(name = "ServerTwoPool")
PoolFactoryBean serverTwoPool() {
PoolFactoryBean serverOnePool = new PoolFactoryBean();
serverOnePool.setMaxConnections(2);
@@ -248,6 +256,7 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
static abstract class AbstractGemFireCacheServerConfiguration {
Properties gemfireProperties() {
return PropertiesBuilder.create()
.setProperty("name", applicationName())
.setProperty("mcast-port", "0")
@@ -275,6 +284,7 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
@Bean
CacheFactoryBean gemfireCache() {
CacheFactoryBean gemfireCache = new CacheFactoryBean();
gemfireCache.setClose(true);
@@ -284,11 +294,12 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
}
@Bean
CacheServerFactoryBean gemfireCacheServer(Cache gemfireCache) {
CacheServerFactoryBean gemfireCacheServer(GemFireCache gemfireCache) {
CacheServerFactoryBean gemfireCacheServer = new CacheServerFactoryBean();
gemfireCacheServer.setAutoStartup(true);
gemfireCacheServer.setCache(gemfireCache);
gemfireCacheServer.setCache((Cache) gemfireCache);
gemfireCacheServer.setMaxTimeBetweenPings(Long.valueOf(TimeUnit.SECONDS.toMillis(60)).intValue());
gemfireCacheServer.setPort(cacheServerPort());
@@ -336,7 +347,8 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
}
@Bean(name = "Cats")
LocalRegionFactoryBean catsRegion(Cache gemfireCache) {
LocalRegionFactoryBean catsRegion(GemFireCache gemfireCache) {
LocalRegionFactoryBean catsRegion = new LocalRegionFactoryBean();
catsRegion.setCache(gemfireCache);
@@ -381,7 +393,8 @@ public class GemfireTemplateQueriesOnGroupedPooledClientCacheRegionsIntegrationT
}
@Bean(name = "Dogs")
LocalRegionFactoryBean<String, Dog> dogsRegion(Cache gemfireCache) {
LocalRegionFactoryBean<String, Dog> dogsRegion(GemFireCache gemfireCache) {
LocalRegionFactoryBean<String, Dog> dogsRegion = new LocalRegionFactoryBean<String, Dog>();
dogsRegion.setCache(gemfireCache);

View File

@@ -76,20 +76,24 @@ public class AbstractCacheConfigurationUnitTests {
}
@SuppressWarnings("unchecked")
protected <T> T invokeMethod(Object obj, String methodName) throws Exception {
private <T> T invokeMethod(Object obj, String methodName) throws Exception {
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetObject(obj);
methodInvoker.setTargetMethod(methodName);
methodInvoker.prepare();
return (T) methodInvoker.invoke();
}
@Test
public void configurePdxWhenEnablePdxIsConfigured() {
AnnotationMetadata mockAnnotationMetadata = mock(AnnotationMetadata.class);
PdxSerializer mockPdxSerializer = mock(PdxSerializer.class);
Map<String, Object> annotationAttributes = new HashMap<String, Object>(5);
Map<String, Object> annotationAttributes = new HashMap<>(5);
annotationAttributes.put("diskStoreName", "BlockDiskStore");
annotationAttributes.put("ignoreUnreadFields", Boolean.FALSE);
@@ -98,19 +102,18 @@ public class AbstractCacheConfigurationUnitTests {
annotationAttributes.put("serializerBeanName", "MockPdxSerializer");
when(mockAnnotationMetadata.hasAnnotation(eq(EnablePdx.class.getName()))).thenReturn(true);
when(mockAnnotationMetadata.getAnnotationAttributes(eq(EnablePdx.class.getName())))
.thenReturn(annotationAttributes);
when(mockAnnotationMetadata.getAnnotationAttributes(eq(EnablePdx.class.getName()))).thenReturn(annotationAttributes);
when(mockBeanFactory.containsBean(eq("MockPdxSerializer"))).thenReturn(true);
when(mockBeanFactory.getBean(eq("MockPdxSerializer"), eq(PdxSerializer.class))).thenReturn(mockPdxSerializer);
cacheConfiguration.setBeanFactory(mockBeanFactory);
cacheConfiguration.configurePdx(mockAnnotationMetadata);
assertThat(cacheConfiguration.pdxDiskStoreName()).isEqualTo("BlockDiskStore");
assertThat(cacheConfiguration.pdxIgnoreUnreadFields()).isFalse();
assertThat(cacheConfiguration.pdxPersistent()).isTrue();
assertThat(cacheConfiguration.pdxReadSerialized()).isTrue();
assertThat(cacheConfiguration.pdxSerializer()).isEqualTo(mockPdxSerializer);
assertThat(cacheConfiguration.getPdxDiskStoreName()).isEqualTo("BlockDiskStore");
assertThat(cacheConfiguration.getPdxIgnoreUnreadFields()).isFalse();
assertThat(cacheConfiguration.getPdxPersistent()).isTrue();
assertThat(cacheConfiguration.getPdxReadSerialized()).isTrue();
assertThat(cacheConfiguration.getPdxSerializer()).isEqualTo(mockPdxSerializer);
verify(mockAnnotationMetadata, times(1)).hasAnnotation(eq(EnablePdx.class.getName()));
verify(mockAnnotationMetadata, times(1)).getAnnotationAttributes(eq(EnablePdx.class.getName()));
@@ -120,17 +123,18 @@ public class AbstractCacheConfigurationUnitTests {
@Test
public void configurePdxWhenEnablePdxIsNotConfigured() {
AnnotationMetadata mockAnnotationMetadata = mock(AnnotationMetadata.class);
when(mockAnnotationMetadata.hasAnnotation(anyString())).thenReturn(false);
cacheConfiguration.configurePdx(mockAnnotationMetadata);
assertThat(cacheConfiguration.pdxDiskStoreName()).isNull();
assertThat(cacheConfiguration.pdxIgnoreUnreadFields()).isNull();
assertThat(cacheConfiguration.pdxPersistent()).isNull();
assertThat(cacheConfiguration.pdxReadSerialized()).isNull();
assertThat(cacheConfiguration.pdxSerializer()).isNull();
assertThat(cacheConfiguration.getPdxDiskStoreName()).isNull();
assertThat(cacheConfiguration.getPdxIgnoreUnreadFields()).isNull();
assertThat(cacheConfiguration.getPdxPersistent()).isNull();
assertThat(cacheConfiguration.getPdxReadSerialized()).isNull();
assertThat(cacheConfiguration.getPdxSerializer()).isNull();
verify(mockAnnotationMetadata, times(1)).hasAnnotation(eq(EnablePdx.class.getName()));
verifyNoMoreInteractions(mockAnnotationMetadata);
@@ -138,6 +142,7 @@ public class AbstractCacheConfigurationUnitTests {
@Test
public void resolvePdxSerializerUsesPdxSerializerBean() {
PdxSerializer mockPdxSerializer = mock(PdxSerializer.class);
when(mockBeanFactory.containsBean(anyString())).thenReturn(true);
@@ -155,6 +160,7 @@ public class AbstractCacheConfigurationUnitTests {
@Test
public void resolvePdxSerializerUsesConfiguredPdxSerializer() {
PdxSerializer mockPdxSerializer = mock(PdxSerializer.class);
when(mockBeanFactory.containsBean(anyString())).thenReturn(false);
@@ -173,6 +179,7 @@ public class AbstractCacheConfigurationUnitTests {
@Test
public void resolvePdxSerializerCallsNewMappingPdxSerializer() {
AbstractCacheConfiguration cacheConfigurationSpy = spy(this.cacheConfiguration);
MappingPdxSerializer mockPdxSerializer = mock(MappingPdxSerializer.class);
@@ -192,6 +199,7 @@ public class AbstractCacheConfigurationUnitTests {
@Test
public void newPdxSerializerUsesConfiguredConversionServiceAndMappingContext() throws Exception {
ConfigurableBeanFactory mockBeanFactory = mock(ConfigurableBeanFactory.class);
ConversionService mockConversionService = mock(ConversionService.class);
GemfireMappingContext mockMappingContext = mock(GemfireMappingContext.class);
@@ -207,13 +215,14 @@ public class AbstractCacheConfigurationUnitTests {
assertThat((Object) invokeMethod(pdxSerializer, "getConversionService")).isEqualTo(mockConversionService);
assertThat((Object) invokeMethod(pdxSerializer, "getMappingContext")).isEqualTo(mockMappingContext);
verify(mockBeanFactory, times(1)).getConversionService();
verify(mockBeanFactory, times(2)).getConversionService();
verifyZeroInteractions(mockConversionService);
verifyZeroInteractions(mockMappingContext);
}
@Test
public void newPdxSerializerDefaultsConversionServiceAndMappingContextWhenNotConfigured() throws Exception {
cacheConfiguration.setBeanFactory(mockBeanFactory);
MappingPdxSerializer pdxSerializer = cacheConfiguration.newPdxSerializer();

View File

@@ -0,0 +1,132 @@
/*
* 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 org.springframework.data.gemfire.config.annotation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.cache.server.ClientSubscriptionConfig;
import org.junit.After;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.data.gemfire.server.SubscriptionEvictionPolicy;
import org.springframework.data.gemfire.test.mock.MockGemFireObjectsSupport;
import org.springframework.mock.env.MockPropertySource;
/**
* The CacheServerPropertiesIntegrationTests class...
*
* @author John Blum
* @since 1.0.0
*/
public class CacheServerPropertiesIntegrationTests {
private ConfigurableApplicationContext applicationContext;
@After
public void tearDown() {
Optional.ofNullable(this.applicationContext).ifPresent(ConfigurableApplicationContext::close);
}
private ConfigurableApplicationContext newApplicationContext(PropertySource<?> testPropertySource,
Class<?>... annotatedClasses) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
propertySources.addFirst(testPropertySource);
applicationContext.registerShutdownHook();
applicationContext.register(annotatedClasses);
applicationContext.refresh();
return applicationContext;
}
@Test
public void cacheServerConfigurationIsCorrect() {
MockPropertySource testPropertySource = new MockPropertySource()
.withProperty("gemfire.cache.server.port", "12480")
.withProperty("spring.data.gemfire.cache.server.bind-address", "10.120.12.1")
.withProperty("spring.data.gemfire.cache.server.max-connections", 500)
.withProperty("spring.data.gemfire.cache.server.max-time-between-pings", 30000)
.withProperty("spring.data.gemfire.cache.server.TestCacheServer.max-time-between-pings", 15000)
.withProperty("spring.data.gemfire.cache.server.NonExistingCacheServer.max-time-between-pings", 5000)
.withProperty("spring.data.gemfire.cache.server.TestCacheServer.subscription-capacity", 200)
.withProperty("spring.data.gemfire.cache.server.port", "${gemfire.cache.server.port:12345}")
.withProperty("spring.data.gemfire.cache.server.TestCacheServer.subscription-eviction-policy", "MEM");
this.applicationContext = newApplicationContext(testPropertySource, TestCacheServerConfiguration.class);
assertThat(this.applicationContext).isNotNull();
assertThat(this.applicationContext.containsBean("TestCacheServer")).isTrue();
CacheServer testCacheServer = this.applicationContext.getBean("TestCacheServer", CacheServer.class);
assertThat(testCacheServer).isNotNull();
assertThat(testCacheServer.getBindAddress()).isEqualTo("10.120.12.1");
assertThat(testCacheServer.getHostnameForClients()).isEqualTo("skullbox");
assertThat(testCacheServer.getLoadPollInterval()).isEqualTo(CacheServer.DEFAULT_LOAD_POLL_INTERVAL);
assertThat(testCacheServer.getMaxConnections()).isEqualTo(1200);
assertThat(testCacheServer.getMaximumMessageCount()).isEqualTo(400000);
assertThat(testCacheServer.getMaxThreads()).isEqualTo(8);
assertThat(testCacheServer.getMessageTimeToLive()).isEqualTo(600);
assertThat(testCacheServer.getPort()).isEqualTo(12480);
assertThat(testCacheServer.getSocketBufferSize()).isEqualTo(CacheServer.DEFAULT_SOCKET_BUFFER_SIZE);
assertThat(testCacheServer.getTcpNoDelay()).isEqualTo(CacheServer.DEFAULT_TCP_NO_DELAY);
ClientSubscriptionConfig testClientSubscriptionConfig = testCacheServer.getClientSubscriptionConfig();
assertThat(testClientSubscriptionConfig).isNotNull();
assertThat(testClientSubscriptionConfig.getCapacity()).isEqualTo(200);
assertThat(testClientSubscriptionConfig.getDiskStoreName()).isEmpty();
assertThat(testClientSubscriptionConfig.getEvictionPolicy()).isEqualTo("mem");
}
// TODO add more tests!
@Configuration
@EnableCacheServer(name = "TestCacheServer", bindAddress = "192.16.0.22", hostnameForClients = "skullbox",
maxConnections = 100, maxThreads = 8, messageTimeToLive = 300, port = 11235, subscriptionCapacity = 100,
subscriptionEvictionPolicy = SubscriptionEvictionPolicy.ENTRY)
static class TestCacheServerConfiguration {
@Bean("gemfireCache")
GemFireCache mockGemFireCache() {
return MockGemFireObjectsSupport.mockPeerCache();
}
@Bean
CacheServerConfigurer testCacheServerConfigurer() {
return (beanName, beanFactory) -> {
beanFactory.setMaxConnections(1200);
beanFactory.setMaxMessageCount(400000);
beanFactory.setMessageTimeToLive(600);
};
}
}
}

View File

@@ -0,0 +1,162 @@
/*
* 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 org.springframework.data.gemfire.config.annotation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import java.util.Optional;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.client.PoolFactory;
import org.apache.geode.cache.control.ResourceManager;
import org.apache.geode.pdx.PdxSerializer;
import org.junit.After;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.data.gemfire.test.mock.annotation.EnableGemFireMocking;
import org.springframework.mock.env.MockPropertySource;
/**
* The ClientCachePropertiesIntegrationTests class...
*
* @author John Blum
* @since 1.0.0
*/
public class ClientCachePropertiesIntegrationTests {
private ConfigurableApplicationContext applicationContext;
@After
public void tearDown() {
Optional.ofNullable(this.applicationContext).ifPresent(ConfigurableApplicationContext::close);
}
private ConfigurableApplicationContext newApplicationContext(PropertySource<?> testPropertySource,
Class<?>... annotatedClasses) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
propertySources.addFirst(testPropertySource);
applicationContext.registerShutdownHook();
applicationContext.register(annotatedClasses);
applicationContext.refresh();
return applicationContext;
}
@Test
public void clientCacheConfiguration() {
MockPropertySource testPropertySource = new MockPropertySource()
.withProperty("spring.data.gemfire.cache.critical-heap-percentage", 90.0f)
.withProperty("spring.data.gemfire.cache.eviction-heap-percentage", 85.0f)
.withProperty("spring.data.gemfire.pdx.ignore-unread-fields", false)
.withProperty("spring.data.gemfire.pdx.persistent", true)
.withProperty("spring.data.gemfire.pool.free-connection-timeout", 20000L)
.withProperty("spring.data.gemfire.pool.max-connections", 250)
.withProperty("spring.data.gemfire.pool.ping-interval", 5000L)
.withProperty("spring.data.gemfire.pool.pr-single-hop-enabled", false)
.withProperty("spring.data.gemfire.pool.default.read-timeout", 5000L)
.withProperty("spring.data.gemfire.pool.read-timeout", 20000L)
.withProperty("spring.data.gemfire.pool.retry-attempts", 2)
.withProperty("spring.data.gemfire.pool.server-group", "testGroup")
.withProperty("spring.data.gemfire.pool.default.subscription-redundancy", 2);
this.applicationContext = newApplicationContext(testPropertySource, TestClientCacheConfiguration.class);
assertThat(this.applicationContext).isNotNull();
assertThat(this.applicationContext.containsBean("gemfireCache")).isTrue();
assertThat(this.applicationContext.containsBean("mockPdxSerializer")).isTrue();
ClientCache testClientCache = this.applicationContext.getBean("gemfireCache", ClientCache.class);
PdxSerializer mockPdxSerializer = this.applicationContext.getBean("mockPdxSerializer", PdxSerializer.class);
assertThat(mockPdxSerializer).isNotNull();
assertThat(testClientCache).isNotNull();
assertThat(testClientCache.getCopyOnRead()).isTrue();
assertThat(testClientCache.getPdxDiskStore()).isNull();
assertThat(testClientCache.getPdxIgnoreUnreadFields()).isFalse();
assertThat(testClientCache.getPdxPersistent()).isTrue();
assertThat(testClientCache.getPdxReadSerialized()).isFalse();
assertThat(testClientCache.getPdxSerializer()).isSameAs(mockPdxSerializer);
Pool defaultPool = testClientCache.getDefaultPool();
assertThat(defaultPool).isNotNull();
assertThat(defaultPool.getFreeConnectionTimeout()).isEqualTo(20000);
assertThat(defaultPool.getIdleTimeout()).isEqualTo(15000L);
assertThat(defaultPool.getLoadConditioningInterval()).isEqualTo(180000);
assertThat(defaultPool.getMaxConnections()).isEqualTo(250);
assertThat(defaultPool.getMinConnections()).isEqualTo(50);
assertThat(defaultPool.getMultiuserAuthentication()).isFalse();
assertThat(defaultPool.getName()).isEqualTo("DEFAULT");
assertThat(defaultPool.getPingInterval()).isEqualTo(5000L);
assertThat(defaultPool.getPRSingleHopEnabled()).isFalse();
assertThat(defaultPool.getReadTimeout()).isEqualTo(5000);
assertThat(defaultPool.getRetryAttempts()).isEqualTo(2);
assertThat(defaultPool.getServerGroup()).isEqualTo("testGroup");
assertThat(defaultPool.getSocketBufferSize()).isEqualTo(PoolFactory.DEFAULT_SOCKET_BUFFER_SIZE);
assertThat(defaultPool.getStatisticInterval()).isEqualTo(500);
assertThat(defaultPool.getSubscriptionAckInterval()).isEqualTo(PoolFactory.DEFAULT_SUBSCRIPTION_ACK_INTERVAL);
assertThat(defaultPool.getSubscriptionEnabled()).isTrue();
assertThat(defaultPool.getSubscriptionMessageTrackingTimeout()).isEqualTo(PoolFactory.DEFAULT_SUBSCRIPTION_MESSAGE_TRACKING_TIMEOUT);
assertThat(defaultPool.getSubscriptionRedundancy()).isEqualTo(2);
ResourceManager resourceManager = testClientCache.getResourceManager();
assertThat(resourceManager).isNotNull();
assertThat(resourceManager.getCriticalHeapPercentage()).isEqualTo(90.0f);
assertThat(resourceManager.getEvictionHeapPercentage()).isEqualTo(90.0f);
}
// TODO add more tests!
@EnableGemFireMocking
@EnablePdx(ignoreUnreadFields = true, readSerialized = true, serializerBeanName = "mockPdxSerializer")
@ClientCacheApplication(name = "TestClientCache", copyOnRead = true,
criticalHeapPercentage = 95.0f, evictionHeapPercentage = 80.0f, idleTimeout = 15000L,
maxConnections = 100, minConnections = 10, pingInterval = 15000L, readTimeout = 15000, retryAttempts = 1,
subscriptionEnabled = true, subscriptionRedundancy = 1)
static class TestClientCacheConfiguration {
@Bean
ClientCacheConfigurer testClientCacheConfigurer() {
return (beanName, factoryBean) -> {
factoryBean.setEvictionHeapPercentage(90.0f);
factoryBean.setPdxReadSerialized(false);
factoryBean.setLoadConditioningInterval(180000);
factoryBean.setMinConnections(50);
factoryBean.setStatisticsInterval(500);
};
}
@Bean
PdxSerializer mockPdxSerializer() {
return mock(PdxSerializer.class);
}
}
}

View File

@@ -67,6 +67,7 @@ public class ClientServerCacheApplicationIntegrationTests extends ClientServerIn
@BeforeClass
public static void setupGemFireServer() throws Exception {
gemfireServerProcess = run(CacheServerApplicationConfiguration.class, String.format("-Dgemfire.name=%1$s",
asApplicationName(ClientServerCacheApplicationIntegrationTests.class)));
@@ -99,6 +100,7 @@ public class ClientServerCacheApplicationIntegrationTests extends ClientServerIn
@Bean("Echo")
public PartitionedRegionFactoryBean<String, String> echoRegion(Cache gemfireCache) {
PartitionedRegionFactoryBean<String, String> echoRegion =
new PartitionedRegionFactoryBean<String, String>();
@@ -111,6 +113,7 @@ public class ClientServerCacheApplicationIntegrationTests extends ClientServerIn
}
CacheLoader<String, String> echoCacheLoader() {
return new CacheLoader<String, String>() {
@Override
public String load(LoaderHelper<String, String> helper) throws CacheLoaderException {
@@ -129,6 +132,7 @@ public class ClientServerCacheApplicationIntegrationTests extends ClientServerIn
@Bean(name = "Echo")
ClientRegionFactoryBean<String, String> echoRegion(ClientCache gemfireCache) {
ClientRegionFactoryBean<String, String> echoRegion = new ClientRegionFactoryBean<String, String>();
echoRegion.setCache(gemfireCache);

View File

@@ -0,0 +1,121 @@
/*
* 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 org.springframework.data.gemfire.config.annotation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.DiskStoreFactory;
import org.apache.geode.cache.GemFireCache;
import org.junit.After;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.data.gemfire.test.mock.MockGemFireObjectsSupport;
import org.springframework.mock.env.MockPropertySource;
/**
* The DiskStorePropertiesIntegrationTests class...
*
* @author John Blum
* @since 1.0.0
*/
public class DiskStorePropertiesIntegrationTests {
private ConfigurableApplicationContext applicationContext;
@After
public void tearDown() {
Optional.ofNullable(this.applicationContext).ifPresent(ConfigurableApplicationContext::close);
}
private ConfigurableApplicationContext newApplicationContext(PropertySource<?> testPropertySource,
Class<?>... annotatedClasses) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
propertySources.addFirst(testPropertySource);
applicationContext.registerShutdownHook();
applicationContext.register(annotatedClasses);
applicationContext.refresh();
return applicationContext;
}
@Test
public void diskStoreConfigurationIsCorrect() {
MockPropertySource testPropertySource = new MockPropertySource()
.withProperty("spring.data.gemfire.disk.store.compaction-threshold", 85)
.withProperty("spring.data.gemfire.disk.store.disk-usage-critical-percentage", 90.0f)
.withProperty("spring.data.gemfire.disk.store.disk-usage-warning-percentage", 80.0f)
.withProperty("spring.data.gemfire.disk.store.TestDiskStore.disk-usage-warning-percentage", 85.0f)
.withProperty("spring.data.gemfire.disk.store.time-interval", 500L)
.withProperty("spring.data.gemfire.disk.store.NonExistingDiskStore.time-interval", 30000L);
this.applicationContext = newApplicationContext(testPropertySource, TestDiskStoreConfiguration.class);
assertThat(this.applicationContext).isNotNull();
assertThat(this.applicationContext.containsBean("TestDiskStore")).isTrue();
DiskStore testDiskStore = this.applicationContext.getBean("TestDiskStore", DiskStore.class);
assertThat(testDiskStore).isNotNull();
assertThat(testDiskStore.getName()).isEqualTo("TestDiskStore");
assertThat(testDiskStore.getAllowForceCompaction()).isTrue();
assertThat(testDiskStore.getAutoCompact()).isTrue();
assertThat(testDiskStore.getCompactionThreshold()).isEqualTo(75);
assertThat(testDiskStore.getDiskUsageCriticalPercentage()).isEqualTo(90.0f);
assertThat(testDiskStore.getDiskUsageWarningPercentage()).isEqualTo(85.0f);
assertThat(testDiskStore.getMaxOplogSize()).isEqualTo(512L);
assertThat(testDiskStore.getQueueSize()).isEqualTo(DiskStoreFactory.DEFAULT_QUEUE_SIZE);
assertThat(testDiskStore.getTimeInterval()).isEqualTo(500L);
assertThat(testDiskStore.getWriteBufferSize()).isEqualTo(DiskStoreFactory.DEFAULT_WRITE_BUFFER_SIZE);
}
// TODO add more tests!
@Configuration
@EnableDiskStore(name = "TestDiskStore", allowForceCompaction = true, compactionThreshold = 65,
diskUsageCriticalPercentage = 95.0f, diskUsageWarningPercentage = 75.0f, maxOplogSize = 2048L)
@SuppressWarnings("unused")
static class TestDiskStoreConfiguration {
@Bean("gemfireCache")
GemFireCache mockGemFireCache() {
return MockGemFireObjectsSupport.mockGemFireCache();
}
@Bean
DiskStoreConfigurer testDiskStoreConfigurer() {
return (beanName, factoryBean) -> {
factoryBean.setCompactionThreshold(75);
//factoryBean.setDiskUsageWarningPercentage(95.0f);
factoryBean.setMaxOplogSize(512L);
};
}
}
}

View File

@@ -18,30 +18,19 @@
package org.springframework.data.gemfire.config.annotation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.DiskStoreFactory;
import org.junit.After;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.gemfire.test.mock.annotation.EnableGemFireMocking;
/**
* Unit tests for the {@link EnableDiskStore} and {@link EnableDiskStores} annotations as well as
@@ -49,7 +38,12 @@ import org.springframework.context.annotation.Configuration;
*
* @author John Blum
* @see org.junit.Test
* @see org.mockito.Mockito
* @see org.apache.geode.cache.DiskStore
* @see org.springframework.context.ConfigurableApplicationContext
* @see org.springframework.data.gemfire.config.annotation.EnableDiskStore
* @see org.springframework.data.gemfire.config.annotation.EnableDiskStores
* @see org.springframework.data.gemfire.config.annotation.DiskStoreConfiguration
* @see org.springframework.data.gemfire.config.annotation.DiskStoresConfiguration
* @since 1.9.0
*/
public class EnableDiskStoresConfigurationUnitTests {
@@ -60,13 +54,11 @@ public class EnableDiskStoresConfigurationUnitTests {
@After
public void tearDown() {
if (applicationContext != null) {
applicationContext.close();
}
Optional.ofNullable(this.applicationContext).ifPresent(ConfigurableApplicationContext::close);
}
/* (non-Javadoc) */
protected void assertDiskStore(DiskStore diskStore, String name, boolean allowForceCompaction, boolean autoCompact,
private void assertDiskStore(DiskStore diskStore, String name, boolean allowForceCompaction, boolean autoCompact,
int compactionThreshold, float diskUsageCriticalPercentage, float diskUsageWarningPercentage,
long maxOplogSize, int queueSize, long timeInterval, int writeBufferSize) {
@@ -84,7 +76,8 @@ public class EnableDiskStoresConfigurationUnitTests {
}
/* (non-Javadoc) */
protected void assertDiskStoreDirectoryLocations(DiskStore diskStore, File... diskDirectories) {
private void assertDiskStoreDirectoryLocations(DiskStore diskStore, File... diskDirectories) {
assertThat(diskStore).isNotNull();
File[] diskStoreDirectories = diskStore.getDiskDirs();
@@ -100,7 +93,8 @@ public class EnableDiskStoresConfigurationUnitTests {
}
/* (non-Javadoc) */
protected void assertDiskStoreDirectorySizes(DiskStore diskStore, int... diskDirectorySizes) {
private void assertDiskStoreDirectorySizes(DiskStore diskStore, int... diskDirectorySizes) {
assertThat(diskStore).isNotNull();
int[] diskStoreDirectorySizes = diskStore.getDiskDirSizes();
@@ -116,22 +110,23 @@ public class EnableDiskStoresConfigurationUnitTests {
}
/* (non-Javadoc) */
protected File newFile(String location) {
return new File(location);
}
/* (non-Javadoc) */
protected ConfigurableApplicationContext newApplicationContext(Class<?>... annotatedClasses) {
private ConfigurableApplicationContext newApplicationContext(Class<?>... annotatedClasses) {
ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(annotatedClasses);
applicationContext.registerShutdownHook();
return applicationContext;
}
/* (non-Javadoc) */
private File newFile(String location) {
return new File(location);
}
@Test
public void enableSingleDiskStore() {
applicationContext = newApplicationContext(SingleDiskStoreConfiguration.class);
DiskStore testDiskStore = applicationContext.getBean("TestDiskStore", DiskStore.class);
this.applicationContext = newApplicationContext(SingleDiskStoreConfiguration.class);
DiskStore testDiskStore = this.applicationContext.getBean("TestDiskStore", DiskStore.class);
assertDiskStore(testDiskStore, "TestDiskStore", true, true, 75, 95.0f, 75.0f, 8192L, 100, 2000L, 65536);
assertDiskStoreDirectoryLocations(testDiskStore, newFile("/absolute/path/to/gemfire/disk/directory"),
@@ -140,14 +135,15 @@ public class EnableDiskStoresConfigurationUnitTests {
}
@Test
public void enablesMultipleDiskStores() {
applicationContext = newApplicationContext(MultipleDiskStoresConfiguration.class);
public void enableMultipleDiskStores() {
DiskStore testDiskStoreOne = applicationContext.getBean("TestDiskStoreOne", DiskStore.class);
this.applicationContext = newApplicationContext(MultipleDiskStoresConfiguration.class);
DiskStore testDiskStoreOne = this.applicationContext.getBean("TestDiskStoreOne", DiskStore.class);
assertDiskStore(testDiskStoreOne, "TestDiskStoreOne", false, true, 75, 99.0f, 90.0f, 2048L, 100, 1000L, 32768);
DiskStore testDiskStoreTwo = applicationContext.getBean("TestDiskStoreTwo", DiskStore.class);
DiskStore testDiskStoreTwo = this.applicationContext.getBean("TestDiskStoreTwo", DiskStore.class);
assertDiskStore(testDiskStoreTwo, "TestDiskStoreTwo", true, true, 85, 99.0f, 90.0f, 4096L, 0, 1000L, 32768);
}
@@ -169,121 +165,26 @@ public class EnableDiskStoresConfigurationUnitTests {
};
}
@Configuration
@SuppressWarnings("unused")
static class CacheConfiguration {
@Bean
Cache gemfireCache() {
Cache mockCache = mock(Cache.class);
when(mockCache.createDiskStoreFactory()).thenAnswer(new Answer<DiskStoreFactory>() {
@Override
public DiskStoreFactory answer(InvocationOnMock invocation) throws Throwable {
final DiskStoreFactory mockDiskStoreFactory =
mock(DiskStoreFactory.class, mockName("MockDiskStoreFactory"));
final AtomicReference<Boolean> allowForceCompaction = new AtomicReference<>(false);
final AtomicReference<Boolean> autoCompact = new AtomicReference<>(false);
final AtomicReference<Integer> compactionThreshold = new AtomicReference<>(50);
final AtomicReference<File[]> diskDirectories = new AtomicReference<>(new File[0]);
final AtomicReference<int[]> diskDirectorySizes = new AtomicReference<>(new int[0]);
final AtomicReference<Float> diskUsageCriticalPercentage = new AtomicReference<>(99.0f);
final AtomicReference<Float> diskUsageWarningPercentage = new AtomicReference<>(90.0f);
final AtomicReference<Long> maxOplogSize = new AtomicReference<>(1024L);
final AtomicReference<Integer> queueSize = new AtomicReference<>(0);
final AtomicReference<Long> timeInterval = new AtomicReference<>(1000L);
final AtomicReference<Integer> writeBufferSize = new AtomicReference<>(32768);
when(mockDiskStoreFactory.setAllowForceCompaction(anyBoolean())).thenAnswer(
newSetter(Boolean.TYPE, allowForceCompaction, mockDiskStoreFactory));
when(mockDiskStoreFactory.setAutoCompact(anyBoolean())).thenAnswer(
newSetter(Boolean.TYPE, autoCompact, mockDiskStoreFactory));
when(mockDiskStoreFactory.setCompactionThreshold(anyInt())).thenAnswer(
newSetter(Integer.TYPE, compactionThreshold, mockDiskStoreFactory));
when(mockDiskStoreFactory.setDiskDirsAndSizes(any(File[].class), any(int[].class))).thenAnswer(
new Answer<DiskStoreFactory>() {
@Override public DiskStoreFactory answer(InvocationOnMock invocation) throws Throwable {
File[] localDiskDirectories = invocation.getArgument(0);
int[] localDiskDirectorySizes = invocation.getArgument(1);
diskDirectories.set(localDiskDirectories);
diskDirectorySizes.set(localDiskDirectorySizes);
return mockDiskStoreFactory;
}
}
);
when(mockDiskStoreFactory.setDiskUsageCriticalPercentage(anyFloat())).thenAnswer(
newSetter(Float.TYPE, diskUsageCriticalPercentage, mockDiskStoreFactory));
when(mockDiskStoreFactory.setDiskUsageWarningPercentage(anyFloat())).thenAnswer(
newSetter(Float.TYPE, diskUsageWarningPercentage, mockDiskStoreFactory));
when(mockDiskStoreFactory.setMaxOplogSize(anyLong())).thenAnswer(
newSetter(Long.TYPE, maxOplogSize, mockDiskStoreFactory));
when(mockDiskStoreFactory.setQueueSize(anyInt())).thenAnswer(
newSetter(Integer.TYPE, queueSize, mockDiskStoreFactory));
when(mockDiskStoreFactory.setTimeInterval(anyLong())).thenAnswer(
newSetter(Long.TYPE, timeInterval, mockDiskStoreFactory));
when(mockDiskStoreFactory.setWriteBufferSize(anyInt())).thenAnswer(
newSetter(Integer.TYPE, writeBufferSize, mockDiskStoreFactory));
when(mockDiskStoreFactory.create(anyString())).thenAnswer(new Answer<DiskStore>() {
@Override
public DiskStore answer(InvocationOnMock invocation) throws Throwable {
String diskStoreName = invocation.getArgument(0);
DiskStore mockDiskStore = mock(DiskStore.class, diskStoreName);
when(mockDiskStore.getAllowForceCompaction()).thenAnswer(newGetter(allowForceCompaction));
when(mockDiskStore.getAutoCompact()).thenAnswer(newGetter(autoCompact));
when(mockDiskStore.getCompactionThreshold()).thenAnswer(newGetter(compactionThreshold));
when(mockDiskStore.getDiskDirs()).thenAnswer(newGetter(diskDirectories));
when(mockDiskStore.getDiskDirSizes()).thenAnswer(newGetter(diskDirectorySizes));
when(mockDiskStore.getDiskUsageCriticalPercentage()).thenAnswer(newGetter(diskUsageCriticalPercentage));
when(mockDiskStore.getDiskUsageWarningPercentage()).thenAnswer(newGetter(diskUsageWarningPercentage));
when(mockDiskStore.getMaxOplogSize()).thenAnswer(newGetter(maxOplogSize));
when(mockDiskStore.getName()).thenReturn(diskStoreName);
when(mockDiskStore.getQueueSize()).thenAnswer(newGetter(queueSize));
when(mockDiskStore.getTimeInterval()).thenAnswer(newGetter(timeInterval));
when(mockDiskStore.getWriteBufferSize()).thenAnswer(newGetter(writeBufferSize));
return mockDiskStore;
}
});
return mockDiskStoreFactory;
}
});
return mockCache;
}
}
@PeerCacheApplication
@EnableGemFireMocking
@EnableDiskStore(name = "TestDiskStore", allowForceCompaction = true, autoCompact = true, compactionThreshold = 75,
diskUsageCriticalPercentage = 95.0f, diskUsageWarningPercentage = 75.0f, maxOplogSize = 8192L, queueSize = 100,
timeInterval = 2000L, writeBufferSize = 65536, diskDirectories = {
@EnableDiskStore.DiskDirectory(location = "/absolute/path/to/gemfire/disk/directory", maxSize = 1024),
@EnableDiskStore.DiskDirectory(location = "relative/path/to/gemfire/disk/directory", maxSize = 4096)
})
static class SingleDiskStoreConfiguration extends CacheConfiguration {
static class SingleDiskStoreConfiguration {
}
@PeerCacheApplication
@EnableGemFireMocking
@EnableDiskStores(autoCompact = true, compactionThreshold = 75, maxOplogSize = 2048L, diskStores = {
@EnableDiskStore(name = "TestDiskStoreOne", queueSize = 100),
@EnableDiskStore(name = "TestDiskStoreTwo", allowForceCompaction = true,
compactionThreshold = 85, maxOplogSize = 4096)
})
static class MultipleDiskStoresConfiguration extends CacheConfiguration {
static class MultipleDiskStoresConfiguration {
}
}

View File

@@ -0,0 +1,129 @@
/*
* 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 org.springframework.data.gemfire.config.annotation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import java.util.Optional;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.control.ResourceManager;
import org.apache.geode.pdx.PdxSerializer;
import org.junit.After;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.data.gemfire.test.mock.annotation.EnableGemFireMocking;
import org.springframework.mock.env.MockPropertySource;
/**
* The PeerCachePropertiesIntegrationTests class...
*
* @author John Blum
* @since 1.0.0
*/
public class PeerCachePropertiesIntegrationTests {
private ConfigurableApplicationContext applicationContext;
@After
public void tearDown() {
Optional.ofNullable(this.applicationContext).ifPresent(ConfigurableApplicationContext::close);
}
private ConfigurableApplicationContext newApplicationContext(PropertySource<?> testPropertySource,
Class<?>... annotatedClasses) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
propertySources.addFirst(testPropertySource);
applicationContext.registerShutdownHook();
applicationContext.register(annotatedClasses);
applicationContext.refresh();
return applicationContext;
}
@Test
public void peerCacheConfiguration() {
MockPropertySource testPropertySource = new MockPropertySource()
.withProperty("spring.data.gemfire.cache.copy-on-read", true)
.withProperty("spring.data.gemfire.cache.critical-heap-percentage", 95.0f)
.withProperty("spring.data.gemfire.cache.eviction-heap-percentage", 85.0f)
.withProperty("spring.data.gemfire.cache.peer.lock-lease", 180)
.withProperty("spring.data.gemfire.cache.peer.lock-timeout", 30)
.withProperty("spring.data.gemfire.cache.peer.search-timeout", 120)
.withProperty("spring.data.gemfire.pdx.ignore-unread-fields", false)
.withProperty("spring.data.gemfire.pdx.persistent", true);
this.applicationContext = newApplicationContext(testPropertySource, TestPeerCacheConfiguration.class);
assertThat(this.applicationContext).isNotNull();
assertThat(this.applicationContext.containsBean("gemfireCache")).isTrue();
assertThat(this.applicationContext.containsBean("mockPdxSerializer")).isTrue();
Cache testPeerCache = this.applicationContext.getBean("gemfireCache", Cache.class);
PdxSerializer mockPdxSerializer = this.applicationContext.getBean("mockPdxSerializer", PdxSerializer.class);
assertThat(testPeerCache).isNotNull();
assertThat(mockPdxSerializer).isNotNull();
assertThat(testPeerCache.getLockLease()).isEqualTo(180);
assertThat(testPeerCache.getLockTimeout()).isEqualTo(30);
assertThat(testPeerCache.getPdxDiskStore()).isNull();
assertThat(testPeerCache.getPdxIgnoreUnreadFields()).isFalse();
assertThat(testPeerCache.getPdxPersistent()).isTrue();
assertThat(testPeerCache.getPdxReadSerialized()).isTrue();
assertThat(testPeerCache.getPdxSerializer()).isSameAs(mockPdxSerializer);
assertThat(testPeerCache.getSearchTimeout()).isEqualTo(60);
ResourceManager resourceManager = testPeerCache.getResourceManager();
assertThat(resourceManager).isNotNull();
assertThat(resourceManager.getCriticalHeapPercentage()).isEqualTo(95.0f);
assertThat(resourceManager.getEvictionHeapPercentage()).isEqualTo(85.0f);
}
//TODO add more tests
@EnableGemFireMocking
@EnablePdx(ignoreUnreadFields = true, readSerialized = true, serializerBeanName = "mockPdxSerializer")
@PeerCacheApplication(name = "TestPeerCache", criticalHeapPercentage = 90.0f, evictionHeapPercentage = 75.0f,
lockLease = 300, lockTimeout = 120)
static class TestPeerCacheConfiguration {
@Bean
PeerCacheConfigurer testPeerCacheConfigurer() {
return (beanName, beanFactory) -> {
beanFactory.setSearchTimeout(60);
};
}
@Bean
PdxSerializer mockPdxSerializer() {
return mock(PdxSerializer.class);
}
}
}

View File

@@ -0,0 +1,111 @@
/*
* 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 org.springframework.data.gemfire.config.annotation.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Unit tests for {@link AbstractAnnotationConfigSupport}.
*
* @author John Blum
* @see org.junit.Test
* @see org.junit.runner.RunWith
* @see org.mockito.Mock
* @see org.mockito.Mockito
* @see org.mockito.junit.MockitoJUnitRunner
* @see org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport
* @since 1.1.0
*/
@RunWith(MockitoJUnitRunner.class)
public class AbstractAnnotationConfigSupportTests {
@Mock
private AbstractAnnotationConfigSupport support;
@Test
public void requirePropertyWithNonStringValueIsSuccessful() {
when(support.requireProperty(anyString(), any())).thenCallRealMethod();
when(support.resolveProperty(anyString(), eq(Integer.class), eq(null))).thenReturn(1);
assertThat(support.requireProperty("key", Integer.class)).isEqualTo(1);
verify(support, times(1))
.resolveProperty(eq("key"), eq(Integer.class), eq(null));
}
@Test
public void requirePropertyWithStringValueIsSuccessful() {
when(support.requireProperty(anyString(), any())).thenCallRealMethod();
when(support.resolveProperty(anyString(), eq(String.class), eq(null))).thenReturn("test");
assertThat(support.requireProperty("key", String.class)).isEqualTo("test");
verify(support, times(1))
.resolveProperty(eq("key"), eq(String.class), eq(null));
}
@Test(expected = IllegalArgumentException.class)
public void requirePropertyWithEmptyStringThrowsIllegalArgumentException() {
when(support.requireProperty(anyString(), any())).thenCallRealMethod();
when(support.resolveProperty(anyString(), eq(String.class), eq(null))).thenReturn(" ");
try {
support.requireProperty("key", String.class);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Property [key] is required");
assertThat(expected).hasNoCause();
throw expected;
}
finally {
verify(support, times(1))
.resolveProperty(eq("key"), eq(String.class), eq(null));
}
}
@Test(expected = IllegalArgumentException.class)
public void requirePropertyWithNullValueThrowsIllegalArgumentException() {
when(support.requireProperty(anyString(), any())).thenCallRealMethod();
when(support.resolveProperty(anyString(), any(), eq(null))).thenReturn(null);
try {
support.requireProperty("key", Integer.class);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Property [key] is required");
assertThat(expected).hasNoCause();
throw expected;
}
finally {
verify(support, times(1))
.resolveProperty(eq("key"), eq(Integer.class), eq(null));
}
}
}

View File

@@ -30,19 +30,23 @@ import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.data.gemfire.DiskStoreFactoryBean;
import org.springframework.data.gemfire.config.annotation.PeerCacheApplication;
import org.springframework.data.gemfire.test.support.FileSystemUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.FileSystemUtils;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration tests for {@link DiskStoreDirectoryBeanPostProcessor}.
*
* @author John Blum
* @see org.junit.Test
* @see org.junit.runner.RunWith
* @see org.springframework.data.gemfire.DiskStoreFactoryBean
* @see org.springframework.data.gemfire.config.support.DiskStoreDirectoryBeanPostProcessor
* @see org.springframework.test.context.ContextConfiguration
* @see org.springframework.test.context.junit4.SpringRunner
* @since 1.5.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
public class DiskStoreDirectoryBeanPostProcessorIntegrationTests {
@@ -53,8 +57,8 @@ public class DiskStoreDirectoryBeanPostProcessorIntegrationTests {
@AfterClass
public static void testSuiteTearDown() {
assertThat(FileSystemUtils.deleteRecursively(new File("./gemfire"))).isTrue();
assertThat(FileSystemUtils.deleteRecursively(new File("./gfe"))).isTrue();
assertThat(FileSystemUtils.deleteRecursive(new File("./gemfire"))).isTrue();
assertThat(FileSystemUtils.deleteRecursive(new File("./gfe"))).isTrue();
}
@Test

View File

@@ -24,10 +24,6 @@ import org.springframework.data.gemfire.CacheFactoryBean;
*/
public class MockCacheFactoryBean extends CacheFactoryBean {
public MockCacheFactoryBean() {
this(null);
}
public MockCacheFactoryBean(CacheFactoryBean cacheFactoryBean) {
setUseBeanFactoryLocator(false);

View File

@@ -51,7 +51,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.apache.commons.lang.StringUtils;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.DiskStore;
@@ -77,7 +79,6 @@ import org.springframework.data.gemfire.test.support.FileSystemUtils;
* Mock GemFire Objects (e.g. {@link Cache}, {@link ClientCache}, {@link Region}, etc).
*
* @author John Blum
* @see org.mockito.Mockito
* @see org.apache.geode.cache.Cache
* @see org.apache.geode.cache.CacheFactory
* @see org.apache.geode.cache.DiskStore
@@ -89,10 +90,12 @@ import org.springframework.data.gemfire.test.support.FileSystemUtils;
* @see org.apache.geode.cache.server.CacheServer
* @see org.apache.geode.cache.server.ClientSubscriptionConfig
* @see org.apache.geode.distributed.DistributedSystem
* @see org.mockito.Mockito
* @see org.springframework.data.gemfire.test.mock.MockObjectsSupport
* @since 2.0.0
*/
@SuppressWarnings("unused")
public abstract class MockGemFireObjectsSupport {
public abstract class MockGemFireObjectsSupport extends MockObjectsSupport {
private static final Map<String, DiskStore> diskStores = new ConcurrentHashMap<>();
@@ -110,6 +113,11 @@ public abstract class MockGemFireObjectsSupport {
return (regionPath.lastIndexOf(Region.SEPARATOR) <= 0);
}
private static String toRegionPath(String regionPath) {
return (StringUtils.startsWith(regionPath, Region.SEPARATOR) ? regionPath
: String.format("%1$s%2$s", Region.SEPARATOR, regionPath));
}
/* (non-Javadoc) */
@SuppressWarnings("unchecked")
private static <T extends GemFireCache> T mockCacheApi(T mockGemFireCache) {
@@ -120,17 +128,12 @@ public abstract class MockGemFireObjectsSupport {
ResourceManager mockResourceManager = mockResourceManager();
doAnswer(invocation -> {
copyOnRead.set(invocation.getArgument(0));
return null;
}).when(mockGemFireCache).setCopyOnRead(anyBoolean());
doAnswer(newSetter(copyOnRead, null)).when(mockGemFireCache).setCopyOnRead(anyBoolean());
doAnswer(invocation -> {
regionAttributes.put(invocation.getArgument(0), invocation.getArgument(1));
return null;
}).when(mockGemFireCache).setRegionAttributes(anyString(), any(RegionAttributes.class));
doAnswer(newSetter(regionAttributes, null))
.when(mockGemFireCache).setRegionAttributes(anyString(), any(RegionAttributes.class));
when(mockGemFireCache.getCopyOnRead()).thenAnswer(invocation -> copyOnRead.get());
when(mockGemFireCache.getCopyOnRead()).thenAnswer(newGetter(copyOnRead));
when(mockGemFireCache.getDistributedSystem()).thenReturn(mockDistributedSystem);
@@ -155,14 +158,11 @@ public abstract class MockGemFireObjectsSupport {
/* (non-Javadoc) */
private static <T extends RegionService> T mockRegionServiceApi(T mockRegionService) {
AtomicBoolean close = new AtomicBoolean(false);
AtomicBoolean closed = new AtomicBoolean(false);
doAnswer(invocation -> {
close.set(true);
return null;
}).when(mockRegionService).close();
doAnswer(newSetter(closed, true, null)).when(mockRegionService).close();
when(mockRegionService.isClosed()).thenAnswer(invocation -> close.get());
when(mockRegionService.isClosed()).thenAnswer(newGetter(closed));
when(mockRegionService.getCancelCriterion()).thenThrow(newUnsupportedOperationException(NOT_SUPPORTED));
@@ -171,7 +171,7 @@ public abstract class MockGemFireObjectsSupport {
String regionPath = invocation.getArgument(0);
Optional.ofNullable(regionPath).map(String::trim).filter(it -> !it.isEmpty())
.map(it -> it.startsWith(Region.SEPARATOR) ? it : String.format("%1$s%2$s", Region.SEPARATOR, it))
.map(MockGemFireObjectsSupport::toRegionPath)
.orElseThrow(() -> newIllegalArgumentException("Region path [%s] is not valid", regionPath));
return regions.get(regionPath);
@@ -233,33 +233,18 @@ public abstract class MockGemFireObjectsSupport {
return mockCacheServer;
});
doAnswer(invocation -> {
lockLease.set(invocation.getArgument(0));
return null;
}).when(mockCache).setLockLease(anyInt());
doAnswer(invocation -> {
lockTimeout.set(invocation.getArgument(0));
return null;
}).when(mockCache).setLockTimeout(anyInt());
doAnswer(invocation -> {
messageSyncInterval.set(invocation.getArgument(0));
return null;
}).when(mockCache).setMessageSyncInterval(anyInt());
doAnswer(invocation -> {
searchTimeout.set(invocation.getArgument(0));
return null;
}).when(mockCache).setSearchTimeout(anyInt());
doAnswer(newSetter(lockLease, null)).when(mockCache).setLockLease(anyInt());
doAnswer(newSetter(lockTimeout, null)).when(mockCache).setLockTimeout(anyInt());
doAnswer(newSetter(messageSyncInterval, null)).when(mockCache).setMessageSyncInterval(anyInt());
doAnswer(newSetter(searchTimeout, null)).when(mockCache).setSearchTimeout(anyInt());
when(mockCache.isServer()).thenReturn(true);
when(mockCache.getCacheServers()).thenAnswer(invocation -> Collections.unmodifiableList(cacheServers));
when(mockCache.getLockLease()).thenAnswer(invocation -> lockLease.get());
when(mockCache.getLockTimeout()).thenAnswer(invocation -> lockTimeout.get());
when(mockCache.getMessageSyncInterval()).thenAnswer(invocation -> messageSyncInterval.get());
when(mockCache.getLockLease()).thenAnswer(newGetter(lockLease));
when(mockCache.getLockTimeout()).thenAnswer(newGetter(lockTimeout));
when(mockCache.getMessageSyncInterval()).thenAnswer(newGetter(messageSyncInterval));
when(mockCache.getReconnectedCache()).thenAnswer(invocation -> mockPeerCache());
when(mockCache.getSearchTimeout()).thenAnswer(invocation -> searchTimeout.get());
when(mockCache.getSearchTimeout()).thenAnswer(newGetter(searchTimeout));
return mockCacheApi(mockCache);
}
@@ -283,72 +268,50 @@ public abstract class MockGemFireObjectsSupport {
AtomicReference<String> bindAddress = new AtomicReference<>(CacheServer.DEFAULT_BIND_ADDRESS);
AtomicReference<String> hostnameForClients = new AtomicReference<>(CacheServer.DEFAULT_HOSTNAME_FOR_CLIENTS);
doAnswer(invocation -> {
bindAddress.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setBindAddress(anyString());
doAnswer(newSetter(bindAddress, null))
.when(mockCacheServer).setBindAddress(anyString());
doAnswer(invocation -> {
hostnameForClients.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setHostnameForClients(anyString());
doAnswer(newSetter(hostnameForClients, null))
.when(mockCacheServer).setHostnameForClients(anyString());
doAnswer(invocation -> {
loadPollInterval.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setLoadPollInterval(anyLong());
doAnswer(newSetter(loadPollInterval, null))
.when(mockCacheServer).setLoadPollInterval(anyLong());
doAnswer(invocation -> {
maxConnections.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setMaxConnections(anyInt());
doAnswer(newSetter(maxConnections, null))
.when(mockCacheServer).setMaxConnections(anyInt());
doAnswer(invocation -> {
maxMessageCount.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setMaximumMessageCount(anyInt());
doAnswer(newSetter(maxMessageCount, null))
.when(mockCacheServer).setMaximumMessageCount(anyInt());
doAnswer(invocation -> {
maxThreads.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setMaxThreads(anyInt());
doAnswer(newSetter(maxThreads, null))
.when(mockCacheServer).setMaxThreads(anyInt());
doAnswer(invocation -> {
maxTimeBetweenPings.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setMaximumTimeBetweenPings(anyInt());
doAnswer(newSetter(maxTimeBetweenPings, null))
.when(mockCacheServer).setMaximumTimeBetweenPings(anyInt());
doAnswer(invocation -> {
messageTimeToLive.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setMessageTimeToLive(anyInt());
doAnswer(newSetter(messageTimeToLive, null))
.when(mockCacheServer).setMessageTimeToLive(anyInt());
doAnswer(invocation -> {
port.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setPort(anyInt());
doAnswer(newSetter(port, null))
.when(mockCacheServer).setPort(anyInt());
doAnswer(invocation -> {
socketBufferSize.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setSocketBufferSize(anyInt());
doAnswer(newSetter(socketBufferSize, null))
.when(mockCacheServer).setSocketBufferSize(anyInt());
doAnswer(invocation -> {
tcpNoDelay.set(invocation.getArgument(0));
return null;
}).when(mockCacheServer).setTcpNoDelay(anyBoolean());
doAnswer(newSetter(tcpNoDelay, null))
.when(mockCacheServer).setTcpNoDelay(anyBoolean());
when(mockCacheServer.getBindAddress()).thenAnswer(invocation -> bindAddress.get());
when(mockCacheServer.getHostnameForClients()).thenAnswer(invocation -> hostnameForClients.get());
when(mockCacheServer.getLoadPollInterval()).thenAnswer(invocation -> loadPollInterval.get());
when(mockCacheServer.getMaxConnections()).thenAnswer(invocation -> maxConnections.get());
when(mockCacheServer.getMaximumMessageCount()).thenAnswer(invocation -> maxMessageCount.get());
when(mockCacheServer.getMaxThreads()).thenAnswer(invocation -> maxThreads.get());
when(mockCacheServer.getMaximumTimeBetweenPings()).thenAnswer(invocation -> maxTimeBetweenPings.get());
when(mockCacheServer.getMessageTimeToLive()).thenAnswer(invocation -> messageTimeToLive.get());
when(mockCacheServer.getPort()).thenAnswer(invocation -> port.get());
when(mockCacheServer.getSocketBufferSize()).thenAnswer(invocation -> socketBufferSize.get());
when(mockCacheServer.getTcpNoDelay()).thenAnswer(invocation -> tcpNoDelay.get());
when(mockCacheServer.getBindAddress()).thenAnswer(newGetter(bindAddress));
when(mockCacheServer.getHostnameForClients()).thenAnswer(newGetter(hostnameForClients));
when(mockCacheServer.getLoadPollInterval()).thenAnswer(newGetter(loadPollInterval));
when(mockCacheServer.getMaxConnections()).thenAnswer(newGetter(maxConnections));
when(mockCacheServer.getMaximumMessageCount()).thenAnswer(newGetter(maxMessageCount));
when(mockCacheServer.getMaxThreads()).thenAnswer(newGetter(maxThreads));
when(mockCacheServer.getMaximumTimeBetweenPings()).thenAnswer(newGetter(maxTimeBetweenPings));
when(mockCacheServer.getMessageTimeToLive()).thenAnswer(newGetter(messageTimeToLive));
when(mockCacheServer.getPort()).thenAnswer(newGetter(port));
when(mockCacheServer.getSocketBufferSize()).thenAnswer(newGetter(socketBufferSize));
when(mockCacheServer.getTcpNoDelay()).thenAnswer(newGetter(tcpNoDelay));
ClientSubscriptionConfig mockClientSubsriptionConfig = mockClientSubscriptionConfig();
@@ -368,26 +331,25 @@ public abstract class MockGemFireObjectsSupport {
AtomicReference<SubscriptionEvictionPolicy> subscriptionEvictionPolicy =
new AtomicReference<>(SubscriptionEvictionPolicy.DEFAULT);
doAnswer(invocation -> {
subscriptionCapacity.set(invocation.getArgument(0));
return null;
}).when(mockClientSubscriptionConfig).setCapacity(anyInt());
Function<String, SubscriptionEvictionPolicy> stringToSubscriptionEvictionPolicyConverter =
arg -> SubscriptionEvictionPolicy.valueOfIgnoreCase(String.valueOf(arg));
doAnswer(invocation -> {
subscriptionDiskStoreName.set(invocation.getArgument(0));
return null;
}).when(mockClientSubscriptionConfig).setDiskStoreName(anyString());
Function<SubscriptionEvictionPolicy, String> subscriptionEvictionPolicyToStringConverter =
arg -> Optional.ofNullable(arg).map(Object::toString).map(String::toLowerCase).orElse(null);
doAnswer(invocation -> {
subscriptionEvictionPolicy.set(SubscriptionEvictionPolicy.valueOfIgnoreCase(invocation.getArgument(0)));
return null;
}).when(mockClientSubscriptionConfig).setEvictionPolicy(anyString());
doAnswer(newSetter(subscriptionCapacity, null))
.when(mockClientSubscriptionConfig).setCapacity(anyInt());
when(mockClientSubscriptionConfig.getCapacity()).thenAnswer(invocation -> subscriptionCapacity.get());
when(mockClientSubscriptionConfig.getDiskStoreName()).thenAnswer(invocation -> subscriptionDiskStoreName.get());
when(mockClientSubscriptionConfig.getEvictionPolicy()).thenAnswer(invocation ->
Optional.ofNullable(subscriptionEvictionPolicy.get()).map(Object::toString).map(String::toLowerCase)
.orElse(null));
doAnswer(newSetter(subscriptionDiskStoreName, null))
.when(mockClientSubscriptionConfig).setDiskStoreName(anyString());
doAnswer(newSetter(subscriptionEvictionPolicy, stringToSubscriptionEvictionPolicyConverter, null))
.when(mockClientSubscriptionConfig).setEvictionPolicy(anyString());
when(mockClientSubscriptionConfig.getCapacity()).thenAnswer(newGetter(subscriptionCapacity));
when(mockClientSubscriptionConfig.getDiskStoreName()).thenAnswer(newGetter(subscriptionDiskStoreName));
when(mockClientSubscriptionConfig.getEvictionPolicy()).thenAnswer(newGetter(subscriptionEvictionPolicy,
subscriptionEvictionPolicyToStringConverter));
return mockClientSubscriptionConfig;
}
@@ -417,20 +379,14 @@ public abstract class MockGemFireObjectsSupport {
AtomicReference<Float> diskUsageWarningPercentage =
new AtomicReference<>(DiskStoreFactory.DEFAULT_DISK_USAGE_WARNING_PERCENTAGE);
when(mockDiskStoreFactory.setAllowForceCompaction(anyBoolean())).thenAnswer(invocation -> {
allowForceCompaction.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setAllowForceCompaction(anyBoolean()))
.thenAnswer(newSetter(allowForceCompaction, mockDiskStoreFactory));
when(mockDiskStoreFactory.setAutoCompact(anyBoolean())).thenAnswer(invocation -> {
autoCompact.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setAutoCompact(anyBoolean()))
.thenAnswer(newSetter(autoCompact, mockDiskStoreFactory));
when(mockDiskStoreFactory.setCompactionThreshold(anyInt())).thenAnswer(invocation -> {
compactionThreshold.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setCompactionThreshold(anyInt()))
.thenAnswer(newSetter(compactionThreshold, mockDiskStoreFactory));
when(mockDiskStoreFactory.setDiskDirs(any(File[].class))).thenAnswer(invocation -> {
@@ -454,35 +410,23 @@ public abstract class MockGemFireObjectsSupport {
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setDiskUsageCriticalPercentage(anyFloat())).thenAnswer(invocation -> {
diskUsageCriticalPercentage.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setDiskUsageCriticalPercentage(anyFloat()))
.thenAnswer(newSetter(diskUsageCriticalPercentage, mockDiskStoreFactory));
when(mockDiskStoreFactory.setDiskUsageWarningPercentage(anyFloat())).thenAnswer(invocation -> {
diskUsageWarningPercentage.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setDiskUsageWarningPercentage(anyFloat()))
.thenAnswer(newSetter(diskUsageWarningPercentage, mockDiskStoreFactory));
when(mockDiskStoreFactory.setMaxOplogSize(anyLong())).thenAnswer(invocation -> {
maxOplogSize.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setMaxOplogSize(anyLong()))
.thenAnswer(newSetter(maxOplogSize, mockDiskStoreFactory));
when(mockDiskStoreFactory.setQueueSize(anyInt())).thenAnswer(invocation -> {
queueSize.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setQueueSize(anyInt()))
.thenAnswer(newSetter(queueSize, mockDiskStoreFactory));
when(mockDiskStoreFactory.setTimeInterval(anyLong())).thenAnswer(invocation -> {
timeInterval.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setTimeInterval(anyLong()))
.thenAnswer(newSetter(timeInterval, mockDiskStoreFactory));
when(mockDiskStoreFactory.setWriteBufferSize(anyInt())).thenAnswer(invocation -> {
writeBufferSize.set(invocation.getArgument(0));
return mockDiskStoreFactory;
});
when(mockDiskStoreFactory.setWriteBufferSize(anyInt()))
.thenAnswer(newSetter(writeBufferSize, mockDiskStoreFactory));
when(mockDiskStoreFactory.create(anyString())).thenAnswer(invocation -> {
@@ -561,95 +505,59 @@ public abstract class MockGemFireObjectsSupport {
return mockPoolFactory;
});
when(mockPoolFactory.setFreeConnectionTimeout(anyInt())).thenAnswer(invocation -> {
freeConnectionTimeout.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setFreeConnectionTimeout(anyInt()))
.thenAnswer(newSetter(freeConnectionTimeout, mockPoolFactory));
when(mockPoolFactory.setIdleTimeout(anyLong())).thenAnswer(invocation -> {
idleTimeout.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setIdleTimeout(anyLong()))
.thenAnswer(newSetter(idleTimeout, mockPoolFactory));
when(mockPoolFactory.setLoadConditioningInterval(anyInt())).thenAnswer(invocation -> {
loadConditioningInterval.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setLoadConditioningInterval(anyInt()))
.thenAnswer(newSetter(loadConditioningInterval, mockPoolFactory));
when(mockPoolFactory.setMaxConnections(anyInt())).thenAnswer(invocation -> {
maxConnections.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setMaxConnections(anyInt()))
.thenAnswer(newSetter(maxConnections, mockPoolFactory));
when(mockPoolFactory.setMinConnections(anyInt())).thenAnswer(invocation -> {
minConnections.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setMinConnections(anyInt()))
.thenAnswer(newSetter(minConnections, mockPoolFactory));
when(mockPoolFactory.setMultiuserAuthentication(anyBoolean())).thenAnswer(invocation -> {
multiuserAuthentication.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setMultiuserAuthentication(anyBoolean()))
.thenAnswer(newSetter(multiuserAuthentication, mockPoolFactory));
when(mockPoolFactory.setPingInterval(anyLong())).thenAnswer(invocation -> {
pingInterval.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setPingInterval(anyLong()))
.thenAnswer(newSetter(pingInterval, mockPoolFactory));
when(mockPoolFactory.setPRSingleHopEnabled(anyBoolean())).thenAnswer(invocation -> {
prSingleHopEnabled.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setPRSingleHopEnabled(anyBoolean()))
.thenAnswer(newSetter(prSingleHopEnabled, mockPoolFactory));
when(mockPoolFactory.setReadTimeout(anyInt())).thenAnswer(invocation -> {
readTimeout.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setReadTimeout(anyInt()))
.thenAnswer(newSetter(readTimeout, mockPoolFactory));
when(mockPoolFactory.setRetryAttempts(anyInt())).thenAnswer(invocation -> {
retryAttempts.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setRetryAttempts(anyInt()))
.thenAnswer(newSetter(retryAttempts, mockPoolFactory));
when(mockPoolFactory.setServerGroup(anyString())).thenAnswer(invocation -> {
serverGroup.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setServerGroup(anyString()))
.thenAnswer(newSetter(serverGroup, mockPoolFactory));
when(mockPoolFactory.setSocketBufferSize(anyInt())).thenAnswer(invocation -> {
socketBufferSize.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setSocketBufferSize(anyInt()))
.thenAnswer(newSetter(socketBufferSize, mockPoolFactory));
when(mockPoolFactory.setStatisticInterval(anyInt())).thenAnswer(invocation -> {
statisticInterval.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setStatisticInterval(anyInt()))
.thenAnswer(newSetter(statisticInterval, mockPoolFactory));
when(mockPoolFactory.setSubscriptionAckInterval(anyInt())).thenAnswer(invocation -> {
subscriptionAckInterval.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setSubscriptionAckInterval(anyInt()))
.thenAnswer(newSetter(subscriptionAckInterval, mockPoolFactory));
when(mockPoolFactory.setSubscriptionEnabled(anyBoolean())).thenAnswer(invocation -> {
subscriptionEnabled.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setSubscriptionEnabled(anyBoolean()))
.thenAnswer(newSetter(subscriptionEnabled, mockPoolFactory));
when(mockPoolFactory.setSubscriptionMessageTrackingTimeout(anyInt())).thenAnswer(invocation -> {
subscriptionMessageTrackingTimeout.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setSubscriptionMessageTrackingTimeout(anyInt()))
.thenAnswer(newSetter(subscriptionMessageTrackingTimeout, mockPoolFactory));
when(mockPoolFactory.setSubscriptionRedundancy(anyInt())).thenAnswer(invocation -> {
subscriptionRedundancy.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setSubscriptionRedundancy(anyInt()))
.thenAnswer(newSetter(subscriptionRedundancy, mockPoolFactory));
when(mockPoolFactory.setThreadLocalConnections(anyBoolean())).thenAnswer(invocation -> {
threadLocalConnections.set(invocation.getArgument(0));
return mockPoolFactory;
});
when(mockPoolFactory.setThreadLocalConnections(anyBoolean()))
.thenAnswer(newSetter(threadLocalConnections, mockPoolFactory));
when(mockPoolFactory.create(anyString())).thenAnswer(invocation -> {
@@ -669,7 +577,7 @@ public abstract class MockGemFireObjectsSupport {
return null;
}).when(mockPool).destroy(anyBoolean());
when(mockPool.isDestroyed()).thenAnswer(invocationOnMock -> destroyed.get());
when(mockPool.isDestroyed()).thenAnswer(newGetter(destroyed));
when(mockPool.getFreeConnectionTimeout()).thenReturn(freeConnectionTimeout.get());
when(mockPool.getIdleTimeout()).thenReturn(idleTimeout.get());
when(mockPool.getLoadConditioningInterval()).thenReturn(loadConditioningInterval.get());
@@ -715,30 +623,22 @@ public abstract class MockGemFireObjectsSupport {
AtomicReference<Float> evictionOffHeapPercentage =
new AtomicReference<>(ResourceManager.DEFAULT_EVICTION_PERCENTAGE);
doAnswer(invocation -> {
criticalHeapPercentage.set(invocation.getArgument(0));
return null;
}).when(mockResourceManager).setCriticalHeapPercentage(anyFloat());
doAnswer(newSetter(criticalHeapPercentage, null))
.when(mockResourceManager).setCriticalHeapPercentage(anyFloat());
doAnswer(invocation -> {
criticalOffHeapPercentage.set(invocation.getArgument(0));
return null;
}).when(mockResourceManager).setCriticalOffHeapPercentage(anyFloat());
doAnswer(newSetter(criticalOffHeapPercentage, null))
.when(mockResourceManager).setCriticalOffHeapPercentage(anyFloat());
doAnswer(invocation -> {
evictionHeapPercentage.set(invocation.getArgument(0));
return null;
}).when(mockResourceManager).setEvictionHeapPercentage(anyFloat());
doAnswer(newSetter(evictionHeapPercentage, null))
.when(mockResourceManager).setEvictionHeapPercentage(anyFloat());
doAnswer(invocation -> {
evictionOffHeapPercentage.set(invocation.getArgument(0));
return null;
}).when(mockResourceManager).setEvictionOffHeapPercentage(anyFloat());
doAnswer(newSetter(evictionOffHeapPercentage, null))
.when(mockResourceManager).setEvictionOffHeapPercentage(anyFloat());
when(mockResourceManager.getCriticalHeapPercentage()).thenAnswer(invocation -> criticalHeapPercentage.get());
when(mockResourceManager.getCriticalOffHeapPercentage()).thenAnswer(invocation -> criticalOffHeapPercentage.get());
when(mockResourceManager.getEvictionHeapPercentage()).thenAnswer(invocation -> evictionHeapPercentage.get());
when(mockResourceManager.getEvictionOffHeapPercentage()).thenAnswer(invocation -> evictionOffHeapPercentage.get());
when(mockResourceManager.getCriticalHeapPercentage()).thenAnswer(newGetter(criticalHeapPercentage));
when(mockResourceManager.getCriticalOffHeapPercentage()).thenAnswer(newGetter(criticalOffHeapPercentage));
when(mockResourceManager.getEvictionHeapPercentage()).thenAnswer(newGetter(evictionHeapPercentage));
when(mockResourceManager.getEvictionOffHeapPercentage()).thenAnswer(newGetter(evictionOffHeapPercentage));
when(mockResourceManager.getRebalanceOperations()).thenReturn(Collections.emptySet());
return mockResourceManager;
@@ -757,38 +657,28 @@ public abstract class MockGemFireObjectsSupport {
AtomicReference<String> pdxDiskStoreName = new AtomicReference<>(null);
AtomicReference<PdxSerializer> pdxSerializer = new AtomicReference<>(null);
doAnswer(invocation -> {
pdxDiskStoreName.set(invocation.getArgument(0));
return cacheFactorySpy;
}).when(cacheFactorySpy.setPdxDiskStore(anyString()));
doAnswer(newSetter(pdxDiskStoreName, cacheFactorySpy))
.when(cacheFactorySpy).setPdxDiskStore(anyString());
doAnswer(invocation -> {
pdxIgnoreUnreadFields.set(invocation.getArgument(0));
return cacheFactorySpy;
}).when(cacheFactorySpy.setPdxIgnoreUnreadFields(anyBoolean()));
doAnswer(newSetter(pdxIgnoreUnreadFields, cacheFactorySpy))
.when(cacheFactorySpy).setPdxIgnoreUnreadFields(anyBoolean());
doAnswer(invocation -> {
pdxPersistent.set(invocation.getArgument(0));
return cacheFactorySpy;
}).when(cacheFactorySpy.setPdxPersistent(anyBoolean()));
doAnswer(newSetter(pdxPersistent, cacheFactorySpy))
.when(cacheFactorySpy).setPdxPersistent(anyBoolean());
doAnswer(invocation -> {
pdxReadSerialized.set(invocation.getArgument(0));
return cacheFactorySpy;
}).when(cacheFactorySpy.setPdxReadSerialized(anyBoolean()));
doAnswer(newSetter(pdxReadSerialized, cacheFactorySpy))
.when(cacheFactorySpy).setPdxReadSerialized(anyBoolean());
doAnswer(invocation -> {
pdxSerializer.set(invocation.getArgument(0));
return cacheFactorySpy;
}).when(cacheFactorySpy.setPdxSerializer(any(PdxSerializer.class)));
doAnswer(newSetter(pdxSerializer, cacheFactorySpy))
.when(cacheFactorySpy).setPdxSerializer(any(PdxSerializer.class));
doReturn(mockCache).when(cacheFactorySpy.create());
doReturn(mockCache).when(cacheFactorySpy).create();
when(mockCache.getPdxDiskStore()).thenAnswer(invocation -> pdxDiskStoreName.get());
when(mockCache.getPdxIgnoreUnreadFields()).thenAnswer(invocation -> pdxIgnoreUnreadFields.get());
when(mockCache.getPdxPersistent()).thenAnswer(invocation -> pdxPersistent.get());
when(mockCache.getPdxReadSerialized()).thenAnswer(invocation -> pdxReadSerialized.get());
when(mockCache.getPdxSerializer()).thenAnswer(invocation -> pdxSerializer.get());
when(mockCache.getPdxDiskStore()).thenAnswer(newGetter(pdxDiskStoreName));
when(mockCache.getPdxIgnoreUnreadFields()).thenAnswer(newGetter(pdxIgnoreUnreadFields));
when(mockCache.getPdxPersistent()).thenAnswer(newGetter(pdxPersistent));
when(mockCache.getPdxReadSerialized()).thenAnswer(newGetter(pdxReadSerialized));
when(mockCache.getPdxSerializer()).thenAnswer(newGetter(pdxSerializer));
return cacheFactorySpy;
}
@@ -799,8 +689,6 @@ public abstract class MockGemFireObjectsSupport {
ClientCache mockClientCache = mockClientCache();
PoolFactory mockPoolFactory = mockPoolFactory();
AtomicBoolean pdxIgnoreUnreadFields = new AtomicBoolean(false);
AtomicBoolean pdxPersistent = new AtomicBoolean(false);
AtomicBoolean pdxReadSerialized = new AtomicBoolean(false);
@@ -809,132 +697,124 @@ public abstract class MockGemFireObjectsSupport {
AtomicReference<PdxSerializer> pdxSerializer = new AtomicReference<>(null);
AtomicReference<Pool> defaultPool = new AtomicReference<>(null);
doAnswer(invocation -> {
pdxDiskStoreName.set(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPdxDiskStore(anyString()));
doAnswer(newSetter(pdxDiskStoreName, clientCacheFactorySpy))
.when(clientCacheFactorySpy).setPdxDiskStore(anyString());
doAnswer(invocation -> {
pdxIgnoreUnreadFields.set(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPdxIgnoreUnreadFields(anyBoolean()));
doAnswer(newSetter(pdxIgnoreUnreadFields, clientCacheFactorySpy))
.when(clientCacheFactorySpy).setPdxIgnoreUnreadFields(anyBoolean());
doAnswer(invocation -> {
pdxPersistent.set(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPdxPersistent(anyBoolean()));
doAnswer(newSetter(pdxPersistent, clientCacheFactorySpy))
.when(clientCacheFactorySpy).setPdxPersistent(anyBoolean());
doAnswer(invocation -> {
pdxReadSerialized.set(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPdxReadSerialized(anyBoolean()));
doAnswer(newSetter(pdxReadSerialized, clientCacheFactorySpy))
.when(clientCacheFactorySpy).setPdxReadSerialized(anyBoolean());
doAnswer(invocation -> {
pdxSerializer.set(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPdxSerializer(any(PdxSerializer.class)));
doAnswer(newSetter(pdxSerializer, clientCacheFactorySpy))
.when(clientCacheFactorySpy).setPdxSerializer(any(PdxSerializer.class));
PoolFactory mockPoolFactory = mockPoolFactory();
doAnswer(invocation -> {
mockPoolFactory.addLocator(invocation.getArgument(0), invocation.getArgument(1));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.addPoolLocator(anyString(), anyInt()));
}).when(clientCacheFactorySpy).addPoolLocator(anyString(), anyInt());
doAnswer(invocation -> {
mockPoolFactory.addServer(invocation.getArgument(0), invocation.getArgument(1));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.addPoolServer(anyString(), anyInt()));
}).when(clientCacheFactorySpy).addPoolServer(anyString(), anyInt());
doAnswer(invocation -> {
mockPoolFactory.setFreeConnectionTimeout(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolFreeConnectionTimeout(anyInt()));
}).when(clientCacheFactorySpy).setPoolFreeConnectionTimeout(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setIdleTimeout(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolIdleTimeout(anyLong()));
}).when(clientCacheFactorySpy).setPoolIdleTimeout(anyLong());
doAnswer(invocation -> {
mockPoolFactory.setLoadConditioningInterval(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolLoadConditioningInterval(anyInt()));
}).when(clientCacheFactorySpy).setPoolLoadConditioningInterval(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setMaxConnections(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolMaxConnections(anyInt()));
}).when(clientCacheFactorySpy).setPoolMaxConnections(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setMinConnections(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolMinConnections(anyInt()));
}).when(clientCacheFactorySpy).setPoolMinConnections(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setMultiuserAuthentication(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolMultiuserAuthentication(anyBoolean()));
}).when(clientCacheFactorySpy).setPoolMultiuserAuthentication(anyBoolean());
doAnswer(invocation -> {
mockPoolFactory.setPingInterval(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolPingInterval(anyLong()));
}).when(clientCacheFactorySpy).setPoolPingInterval(anyLong());
doAnswer(invocation -> {
mockPoolFactory.setPRSingleHopEnabled(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolPRSingleHopEnabled(anyBoolean()));
}).when(clientCacheFactorySpy).setPoolPRSingleHopEnabled(anyBoolean());
doAnswer(invocation -> {
mockPoolFactory.setReadTimeout(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolReadTimeout(anyInt()));
}).when(clientCacheFactorySpy).setPoolReadTimeout(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setRetryAttempts(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolRetryAttempts(anyInt()));
}).when(clientCacheFactorySpy).setPoolRetryAttempts(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setServerGroup(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolServerGroup(anyString()));
}).when(clientCacheFactorySpy).setPoolServerGroup(anyString());
doAnswer(invocation -> {
mockPoolFactory.setSocketBufferSize(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolSocketBufferSize(anyInt()));
}).when(clientCacheFactorySpy).setPoolSocketBufferSize(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setStatisticInterval(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolStatisticInterval(anyInt()));
}).when(clientCacheFactorySpy).setPoolStatisticInterval(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setSubscriptionAckInterval(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolSubscriptionAckInterval(anyInt()));
}).when(clientCacheFactorySpy).setPoolSubscriptionAckInterval(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setSubscriptionEnabled(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolSubscriptionEnabled(anyBoolean()));
}).when(clientCacheFactorySpy).setPoolSubscriptionEnabled(anyBoolean());
doAnswer(invocation -> {
mockPoolFactory.setSubscriptionMessageTrackingTimeout(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolSubscriptionMessageTrackingTimeout(anyInt()));
}).when(clientCacheFactorySpy).setPoolSubscriptionMessageTrackingTimeout(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setSubscriptionRedundancy(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolSubscriptionRedundancy(anyInt()));
}).when(clientCacheFactorySpy).setPoolSubscriptionRedundancy(anyInt());
doAnswer(invocation -> {
mockPoolFactory.setThreadLocalConnections(invocation.getArgument(0));
return clientCacheFactorySpy;
}).when(clientCacheFactorySpy.setPoolThreadLocalConnections(anyBoolean()));
}).when(clientCacheFactorySpy).setPoolThreadLocalConnections(anyBoolean());
doReturn(mockClientCache).when(clientCacheFactorySpy.create());
doReturn(mockClientCache).when(clientCacheFactorySpy).create();
when(mockClientCache.getCurrentServers()).thenAnswer(invocation ->
Collections.unmodifiableSet(new HashSet<>(defaultPool.get().getServers())));
@@ -948,11 +828,11 @@ public abstract class MockGemFireObjectsSupport {
return defaultPool.get();
});
when(mockClientCache.getPdxDiskStore()).thenAnswer(invocation -> pdxDiskStoreName.get());
when(mockClientCache.getPdxIgnoreUnreadFields()).thenAnswer(invocation -> pdxIgnoreUnreadFields.get());
when(mockClientCache.getPdxPersistent()).thenAnswer(invocation -> pdxPersistent.get());
when(mockClientCache.getPdxReadSerialized()).thenAnswer(invocation -> pdxReadSerialized.get());
when(mockClientCache.getPdxSerializer()).thenAnswer(invocation -> pdxSerializer.get());
when(mockClientCache.getPdxDiskStore()).thenAnswer(newGetter(pdxDiskStoreName));
when(mockClientCache.getPdxIgnoreUnreadFields()).thenAnswer(newGetter(pdxIgnoreUnreadFields));
when(mockClientCache.getPdxPersistent()).thenAnswer(newGetter(pdxPersistent));
when(mockClientCache.getPdxReadSerialized()).thenAnswer(newGetter(pdxReadSerialized));
when(mockClientCache.getPdxSerializer()).thenAnswer(newGetter(pdxSerializer));
return clientCacheFactorySpy;
}

View File

@@ -0,0 +1,142 @@
/*
* 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 org.springframework.data.gemfire.test.mock;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.mockito.stubbing.Answer;
/**
* The {@link MockObjectsSupport} class is an abstract base class encapsulating common operations and utilities
* used in mocking using Mockito.
*
* @author John Blum
* @since 2.0.0
*/
@SuppressWarnings("unused")
public abstract class MockObjectsSupport {
/* (non-Javadoc) */
protected static Answer<Boolean> newGetter(AtomicBoolean returnValue) {
return invocation -> returnValue.get();
}
/* (non-Javadoc) */
protected static Answer<Integer> newGetter(AtomicInteger returnValue) {
return invocation -> returnValue.get();
}
/* (non-Javadoc) */
protected static Answer<Long> newGetter(AtomicLong returnValue) {
return invocation -> returnValue.get();
}
/* (non-Javadoc) */
protected static <R> Answer<R> newGetter(AtomicReference<R> returnValue) {
return invocation -> returnValue.get();
}
/* (non-Javadoc) */
protected static <R, S> Answer<S> newGetter(AtomicReference<R> returnValue, Function<R, S> converter) {
return invocation -> converter.apply(returnValue.get());
}
/* (non-Javadoc) */
protected static <R> Answer<R> newSetter(AtomicBoolean argument, R returnValue) {
return invocation -> {
argument.set(invocation.getArgument(0));
return returnValue;
};
}
/* (non-Javadoc) */
protected static <R> Answer<R> newSetter(AtomicBoolean argument, Boolean value, R returnValue) {
return invocation -> {
argument.set(value);
return returnValue;
};
}
/* (non-Javadoc) */
protected static <R> Answer<R> newSetter(AtomicInteger argument, R returnValue) {
return invocation -> {
argument.set(invocation.getArgument(0));
return returnValue;
};
}
/* (non-Javadoc) */
protected static <R> Answer<R> newSetter(AtomicInteger argument, Integer value, R returnValue) {
return invocation -> {
argument.set(value);
return returnValue;
};
}
/* (non-Javadoc) */
protected static <R> Answer<R> newSetter(AtomicLong argument, R returnValue) {
return invocation -> {
argument.set(invocation.getArgument(0));
return returnValue;
};
}
/* (non-Javadoc) */
protected static <R> Answer<R> newSetter(AtomicLong argument, Long value, R returnValue) {
return invocation -> {
argument.set(value);
return returnValue;
};
}
/* (non-Javadoc) */
protected static <T, R> Answer<R> newSetter(AtomicReference<T> argument, R returnValue) {
return invocation -> {
argument.set(invocation.getArgument(0));
return returnValue;
};
}
/* (non-Javadoc) */
protected static <T, R> Answer<R> newSetter(AtomicReference<T> argument, T value, R returnValue) {
return invocation -> {
argument.set(value);
return returnValue;
};
}
/* (non-Javadoc) */
protected static <T, R> Answer<R> newSetter(AtomicReference<T> argument, Function<?, T> converter, R returnValue) {
return invocation -> {
argument.set(converter.apply(invocation.getArgument(0)));
return returnValue;
};
}
/* (non-Javadoc) */
protected static <K, V, R> Answer<R> newSetter(Map<K, V> argument, R returnValue) {
return invocation -> {
argument.put(invocation.getArgument(0), invocation.getArgument(1));
return returnValue;
};
}
}