SGF-146 - improved test performance

This commit is contained in:
David Turanski
2013-01-07 18:38:04 -05:00
parent 2edbbff5ed
commit 7e96988184
58 changed files with 3989 additions and 600 deletions

View File

@@ -40,17 +40,16 @@ import org.springframework.util.CollectionUtils;
import com.gemstone.gemfire.GemFireCheckedException;
import com.gemstone.gemfire.GemFireException;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.GemFireCache;
import com.gemstone.gemfire.cache.CacheClosedException;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.CacheTransactionManager;
import com.gemstone.gemfire.cache.DynamicRegionFactory;
import com.gemstone.gemfire.cache.GemFireCache;
import com.gemstone.gemfire.cache.TransactionListener;
import com.gemstone.gemfire.cache.TransactionWriter;
import com.gemstone.gemfire.cache.util.GatewayConflictResolver;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.datasource.ConfigProperty;
import com.gemstone.gemfire.internal.jndi.JNDIInvoker;
import com.gemstone.gemfire.pdx.PdxSerializable;
@@ -74,7 +73,8 @@ import com.gemstone.gemfire.pdx.PdxSerializer;
* @author David Turanski
*/
public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanClassLoaderAware, DisposableBean,
FactoryBean<GemFireCache>, PersistenceExceptionTranslator {
FactoryBean<Cache>, PersistenceExceptionTranslator {
/**
* Inner class to avoid a hard dependency on the GemFire 6.6 API.
*
@@ -110,34 +110,6 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
}
}
private class InternalCacheOptions implements Runnable {
private final GemFireCacheImpl cacheImpl;
InternalCacheOptions(GemFireCache cache) {
this.cacheImpl = (GemFireCacheImpl) cache;
}
@Override
public void run() {
if (lockLease != null) {
cacheImpl.setLockLease(lockLease);
}
if (lockTimeout != null) {
cacheImpl.setLockTimeout(lockTimeout);
}
if (searchTimeout != null) {
cacheImpl.setSearchTimeout(searchTimeout);
}
if (messageSyncInterval != null) {
cacheImpl.setMessageSyncInterval(messageSyncInterval);
}
if (gatewayConflictResolver != null) {
cacheImpl.setGatewayConflictResolver((GatewayConflictResolver) gatewayConflictResolver);
}
}
}
public static class DynamicRegionSupport {
private String diskDir;
@@ -214,7 +186,7 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
protected final Log log = LogFactory.getLog(getClass());
protected GemFireCache cache;
protected Cache cache;
protected Resource cacheXml;
@@ -283,7 +255,7 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
// first look for open caches
String msg = null;
try {
cache = fetchCache();
cache =(Cache)fetchCache();
msg = "Retrieved existing";
} catch (CacheClosedException ex) {
@@ -300,14 +272,29 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
}
// fall back to cache creation
cache = createCache(factory);
cache = (Cache)createCache(factory);
msg = "Created";
}
if (this.copyOnRead != null) {
cache.setCopyOnRead(this.copyOnRead);
}
if (lockLease != null) {
cache.setLockLease(lockLease);
}
if (lockTimeout != null) {
cache.setLockTimeout(lockTimeout);
}
if (searchTimeout != null) {
cache.setSearchTimeout(searchTimeout);
}
if (messageSyncInterval != null) {
cache.setMessageSyncInterval(messageSyncInterval);
}
applyInternalCacheOptions();
if (gatewayConflictResolver != null) {
cache.setGatewayConflictResolver((GatewayConflictResolver) gatewayConflictResolver);
}
DistributedSystem system = cache.getDistributedSystem();
DistributedMember member = system.getDistributedMember();
@@ -402,21 +389,17 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
new PdxOptions((CacheFactory) factory).run();
}
}
protected void applyInternalCacheOptions() {
new InternalCacheOptions(cache).run();
}
protected Object createFactory(Properties props) {
return new CacheFactory(props);
}
protected GemFireCache fetchCache() {
return CacheFactory.getAnyInstance();
return (cache == null)? CacheFactory.getAnyInstance(): cache;
}
protected GemFireCache createCache(Object factory) {
return ((CacheFactory) factory).create();
return (cache == null)? ((CacheFactory) factory).create() : cache;
}
@Override
@@ -456,13 +439,13 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
}
@Override
public GemFireCache getObject() throws Exception {
public Cache getObject() throws Exception {
init();
return cache;
}
@Override
public Class<? extends GemFireCache> getObjectType() {
public Class<? extends Cache> getObjectType() {
return (cache != null ? cache.getClass() : Cache.class);
}
@@ -571,7 +554,7 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
/**
* @return the beanFactory
*/
protected BeanFactory getBeanFactory() {
public BeanFactory getBeanFactory() {
return beanFactory;
}
@@ -579,7 +562,7 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
*
* @param copyOnRead
*/
public void setCopyOnRead(boolean copyOnRead) {
public void setCopyOnRead(Boolean copyOnRead) {
this.copyOnRead = copyOnRead;
}
@@ -587,7 +570,7 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
*
* @param lockTimeout
*/
public void setLockTimeout(int lockTimeout) {
public void setLockTimeout(Integer lockTimeout) {
this.lockTimeout = lockTimeout;
}
@@ -595,7 +578,7 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
*
* @param lockLease
*/
public void setLockLease(int lockLease) {
public void setLockLease(Integer lockLease) {
this.lockLease = lockLease;
}
@@ -603,7 +586,7 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
*
* @param messageSyncInterval
*/
public void setMessageSyncInterval(int messageSyncInterval) {
public void setMessageSyncInterval(Integer messageSyncInterval) {
this.messageSyncInterval = messageSyncInterval;
}
@@ -611,7 +594,7 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
*
* @param searchTimeout
*/
public void setSearchTimeout(int searchTimeout) {
public void setSearchTimeout(Integer searchTimeout) {
this.searchTimeout = searchTimeout;
}
@@ -673,4 +656,154 @@ public class CacheFactoryBean implements BeanNameAware, BeanFactoryAware, BeanCl
this.jndiDataSources = jndiDataSources;
}
/**
* @return the cacheXml
*/
public Resource getCacheXml() {
return cacheXml;
}
/**
* @return the properties
*/
public Properties getProperties() {
return properties;
}
/**
* @return the beanClassLoader
*/
public ClassLoader getBeanClassLoader() {
return beanClassLoader;
}
/**
* @return the beanName
*/
public String getBeanName() {
return beanName;
}
/**
* @return the pdxSerializer
*/
public Object getPdxSerializer() {
return pdxSerializer;
}
/**
* @return the pdxPersistent
*/
public Boolean getPdxPersistent() {
return pdxPersistent;
}
/**
* @return the pdxReadSerialized
*/
public Boolean getPdxReadSerialized() {
return pdxReadSerialized;
}
/**
* @return the pdxIgnoreUnreadFields
*/
public Boolean getPdxIgnoreUnreadFields() {
return pdxIgnoreUnreadFields;
}
/**
* @return the pdxDiskStoreName
*/
public String getPdxDiskStoreName() {
return pdxDiskStoreName;
}
/**
* @return the copyOnRead
*/
public Boolean getCopyOnRead() {
return copyOnRead;
}
/**
* @return the lockTimeout
*/
public Integer getLockTimeout() {
return lockTimeout;
}
/**
* @return the lockLease
*/
public Integer getLockLease() {
return lockLease;
}
/**
* @return the messageSyncInterval
*/
public Integer getMessageSyncInterval() {
return messageSyncInterval;
}
/**
* @return the searchTimeout
*/
public Integer getSearchTimeout() {
return searchTimeout;
}
/**
* @return the transactionListeners
*/
public List<TransactionListener> getTransactionListeners() {
return transactionListeners;
}
/**
* @return the transactionWriter
*/
public TransactionWriter getTransactionWriter() {
return transactionWriter;
}
/**
* @return the evictionHeapPercentage
*/
public Float getEvictionHeapPercentage() {
return evictionHeapPercentage;
}
/**
* @return the criticalHeapPercentage
*/
public Float getCriticalHeapPercentage() {
return criticalHeapPercentage;
}
/**
* @return the dynamicRegionSupport
*/
public DynamicRegionSupport getDynamicRegionSupport() {
return dynamicRegionSupport;
}
/**
* @return the jndiDataSources
*/
public List<JndiDataSource> getJndiDataSources() {
return jndiDataSources;
}
/**
* @return the gatewayConflictResolver
*/
public Object getGatewayConflictResolver() {
return gatewayConflictResolver;
}
public GemfireBeanFactoryLocator getBeanFactoryLocator() {
return factoryLocator;
}
}

View File

@@ -113,6 +113,7 @@ public class DiskStoreFactoryBean implements FactoryBean<DiskStore>, Initializin
}
diskStore = diskStoreFactory.create(name == null ? DiskStoreFactory.DEFAULT_DISK_STORE_NAME : name);
Assert.notNull(diskStore);
}
public void setCache(GemFireCache cache) {

View File

@@ -255,8 +255,8 @@ public class GemfireTemplate extends GemfireAccessor {
public SelectResults<E> doInGemfire(Region region) throws GemFireCheckedException, GemFireException {
QueryService queryService = lookupQueryService(region);
Query q = queryService.newQuery(query);
Object result = q.execute(params);
if (result instanceof SelectResults) {
Object result = q.execute(params);
if (result instanceof SelectResults) {
return (SelectResults<E>) result;
}
throw new InvalidDataAccessApiUsageException(
@@ -310,7 +310,6 @@ public class GemfireTemplate extends GemfireAccessor {
&& Scope.LOCAL.equals(region.getAttributes().getScope())) {
return ((ClientCache) region.getRegionService()).getLocalQueryService();
}
return region.getRegionService().getQueryService();
}

View File

@@ -114,7 +114,7 @@ public class RegionFactoryBean<K, V> extends RegionLookupFactoryBean<K, V> imple
AttributesFactory.validateAttributes(attributes);
final RegionFactory<K, V> regionFactory = (attributes != null ? c.createRegionFactory(attributes) : c
.<K, V> createRegionFactory());
.<K, V> createRegionFactory());
if (hubId != null) {
enableGateway = enableGateway == null ? true : enableGateway;

View File

@@ -96,7 +96,7 @@ public class ClientCacheFactoryBean extends CacheFactoryBean {
return ClientCacheFactory.getAnyInstance();
}
Properties getProperties() {
public Properties getProperties() {
return this.properties;
}

View File

@@ -0,0 +1,25 @@
/*
* Copyright 2002-2012 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;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
/**
* @author David Turanski
*
*/
class ContextLoaderUtils {
static void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new GemfireTestBeanPostProcessor());
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2002-2012 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;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
/**
* @author David Turanski
*
*/
public class GemfireAnnotationConfigContextLoader extends AnnotationConfigContextLoader {
@Override
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
ContextLoaderUtils.customizeBeanFactory(beanFactory);
}
}

View File

@@ -0,0 +1,277 @@
/*
* Copyright 2002-2012 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;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.SmartContextLoader;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.DelegatingSmartContextLoader;
import org.springframework.test.context.support.GenericXmlContextLoader;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* @author David Turanski
*
*/
/*
* Copyright 2002-2011 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.
*/
/**
* {@code DelegatingSmartContextLoader} is an implementation of the {@link SmartContextLoader}
* SPI that delegates to a set of <em>candidate</em> SmartContextLoaders (i.e.,
* {@link GenericXmlContextLoader} and {@link AnnotationConfigContextLoader}) to
* determine which context loader is appropriate for a given test class<73>s configuration.
* Each candidate is given a chance to {@link #processContextConfiguration process} the
* {@link ContextConfigurationAttributes} for each class in the test class hierarchy that
* is annotated with {@link ContextConfiguration @ContextConfiguration}, and the candidate
* that supports the merged, processed configuration will be used to actually
* {@link #loadContext load} the context.
*
* <p>Placing an empty {@code @ContextConfiguration} annotation on a test class signals
* that default resource locations (i.e., XML configuration files) or default
* {@link org.springframework.context.annotation.Configuration configuration classes}
* should be detected. Furthermore, if a specific {@link ContextLoader} or
* {@link SmartContextLoader} is not explicitly declared via
* {@code @ContextConfiguration}, {@code DelegatingSmartContextLoader} will be used as
* the default loader, thus providing automatic support for either XML configuration
* files or configuration classes, but not both simultaneously.
*
* @author Sam Brannen
* @author David Turanski
* Replaces {@link DelegatingSmartContextLoader}
*/
public class GemfireSmartContextLoader implements SmartContextLoader {
private static final Log logger = LogFactory.getLog(GemfireSmartContextLoader.class);
private final SmartContextLoader xmlLoader = new GemfireXmlContextLoader();
private final SmartContextLoader annotationConfigLoader = new GemfireAnnotationConfigContextLoader();
// --- SmartContextLoader --------------------------------------------------
private static String name(SmartContextLoader loader) {
return loader.getClass().getSimpleName();
}
private static void delegateProcessing(SmartContextLoader loader, ContextConfigurationAttributes configAttributes) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Delegating to %s to process context configuration %s.", name(loader),
configAttributes));
}
loader.processContextConfiguration(configAttributes);
}
private static boolean supports(SmartContextLoader loader, MergedContextConfiguration mergedConfig) {
if (loader instanceof GemfireAnnotationConfigContextLoader) {
return ObjectUtils.isEmpty(mergedConfig.getLocations()) && !ObjectUtils.isEmpty(mergedConfig.getClasses());
}
else {
return !ObjectUtils.isEmpty(mergedConfig.getLocations()) && ObjectUtils.isEmpty(mergedConfig.getClasses());
}
}
/**
* Delegates to candidate {@code SmartContextLoaders} to process the supplied
* {@link ContextConfigurationAttributes}.
*
* <p>Delegation is based on explicit knowledge of the implementations of
* {@link GenericXmlContextLoader} and {@link AnnotationConfigContextLoader}.
* Specifically, the delegation algorithm is as follows:
*
* <ul>
* <li>If the resource locations or configuration classes in the supplied
* {@code ContextConfigurationAttributes} are not empty, the appropriate
* candidate loader will be allowed to process the configuration <em>as is</em>,
* without any checks for detection of defaults.</li>
* <li>Otherwise, {@code GenericXmlContextLoader} will be allowed to process
* the configuration in order to detect default resource locations. If
* {@code GenericXmlContextLoader} detects default resource locations,
* an {@code info} message will be logged.</li>
* <li>Subsequently, {@code AnnotationConfigContextLoader} will be allowed to
* process the configuration in order to detect default configuration classes.
* If {@code AnnotationConfigContextLoader} detects default configuration
* classes, an {@code info} message will be logged.</li>
* </ul>
*
* @param configAttributes the context configuration attributes to process
* @throws IllegalArgumentException if the supplied configuration attributes are
* <code>null</code>, or if the supplied configuration attributes include both
* resource locations and configuration classes
* @throws IllegalStateException if {@code GenericXmlContextLoader} detects default
* configuration classes; if {@code AnnotationConfigContextLoader} detects default
* resource locations; if neither candidate loader detects defaults for the supplied
* context configuration; or if both candidate loaders detect defaults for the
* supplied context configuration
*/
public void processContextConfiguration(final ContextConfigurationAttributes configAttributes) {
Assert.notNull(configAttributes, "configAttributes must not be null");
Assert.isTrue(!(configAttributes.hasLocations() && configAttributes.hasClasses()), String.format(
"Cannot process locations AND configuration classes for context "
+ "configuration %s; configure one or the other, but not both.", configAttributes));
// If the original locations or classes were not empty, there's no
// need to bother with default detection checks; just let the
// appropriate loader process the configuration.
if (configAttributes.hasLocations()) {
delegateProcessing(xmlLoader, configAttributes);
}
else if (configAttributes.hasClasses()) {
delegateProcessing(annotationConfigLoader, configAttributes);
}
else {
// Else attempt to detect defaults...
// Let the XML loader process the configuration.
delegateProcessing(xmlLoader, configAttributes);
boolean xmlLoaderDetectedDefaults = configAttributes.hasLocations();
if (xmlLoaderDetectedDefaults) {
if (logger.isInfoEnabled()) {
logger.info(String.format("%s detected default locations for context configuration %s.",
name(xmlLoader), configAttributes));
}
}
if (configAttributes.hasClasses()) {
throw new IllegalStateException(String.format(
"%s should NOT have detected default configuration classes for context configuration %s.",
name(xmlLoader), configAttributes));
}
// Now let the annotation config loader process the configuration.
delegateProcessing(annotationConfigLoader, configAttributes);
if (configAttributes.hasClasses()) {
if (logger.isInfoEnabled()) {
logger.info(String.format(
"%s detected default configuration classes for context configuration %s.",
name(annotationConfigLoader), configAttributes));
}
}
if (!xmlLoaderDetectedDefaults && configAttributes.hasLocations()) {
throw new IllegalStateException(String.format(
"%s should NOT have detected default locations for context configuration %s.",
name(annotationConfigLoader), configAttributes));
}
// If neither loader detected defaults, throw an exception.
if (!configAttributes.hasResources()) {
throw new IllegalStateException(String.format(
"Neither %s nor %s was able to detect defaults for context configuration %s.", name(xmlLoader),
name(annotationConfigLoader), configAttributes));
}
if (configAttributes.hasLocations() && configAttributes.hasClasses()) {
String message = String.format(
"Configuration error: both default locations AND default configuration classes "
+ "were detected for context configuration %s; configure one or the other, but not both.",
configAttributes);
logger.error(message);
throw new IllegalStateException(message);
}
}
}
/**
* Delegates to an appropriate candidate {@code SmartContextLoader} to load
* an {@link ApplicationContext}.
*
* <p>Delegation is based on explicit knowledge of the implementations of
* {@link GenericXmlContextLoader} and {@link AnnotationConfigContextLoader}.
* Specifically, the delegation algorithm is as follows:
*
* <ul>
* <li>If the resource locations in the supplied {@code MergedContextConfiguration}
* are not empty and the configuration classes are empty,
* {@code GenericXmlContextLoader} will load the {@code ApplicationContext}.</li>
* <li>If the configuration classes in the supplied {@code MergedContextConfiguration}
* are not empty and the resource locations are empty,
* {@code AnnotationConfigContextLoader} will load the {@code ApplicationContext}.</li>
* </ul>
*
* @param mergedConfig the merged context configuration to use to load the application context
* @throws IllegalArgumentException if the supplied merged configuration is <code>null</code>
* @throws IllegalStateException if neither candidate loader is capable of loading an
* {@code ApplicationContext} from the supplied merged context configuration
*/
public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {
Assert.notNull(mergedConfig, "mergedConfig must not be null");
List<SmartContextLoader> candidates = Arrays.asList(xmlLoader, annotationConfigLoader);
for (SmartContextLoader loader : candidates) {
// Determine if each loader can load a context from the
// mergedConfig. If it can, let it; otherwise, keep iterating.
if (supports(loader, mergedConfig)) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Delegating to %s to load context from %s.", name(loader), mergedConfig));
}
return loader.loadContext(mergedConfig);
}
}
throw new IllegalStateException(String.format(
"Neither %s nor %s was able to load an ApplicationContext from %s.", name(xmlLoader),
name(annotationConfigLoader), mergedConfig));
}
// --- ContextLoader -------------------------------------------------------
/**
* {@code DelegatingSmartContextLoader} does not support the
* {@link ContextLoader#processLocations(Class, String...)} method. Call
* {@link #processContextConfiguration(ContextConfigurationAttributes)} instead.
* @throws UnsupportedOperationException
*/
public String[] processLocations(Class<?> clazz, String... locations) {
throw new UnsupportedOperationException("DelegatingSmartContextLoader does not support the ContextLoader SPI. "
+ "Call processContextConfiguration(ContextConfigurationAttributes) instead.");
}
/**
* {@code DelegatingSmartContextLoader} does not support the
* {@link ContextLoader#loadContext(String...) } method. Call
* {@link #loadContext(MergedContextConfiguration)} instead.
* @throws UnsupportedOperationException
*/
public ApplicationContext loadContext(String... locations) throws Exception {
throw new UnsupportedOperationException("DelegatingSmartContextLoader does not support the ContextLoader SPI. "
+ "Call loadContext(MergedContextConfiguration) instead.");
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2002-2012 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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.data.gemfire.CacheFactoryBean;
import org.springframework.data.gemfire.client.ClientCacheFactoryBean;
import org.springframework.data.gemfire.server.CacheServerFactoryBean;
import com.gemstone.gemfire.cache.Cache;
/**
* @author David Turanski
*
*/
public class GemfireTestBeanPostProcessor implements BeanPostProcessor {
private static Log logger = LogFactory.getLog(GemfireTestBeanPostProcessor.class);
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof CacheFactoryBean) {
logger.info("replacing " + beanName+ " definition to mock GemFire components" );
bean = (bean instanceof ClientCacheFactoryBean)?
new MockClientCacheFactoryBean((ClientCacheFactoryBean)bean):
new MockCacheFactoryBean((CacheFactoryBean)bean);
}
else if (bean instanceof CacheServerFactoryBean) {
((CacheServerFactoryBean)bean).setCache(new StubCache());
}
return bean;
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2002-2012 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;
import org.springframework.test.context.TestContextManager;
/**
* @author David Turanski
*
*/
public class GemfireTestContextManager extends TestContextManager {
private final static String GEMFIRE_CONTEXT_LOADER_CLASSNAME = GemfireSmartContextLoader.class.getName();
/**
* @param testClass
* @param defaultContextLoaderClassName
*/
public GemfireTestContextManager(Class<?> testClass, String defaultContextLoaderClassName) {
super(testClass, defaultContextLoaderClassName);
initializeTestContext();
}
/**
*
*/
private void initializeTestContext() {
registerTestExecutionListeners(new GemfireTestExecutionListener());
}
/**
* @param testClass
*/
public GemfireTestContextManager(Class<?> testClass) {
super(testClass,GEMFIRE_CONTEXT_LOADER_CLASSNAME);
initializeTestContext();
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2002-2012 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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import com.gemstone.gemfire.cache.Cache;
/**
* @author David Turanski
*
*/
public class GemfireTestExecutionListener implements TestExecutionListener {
private static Log logger = LogFactory.getLog(GemfireTestExecutionListener.class);
/* (non-Javadoc)
* @see org.springframework.test.context.TestExecutionListener#beforeTestClass(org.springframework.test.context.TestContext)
*/
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
}
/* (non-Javadoc)
* @see org.springframework.test.context.TestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext)
*/
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.springframework.test.context.TestExecutionListener#beforeTestMethod(org.springframework.test.context.TestContext)
*/
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.springframework.test.context.TestExecutionListener#afterTestMethod(org.springframework.test.context.TestContext)
*/
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.springframework.test.context.TestExecutionListener#afterTestClass(org.springframework.test.context.TestContext)
*/
@Override
public void afterTestClass(TestContext testContext) throws Exception {
// TODO Auto-generated method stub
}
public static class GemfireTestBeanPostProcessor implements BeanPostProcessor {
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
logger.debug("I have bean " + beanName);
return bean;
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
return null;
}
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2002-2012 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;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author David Turanski
*
*/
public class GemfireTestRunner extends SpringJUnit4ClassRunner {
/**
* @param clazz
* @throws InitializationError
*/
public GemfireTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
protected TestContextManager createTestContextManager(Class<?> testClass) {
return new GemfireTestContextManager(testClass);
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2002-2012 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;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.test.context.support.GenericXmlContextLoader;
/**
* @author David Turanski
*
*/
public class GemfireXmlContextLoader extends GenericXmlContextLoader {
@Override
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
ContextLoaderUtils.customizeBeanFactory(beanFactory);
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2002-2012 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;
import java.util.Properties;
import org.springframework.data.gemfire.CacheFactoryBean;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.GemFireCache;
/**
* @author David Turanski
*
*/
public class MockCacheFactoryBean extends CacheFactoryBean {
public MockCacheFactoryBean() {
this.cache = new StubCache();
}
/**
* @param bean
*/
public MockCacheFactoryBean(CacheFactoryBean cacheFactoryBean) {
this();
if (cacheFactoryBean != null) {
this.factoryLocator = cacheFactoryBean.getBeanFactoryLocator();
this.beanFactory = cacheFactoryBean.getBeanFactory();
this.beanName = cacheFactoryBean.getBeanName();
this.beanClassLoader = cacheFactoryBean.getBeanClassLoader();
this.cacheXml = cacheFactoryBean.getCacheXml();
this.copyOnRead = cacheFactoryBean.getCopyOnRead();
this.criticalHeapPercentage = cacheFactoryBean.getCriticalHeapPercentage();
this.dynamicRegionSupport = cacheFactoryBean.getDynamicRegionSupport();
this.evictionHeapPercentage = cacheFactoryBean.getEvictionHeapPercentage();
this.gatewayConflictResolver = cacheFactoryBean.getGatewayConflictResolver();
this.jndiDataSources = cacheFactoryBean.getJndiDataSources();
this.lockLease = cacheFactoryBean.getLockLease();
this.lockTimeout = cacheFactoryBean.getLockTimeout();
this.messageSyncInterval = cacheFactoryBean.getMessageSyncInterval();
this.pdxDiskStoreName = cacheFactoryBean.getPdxDiskStoreName();
this.pdxIgnoreUnreadFields = cacheFactoryBean.getPdxIgnoreUnreadFields();
this.pdxPersistent = cacheFactoryBean.getPdxPersistent();
this.pdxSerializer = cacheFactoryBean.getPdxSerializer();
this.properties = cacheFactoryBean.getProperties();
this.searchTimeout = cacheFactoryBean.getSearchTimeout();
this.transactionListeners = cacheFactoryBean.getTransactionListeners();
this.transactionWriter = cacheFactoryBean.getTransactionWriter();
this.properties = cacheFactoryBean.getProperties();
}
}
@Override
protected Object createFactory(Properties props) {
setProperties(props);
return new CacheFactory(props);
}
protected GemFireCache fetchCache() {
((StubCache)cache).setProperties(this.properties);
return cache;
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2002-2012 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;
import java.util.Properties;
import org.springframework.data.gemfire.CacheFactoryBean;
import org.springframework.data.gemfire.client.ClientCacheFactoryBean;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
/**
* @author David Turanski
*
*/
public class MockClientCacheFactoryBean extends ClientCacheFactoryBean {
public MockClientCacheFactoryBean() {
this.cache = new StubCache();
}
/**
* @param bean
*/
public MockClientCacheFactoryBean(ClientCacheFactoryBean cacheFactoryBean) {
this();
if (cacheFactoryBean != null) {
this.factoryLocator = cacheFactoryBean.getBeanFactoryLocator();
this.beanFactory = cacheFactoryBean.getBeanFactory();
this.beanName = cacheFactoryBean.getBeanName();
this.beanClassLoader = cacheFactoryBean.getBeanClassLoader();
this.cacheXml = cacheFactoryBean.getCacheXml();
this.copyOnRead = cacheFactoryBean.getCopyOnRead();
this.criticalHeapPercentage = cacheFactoryBean.getCriticalHeapPercentage();
this.dynamicRegionSupport = cacheFactoryBean.getDynamicRegionSupport();
this.evictionHeapPercentage = cacheFactoryBean.getEvictionHeapPercentage();
this.gatewayConflictResolver = cacheFactoryBean.getGatewayConflictResolver();
this.jndiDataSources = cacheFactoryBean.getJndiDataSources();
this.lockLease = cacheFactoryBean.getLockLease();
this.lockTimeout = cacheFactoryBean.getLockTimeout();
this.messageSyncInterval = cacheFactoryBean.getMessageSyncInterval();
this.pdxDiskStoreName = cacheFactoryBean.getPdxDiskStoreName();
this.pdxIgnoreUnreadFields = cacheFactoryBean.getPdxIgnoreUnreadFields();
this.pdxPersistent = cacheFactoryBean.getPdxPersistent();
this.pdxSerializer = cacheFactoryBean.getPdxSerializer();
this.properties = cacheFactoryBean.getProperties();
this.searchTimeout = cacheFactoryBean.getSearchTimeout();
this.transactionListeners = cacheFactoryBean.getTransactionListeners();
this.transactionWriter = cacheFactoryBean.getTransactionWriter();
}
}
@Override
protected Object createFactory(Properties props) {
((StubCache)cache).setProperties(props);
return new ClientCacheFactory(props);
}
}

View File

@@ -0,0 +1,561 @@
/*
* Copyright 2002-2012 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;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.CacheListener;
import com.gemstone.gemfire.cache.CacheLoader;
import com.gemstone.gemfire.cache.CacheWriter;
import com.gemstone.gemfire.cache.CustomExpiry;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.DiskWriteAttributes;
import com.gemstone.gemfire.cache.EvictionAttributes;
import com.gemstone.gemfire.cache.ExpirationAttributes;
import com.gemstone.gemfire.cache.MembershipAttributes;
import com.gemstone.gemfire.cache.PartitionAttributes;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionFactory;
import com.gemstone.gemfire.cache.RegionService;
import com.gemstone.gemfire.cache.Scope;
import com.gemstone.gemfire.cache.SubscriptionAttributes;
import com.gemstone.gemfire.cache.query.QueryService;
/**
* @author David Turanski
*
*/
@SuppressWarnings("deprecation")
public class MockRegionFactory<K,V> {
private static QueryService queryService = mock(QueryService.class);
private static RegionService regionService = mock(RegionService.class);
private AttributesFactory<K,V> attributesFactory;
private final StubCache cache;
public MockRegionFactory(StubCache cache) {
this.cache = cache;
}
public RegionFactory<K, V> createMockRegionFactory() {
return createMockRegionFactory(null);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public RegionFactory<K, V> createMockRegionFactory(RegionAttributes<K,V> attributes) {
attributesFactory = attributes == null?
new AttributesFactory<K,V>() :
new AttributesFactory<K,V>(attributes) ;
//Workaround for GemFire bug
if(attributes !=null) {
attributesFactory.setLockGrantor(attributes.isLockGrantor());
}
final RegionFactory<K, V> regionFactory = mock(RegionFactory.class);
when(regionFactory.create(anyString())).thenAnswer(new Answer<Region>() {
@Override
public Region answer(InvocationOnMock invocation) throws Throwable {
String name = (String)invocation.getArguments()[0];
Region region = mockRegion(name);
cache.allRegions().put(name, region);
return region;
}});
when(regionFactory.createSubregion(any(Region.class),anyString())).thenAnswer(new Answer<Region>() {
@Override
public Region answer(InvocationOnMock invocation) throws Throwable {
Region parent = (Region)invocation.getArguments()[0];
String name = (String)invocation.getArguments()[1];
String parentName = null;
for (String key: cache.allRegions().keySet()) {
if (cache.allRegions().get(key).equals(parent)) {
parentName = key;
}
}
String regionName = parentName.startsWith("/") ? parentName+"/"+name : "/"+parentName+"/"+ name;
Region subRegion = mockRegion(regionName);
cache.allRegions().put(regionName, subRegion);
return subRegion;
}});
when(regionFactory.setCacheLoader(any(CacheLoader.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
CacheLoader val = (CacheLoader)invocation.getArguments()[0];
attributesFactory.setCacheLoader(val);
return regionFactory;
}
});
when(regionFactory.setCacheWriter(any(CacheWriter.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
CacheWriter val = (CacheWriter)invocation.getArguments()[0];
attributesFactory.setCacheWriter(val);
return regionFactory;
}
});
when(regionFactory.addAsyncEventQueueId(anyString())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
String val = (String)invocation.getArguments()[0];
attributesFactory.addAsyncEventQueueId(val);
return regionFactory;
}
});
when(regionFactory.addCacheListener(any(CacheListener.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
CacheListener val = (CacheListener)invocation.getArguments()[0];
attributesFactory.addCacheListener(val);
return regionFactory;
}
});
when(regionFactory.setEvictionAttributes(any(EvictionAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
EvictionAttributes val = (EvictionAttributes)invocation.getArguments()[0];
attributesFactory.setEvictionAttributes(val);
return regionFactory;
}
});
when(regionFactory.setEntryIdleTimeout(any(ExpirationAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
ExpirationAttributes val = (ExpirationAttributes)invocation.getArguments()[0];
attributesFactory.setEntryIdleTimeout(val);
return regionFactory;
}
});
when(regionFactory.setCustomEntryIdleTimeout(any(CustomExpiry.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
CustomExpiry val = (CustomExpiry)invocation.getArguments()[0];
attributesFactory.setCustomEntryIdleTimeout(val);
return regionFactory;
}
});
when(regionFactory.setEntryTimeToLive(any(ExpirationAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
ExpirationAttributes val = (ExpirationAttributes)invocation.getArguments()[0];
attributesFactory.setEntryTimeToLive(val);
return regionFactory;
}
});
when(regionFactory.setCustomEntryTimeToLive(any(CustomExpiry.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
CustomExpiry val = (CustomExpiry)invocation.getArguments()[0];
attributesFactory.setCustomEntryTimeToLive(val);
return regionFactory;
}
});
when(regionFactory.setRegionIdleTimeout(any(ExpirationAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
ExpirationAttributes val = (ExpirationAttributes)invocation.getArguments()[0];
attributesFactory.setRegionIdleTimeout(val);
return regionFactory;
}
});
when(regionFactory.setRegionTimeToLive(any(ExpirationAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
ExpirationAttributes val = (ExpirationAttributes)invocation.getArguments()[0];
attributesFactory.setRegionTimeToLive(val);
return regionFactory;
}
});
when(regionFactory.setScope(any(Scope.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
Scope val = (Scope)invocation.getArguments()[0];
attributesFactory.setScope(val);
return regionFactory;
}
});
when(regionFactory.setDataPolicy(any(DataPolicy.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
DataPolicy val = (DataPolicy)invocation.getArguments()[0];
attributesFactory.setDataPolicy(val);
return regionFactory;
}
});
when(regionFactory.setEarlyAck(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setEarlyAck(val);
return regionFactory;
}
});
when(regionFactory.setMulticastEnabled(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setMulticastEnabled(val);
return regionFactory;
}
});
when(regionFactory.setPoolName(anyString())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
String val = (String)invocation.getArguments()[0];
attributesFactory.setPoolName(val);
return regionFactory;
}
});
when(regionFactory.setEnableGateway(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setEnableGateway(val);
return regionFactory;
}
});
when(regionFactory.setEnableAsyncConflation(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setEnableAsyncConflation(val);
return regionFactory;
}
});
when(regionFactory.setEnableSubscriptionConflation(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setEnableSubscriptionConflation(val);
return regionFactory;
}
});
when(regionFactory.setKeyConstraint(any(Class.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
Class val = (Class)invocation.getArguments()[0];
attributesFactory.setKeyConstraint(val);
return regionFactory;
}
});
when(regionFactory.setValueConstraint(any(Class.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
Class val = (Class)invocation.getArguments()[0];
attributesFactory.setValueConstraint(val);
return regionFactory;
}
});
when(regionFactory.setInitialCapacity(anyInt())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
int val = (Integer)invocation.getArguments()[0];
System.out.println("setInitialCapacity " + val);
attributesFactory.setInitialCapacity(val);
return regionFactory;
}
});
when(regionFactory.setLoadFactor(anyInt())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
int val = (Integer)invocation.getArguments()[0];
attributesFactory.setLoadFactor(val);
return regionFactory;
}
});
when(regionFactory.setConcurrencyLevel(anyInt())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
int val = (Integer)invocation.getArguments()[0];
attributesFactory.setConcurrencyLevel(val);
return regionFactory;
}
});
when(regionFactory.setConcurrencyChecksEnabled(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setConcurrencyChecksEnabled(val);
return regionFactory;
}
});
when(regionFactory.setDiskWriteAttributes(any(DiskWriteAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
DiskWriteAttributes val = (DiskWriteAttributes)invocation.getArguments()[0];
attributesFactory.setDiskWriteAttributes(val);
return regionFactory;
}
});
when(regionFactory.setDiskStoreName(anyString())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
String val = (String)invocation.getArguments()[0];
attributesFactory.setDiskStoreName(val);
return regionFactory;
}
});
when(regionFactory.setDiskSynchronous(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setDiskSynchronous(val);
return regionFactory;
}
});
when(regionFactory.setDiskDirs(any(File[].class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
File[] val = (File[])invocation.getArguments()[0];
attributesFactory.setDiskDirs(val);
return regionFactory;
}
});
when(regionFactory.setDiskDirsAndSizes(any(File[].class),any(int[].class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
File[] val0 = (File[])invocation.getArguments()[0];
int[] val1 = (int[])invocation.getArguments()[1];
attributesFactory.setDiskDirsAndSizes(val0,val1);
return regionFactory;
}
});
when(regionFactory.setPartitionAttributes(any(PartitionAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
PartitionAttributes val = (PartitionAttributes)invocation.getArguments()[0];
attributesFactory.setPartitionAttributes(val);
return regionFactory;
}
});
when(regionFactory.setMembershipAttributes(any(MembershipAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
MembershipAttributes val = (MembershipAttributes)invocation.getArguments()[0];
attributesFactory.setMembershipAttributes(val);
return regionFactory;
}
});
when(regionFactory.setIndexMaintenanceSynchronous(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setIndexMaintenanceSynchronous(val);
return regionFactory;
}
});
when(regionFactory.setStatisticsEnabled(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setStatisticsEnabled(val);
return regionFactory;
}
});
when(regionFactory.setIgnoreJTA(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setIgnoreJTA(val);
return regionFactory;
}
});
when(regionFactory.setLockGrantor(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
System.out.println("setting lock grantor to " + val);
attributesFactory.setLockGrantor(val);
return regionFactory;
}
});
when(regionFactory.setSubscriptionAttributes(any(SubscriptionAttributes.class))).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
SubscriptionAttributes val = (SubscriptionAttributes)invocation.getArguments()[0];
attributesFactory.setSubscriptionAttributes(val);
return regionFactory;
}
});
when(regionFactory.setGatewayHubId(anyString())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
String val = (String)invocation.getArguments()[0];
attributesFactory.setGatewayHubId(val);
return regionFactory;
}
});
when(regionFactory.setCloningEnabled(anyBoolean())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
boolean val = (Boolean)invocation.getArguments()[0];
attributesFactory.setCloningEnabled(val);
return regionFactory;
}
});
when(regionFactory.addGatewaySenderId(anyString())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
String val = (String)invocation.getArguments()[0];
attributesFactory.addGatewaySenderId(val);
return regionFactory;
}
});
when(regionFactory.addAsyncEventQueueId(anyString())).thenAnswer(new Answer<RegionFactory>(){
@Override
public RegionFactory answer(InvocationOnMock invocation) throws Throwable {
String val = (String)invocation.getArguments()[0];
attributesFactory.addAsyncEventQueueId(val);
return regionFactory;
}
});
return regionFactory;
}
RegionFactory createRegionFactory() {
return createMockRegionFactory();
}
@SuppressWarnings("unchecked")
public Region mockRegion(String name) {
RegionService regionService = mockRegionService();
Region region = mock(Region.class);
when(region.getRegionService()).thenReturn(regionService);
when(region.getAttributes()).thenAnswer(new Answer<RegionAttributes>() {
@Override
public RegionAttributes answer(InvocationOnMock invocation) throws Throwable {
RegionAttributes attributes = attributesFactory.create();
return attributes;
}
});
when(region.getName()).thenReturn(name);
when(region.getSubregion(anyString())).thenAnswer(new Answer<Region>() {
@Override
public Region answer(InvocationOnMock invocation) throws Throwable {
String name = (String) invocation.getArguments()[0];
Region parent = (Region)invocation.getMock();
String parentName = parent.getName();
String regionName = parentName.startsWith("/") ? parentName+"/"+ name :
"/"+parentName+"/"+ name;
Region region = cache.getRegion(regionName);
return region;
}
});
when(region.createSubregion(anyString(),any(RegionAttributes.class))).thenAnswer(new Answer<Region>() {
@SuppressWarnings("rawtypes")
@Override
public Region answer(InvocationOnMock invocation) throws Throwable {
String name = (String)invocation.getArguments()[0];
RegionAttributes attributes = (RegionAttributes)invocation.getArguments()[1];
Region parent = (Region)invocation.getMock();
String parentName = parent.getName();
String regionName = parentName.startsWith("/") ? parentName+"/"+name : "/"+parentName+"/"+ name;
Region subRegion = new MockRegionFactory(cache).createMockRegionFactory(attributes).create(regionName);
when(subRegion.getFullPath()).thenReturn(regionName);
cache.allRegions().put(regionName, subRegion);
return subRegion;
}});
return region;
}
public static RegionService mockRegionService() {
when(regionService.getQueryService()).thenReturn(queryService);
return regionService;
}
public static QueryService mockQueryService() {
return queryService;
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2002-2012 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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.gemstone.gemfire.cache.asyncqueue.AsyncEventListener;
import com.gemstone.gemfire.cache.asyncqueue.AsyncEventQueue;
import com.gemstone.gemfire.cache.asyncqueue.AsyncEventQueueFactory;
/**
* @author David Turanski
*
*/
public class StubAsyncEventQueueFactory implements AsyncEventQueueFactory {
private AsyncEventListener listener;
private AsyncEventQueue asyncEventQueue = mock(AsyncEventQueue.class);
private boolean persistent;
private int maxQueueMemory;
private String diskStoreName;
private int batchSize;
private String name;
private boolean parallel;
@Override
public AsyncEventQueue create(String name, AsyncEventListener listener) {
this.name = name;
this.listener = listener;
when(asyncEventQueue.getAsyncEventListener()).thenReturn(this.listener);
when(asyncEventQueue.getBatchSize()).thenReturn(this.batchSize);
when(asyncEventQueue.getDiskStoreName()).thenReturn(this.diskStoreName);
when(asyncEventQueue.isPersistent()).thenReturn(this.persistent);
when(asyncEventQueue.getId()).thenReturn(this.name);
when(asyncEventQueue.getMaximumQueueMemory()).thenReturn(this.maxQueueMemory);
when(asyncEventQueue.isParallel()).thenReturn(this.parallel);
return this.asyncEventQueue;
}
@Override
public AsyncEventQueueFactory setBatchSize(int batchSize) {
this.batchSize = batchSize;
return this;
}
@Override
public AsyncEventQueueFactory setDiskStoreName(String diskStoreName) {
this.diskStoreName = diskStoreName;
return this;
}
@Override
public AsyncEventQueueFactory setMaximumQueueMemory(int maxQueueMemory) {
this.maxQueueMemory = maxQueueMemory;
return this;
}
@Override
public AsyncEventQueueFactory setPersistent(boolean persistent) {
this.persistent = persistent;
return this;
}
@Override
public AsyncEventQueueFactory setParallel(boolean parallel) {
this.parallel = parallel;
return this;
}
}

View File

@@ -0,0 +1,890 @@
package org.springframework.data.gemfire.test;
import static org.mockito.Mockito.*;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import javax.naming.Context;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.gemstone.gemfire.CancelCriterion;
import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheTransactionManager;
import com.gemstone.gemfire.cache.CacheWriterException;
import com.gemstone.gemfire.cache.Declarable;
import com.gemstone.gemfire.cache.DiskStore;
import com.gemstone.gemfire.cache.DiskStoreFactory;
import com.gemstone.gemfire.cache.GatewayException;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionExistsException;
import com.gemstone.gemfire.cache.RegionFactory;
import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.TimeoutException;
import com.gemstone.gemfire.cache.asyncqueue.AsyncEventQueue;
import com.gemstone.gemfire.cache.asyncqueue.AsyncEventQueueFactory;
import com.gemstone.gemfire.cache.control.ResourceManager;
import com.gemstone.gemfire.cache.query.Index;
import com.gemstone.gemfire.cache.query.IndexExistsException;
import com.gemstone.gemfire.cache.query.IndexInvalidException;
import com.gemstone.gemfire.cache.query.IndexNameConflictException;
import com.gemstone.gemfire.cache.query.IndexType;
import com.gemstone.gemfire.cache.query.QueryService;
import com.gemstone.gemfire.cache.query.RegionNotFoundException;
import com.gemstone.gemfire.cache.server.CacheServer;
import com.gemstone.gemfire.cache.snapshot.CacheSnapshotService;
import com.gemstone.gemfire.cache.util.BridgeServer;
import com.gemstone.gemfire.cache.util.Gateway;
import com.gemstone.gemfire.cache.util.GatewayConflictResolver;
import com.gemstone.gemfire.cache.util.GatewayHub;
import com.gemstone.gemfire.cache.util.GatewayQueueAttributes;
import com.gemstone.gemfire.cache.wan.GatewayReceiver;
import com.gemstone.gemfire.cache.wan.GatewayReceiverFactory;
import com.gemstone.gemfire.cache.wan.GatewaySender;
import com.gemstone.gemfire.cache.wan.GatewaySenderFactory;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.i18n.LogWriterI18n;
import com.gemstone.gemfire.pdx.PdxInstance;
import com.gemstone.gemfire.pdx.PdxInstanceFactory;
import com.gemstone.gemfire.pdx.PdxSerializer;
public class StubCache implements Cache {
private Properties properties;
private DistributedSystem distributedSystem;
private CacheTransactionManager cacheTransactionManager;
private boolean copyOnRead;
private Declarable initializer;
private Context jndiContext;
private LogWriter logWriter;
private String name;
private String pdxDiskStore;
private boolean pdxIgnoreUnreadFields;
private boolean pdxPersistent;
private boolean pdxReadSerialized;
private PdxSerializer pdxSerializer;
private ResourceManager resourceManager;
private LogWriter securityLogger;
private boolean closed;
private GatewayConflictResolver gatewayConflictResolver;
private List<GatewayHub> gatewayHubs;
private Set<GatewayReceiver> gatewayReceivers;
private Set<GatewaySender> gatewaySenders;
private int lockLease;
private int lockTimeout;
private int messageSyncInterval;
private int searchTimeout;
private boolean server;
private HashMap<String, Region> allRegions;
public StubCache(){
this.allRegions = new HashMap<String,Region>();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#createDiskStoreFactory()
*/
@Override
public DiskStoreFactory createDiskStoreFactory() {
return new StubDiskStore();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#findDiskStore(java.lang.String)
*/
@Override
public DiskStore findDiskStore(String name) {
return StubDiskStore.diskStores.get(name);
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getCacheTransactionManager()
*/
@Override
public CacheTransactionManager getCacheTransactionManager() {
if (cacheTransactionManager == null) {
cacheTransactionManager = new StubCacheTransactionMananger();
}
return cacheTransactionManager;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getCopyOnRead()
*/
@Override
public boolean getCopyOnRead() {
return this.copyOnRead;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getDistributedSystem()
*/
@Override
public DistributedSystem getDistributedSystem() {
if (distributedSystem == null) {
distributedSystem = mockDistributedSystem();
}
return distributedSystem;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getInitializer()
*/
@Override
public Declarable getInitializer() {
return this.initializer;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getInitializerProps()
*/
@Override
public Properties getInitializerProps() {
return this.properties;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getJNDIContext()
*/
@Override
public Context getJNDIContext() {
return this.jndiContext;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getLogger()
*/
@Override
public LogWriter getLogger() {
return this.logWriter;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getName()
*/
@Override
public String getName() {
return this.properties == null? null: (String)this.properties.get("name");
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getPdxDiskStore()
*/
@Override
public String getPdxDiskStore() {
return this.pdxDiskStore;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getPdxIgnoreUnreadFields()
*/
@Override
public boolean getPdxIgnoreUnreadFields() {
return this.pdxIgnoreUnreadFields;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getPdxPersistent()
*/
@Override
public boolean getPdxPersistent() {
return this.pdxPersistent;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getPdxReadSerialized()
*/
@Override
public boolean getPdxReadSerialized() {
return this.pdxReadSerialized;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getPdxSerializer()
*/
@Override
public PdxSerializer getPdxSerializer() {
return this.pdxSerializer;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getRegionAttributes(java.lang.String)
*/
@Override
public <K, V> RegionAttributes<K, V> getRegionAttributes(String region) {
return allRegions().get(region).getAttributes();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getResourceManager()
*/
@Override
public ResourceManager getResourceManager() {
return this.resourceManager;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#getSecurityLogger()
*/
@Override
public LogWriter getSecurityLogger() {
return this.securityLogger;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#listRegionAttributes()
*/
@Override
public <K, V> Map<String, RegionAttributes<K, V>> listRegionAttributes() {
Map<String, RegionAttributes<K, V>> attributes = new HashMap<String, RegionAttributes<K, V>>();
for (Entry<String, Region> entry: allRegions().entrySet()) {
attributes.put(entry.getKey(), entry.getValue().getAttributes());
}
return attributes;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#loadCacheXml(java.io.InputStream)
*/
@Override
public void loadCacheXml(InputStream is) throws TimeoutException, CacheWriterException, GatewayException,
RegionExistsException {
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#setCopyOnRead(boolean)
*/
@Override
public void setCopyOnRead(boolean arg0) {
this.copyOnRead = arg0;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.GemFireCache#setRegionAttributes(java.lang.String, com.gemstone.gemfire.cache.RegionAttributes)
*/
@Override
public <K, V> void setRegionAttributes(String region, RegionAttributes<K, V> attributes) {
RegionFactory<K,V> rf = new MockRegionFactory<K, V>(this).createMockRegionFactory(attributes);
rf.create(region);
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.RegionService#close()
*/
@Override
public void close() {
this.closed = true;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.RegionService#createPdxEnum(java.lang.String, java.lang.String, int)
*/
@Override
public PdxInstance createPdxEnum(String arg0, String arg1, int arg2) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.RegionService#createPdxInstanceFactory(java.lang.String)
*/
@Override
public PdxInstanceFactory createPdxInstanceFactory(String arg0) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.RegionService#getCancelCriterion()
*/
@Override
public CancelCriterion getCancelCriterion() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.RegionService#getQueryService()
*/
@Override
public QueryService getQueryService() {
QueryService qs = null;
try {
qs = mockQueryService();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qs;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.RegionService#getRegion(java.lang.String)
*/
@Override
public <K, V> Region<K, V> getRegion(String name) {
return allRegions().get(name);
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.RegionService#isClosed()
*/
@Override
public boolean isClosed() {
return this.closed;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.RegionService#rootRegions()
*/
@Override
public Set<Region<?, ?>> rootRegions() {
Set<Region<?,?>> rootRegions = new HashSet<Region<?,?>>();
for (String key: allRegions().keySet()) {
if (!key.contains("/")) {
rootRegions.add(allRegions().get(key));
}
}
return rootRegions;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#addBridgeServer()
*/
@Override
@Deprecated
public BridgeServer addBridgeServer() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#addCacheServer()
*/
@Override
public CacheServer addCacheServer() {
return mockCacheServer();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#addGatewayHub(java.lang.String, int)
*/
@Override
public GatewayHub addGatewayHub(String name, int port) {
return mockGatewayHub();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#close(boolean)
*/
@Override
@Deprecated
public void close(boolean arg0) {
this.closed = true;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createAsyncEventQueueFactory()
*/
@Override
public AsyncEventQueueFactory createAsyncEventQueueFactory() {
return new StubAsyncEventQueueFactory();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createGatewayReceiverFactory()
*/
@Override
public GatewayReceiverFactory createGatewayReceiverFactory() {
return new StubGatewayReceiverFactory();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createGatewaySenderFactory()
*/
@Override
public GatewaySenderFactory createGatewaySenderFactory() {
return new StubGatewaySenderFactory();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createRegion(java.lang.String, com.gemstone.gemfire.cache.RegionAttributes)
*/
@Override
@Deprecated
public <K, V> Region<K, V> createRegion(String arg0, RegionAttributes<K, V> arg1) throws RegionExistsException,
TimeoutException {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createRegionFactory()
*/
@SuppressWarnings("unchecked")
@Override
public <K, V> RegionFactory<K, V> createRegionFactory() {
RegionFactory<K, V> regionFactory = new MockRegionFactory<K,V>(this).createRegionFactory();
return regionFactory;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createRegionFactory(com.gemstone.gemfire.cache.RegionShortcut)
*/
@Override
public <K, V> RegionFactory<K, V> createRegionFactory(RegionShortcut shortCut) {
RegionFactory<K, V> regionFactory = new MockRegionFactory<K,V>(this).createRegionFactory();
return regionFactory;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createRegionFactory(java.lang.String)
*/
@Override
public <K, V> RegionFactory<K, V> createRegionFactory(String arg0) {
RegionFactory<K, V> regionFactory = new MockRegionFactory<K,V>(this).createRegionFactory();
return regionFactory;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createRegionFactory(com.gemstone.gemfire.cache.RegionAttributes)
*/
@Override
public <K, V> RegionFactory<K, V> createRegionFactory(RegionAttributes<K, V> regionAttributes) {
RegionFactory<K, V> regionFactory = new MockRegionFactory<K,V>(this).createMockRegionFactory(regionAttributes);
return regionFactory;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#createVMRegion(java.lang.String, com.gemstone.gemfire.cache.RegionAttributes)
*/
@Override
@Deprecated
public <K, V> Region<K, V> createVMRegion(String arg0, RegionAttributes<K, V> arg1) throws RegionExistsException,
TimeoutException {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getAdminMembers()
*/
@Override
public Set<DistributedMember> getAdminMembers() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getAsyncEventQueue(java.lang.String)
*/
@Override
public AsyncEventQueue getAsyncEventQueue(String name) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getAsyncEventQueues()
*/
@Override
public Set<AsyncEventQueue> getAsyncEventQueues() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getBridgeServers()
*/
@Override
@Deprecated
public List<CacheServer> getBridgeServers() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getCacheServers()
*/
@Override
public List<CacheServer> getCacheServers() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getGatewayConflictResolver()
*/
@Override
public GatewayConflictResolver getGatewayConflictResolver() {
return this.gatewayConflictResolver;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getGatewayHub()
*/
@Override
@Deprecated
public GatewayHub getGatewayHub() {
return mockGatewayHub();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getGatewayHub(java.lang.String)
*/
@Override
public GatewayHub getGatewayHub(String name) {
return mockGatewayHub();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getGatewayHubs()
*/
@Override
public List<GatewayHub> getGatewayHubs() {
return this.gatewayHubs;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getGatewayReceivers()
*/
@Override
public Set<GatewayReceiver> getGatewayReceivers() {
return this.gatewayReceivers;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getGatewaySender(java.lang.String)
*/
@Override
public GatewaySender getGatewaySender(String name) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getGatewaySenders()
*/
@Override
public Set<GatewaySender> getGatewaySenders() {
return this.gatewaySenders;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getLockLease()
*/
@Override
public int getLockLease() {
return this.lockLease;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getLockTimeout()
*/
@Override
public int getLockTimeout() {
return this.lockTimeout;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getLoggerI18n()
*/
@Override
@Deprecated
public LogWriterI18n getLoggerI18n() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getMembers()
*/
@Override
public Set<DistributedMember> getMembers() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getMembers(com.gemstone.gemfire.cache.Region)
*/
@Override
public Set<DistributedMember> getMembers(Region arg0) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getMessageSyncInterval()
*/
@Override
public int getMessageSyncInterval() {
return this.messageSyncInterval;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getSearchTimeout()
*/
@Override
public int getSearchTimeout() {
return this.searchTimeout;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getSecurityLoggerI18n()
*/
@Override
@Deprecated
public LogWriterI18n getSecurityLoggerI18n() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#getSnapshotService()
*/
@Override
public CacheSnapshotService getSnapshotService() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#isServer()
*/
@Override
public boolean isServer() {
return this.server;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#readyForEvents()
*/
@Override
@Deprecated
public void readyForEvents() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#setGatewayConflictResolver(com.gemstone.gemfire.cache.util.GatewayConflictResolver)
*/
@Override
public void setGatewayConflictResolver(GatewayConflictResolver arg0) {
this.gatewayConflictResolver = arg0;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#setGatewayHub(java.lang.String, int)
*/
@Override
@Deprecated
public GatewayHub setGatewayHub(String arg0, int arg1) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#setIsServer(boolean)
*/
@Override
public void setIsServer(boolean arg0) {
this.server = arg0;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#setLockLease(int)
*/
@Override
public void setLockLease(int arg0) {
this.lockLease = arg0;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#setLockTimeout(int)
*/
@Override
public void setLockTimeout(int arg0) {
this.lockTimeout = arg0;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#setMessageSyncInterval(int)
*/
@Override
public void setMessageSyncInterval(int arg0) {
this.messageSyncInterval = arg0;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Cache#setSearchTimeout(int)
*/
@Override
public void setSearchTimeout(int arg0) {
this.searchTimeout = arg0;
}
/**
* @return
*/
DistributedSystem mockDistributedSystem() {
DistributedSystem ds = mock(DistributedSystem.class);
DistributedMember dm = mockDistributedMember();
when(ds.getName()).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return getName();
}
});
when(ds.getDistributedMember()).thenReturn(dm);
return ds;
}
DistributedMember mockDistributedMember() {
DistributedMember dm = mock(DistributedMember.class);
when(dm.getHost()).thenReturn("mockDistributedMember.host");
when(dm.getName()).thenReturn("mockDistributedMember");
return dm;
}
/**
* @return
*/
CacheServer mockCacheServer() {
return new StubCacheServer();
}
GatewayHub mockGatewayHub() {
final Gateway gw = mock(Gateway.class);
final GatewayQueueAttributes queueAttributes= mock(GatewayQueueAttributes.class);
when(gw.getQueueAttributes()).thenReturn(queueAttributes);
GatewayHub gwh = mock(GatewayHub.class);
when(gwh.addGateway(anyString(),anyInt())).thenAnswer(new Answer<Gateway>() {
@Override
public Gateway answer(InvocationOnMock invocation) throws Throwable {
// TODO Auto-generated method stub
return gw;
}
});
return gwh;
}
QueryService mockQueryService() throws RegionNotFoundException, IndexInvalidException, IndexNameConflictException, IndexExistsException, UnsupportedOperationException {
QueryService qs = mock(QueryService.class);
when(qs.getIndexes()).thenReturn(new ArrayList<Index>());
when(qs.createIndex(anyString(), anyString(),anyString())).thenAnswer(new Answer<Index>(){
@Override
public Index answer(InvocationOnMock invocation) throws Throwable {
String indexName = (String)invocation.getArguments()[0];
String indexedExpression = (String)invocation.getArguments()[1];
String fromClause = (String)invocation.getArguments()[2];
return mockIndex(indexName, null, indexedExpression, fromClause, null, null);
}
});
when(qs.createIndex(anyString(), anyString(),anyString(),anyString())).thenAnswer(new Answer<Index>(){
@Override
public Index answer(InvocationOnMock invocation) throws Throwable {
String indexName = (String)invocation.getArguments()[0];
String indexedExpression = (String)invocation.getArguments()[1];
String fromClause = (String)invocation.getArguments()[2];
return mockIndex(indexName, null, indexedExpression, fromClause, null, null);
}
});
when(qs.createIndex(anyString(), any(IndexType.class), anyString(), anyString())).thenAnswer(new Answer<Index>(){
@Override
public Index answer(InvocationOnMock invocation) throws Throwable {
String indexName = (String)invocation.getArguments()[0];
IndexType type = (IndexType)invocation.getArguments()[1];
String indexedExpression = (String)invocation.getArguments()[2];
String fromClause = (String)invocation.getArguments()[3];
return mockIndex(indexName, type, indexedExpression, null, fromClause, null);
}
});
when(qs.createIndex(anyString(), any(IndexType.class),anyString(), anyString(), anyString())).thenAnswer(new Answer<Index>(){
@Override
public Index answer(InvocationOnMock invocation) throws Throwable {
String indexName = (String)invocation.getArguments()[0];
IndexType type = (IndexType)invocation.getArguments()[1];
String indexedExpression = (String)invocation.getArguments()[2];
String fromClause = (String)invocation.getArguments()[3];
String imports = (String)invocation.getArguments()[4];
return mockIndex(indexName, type, indexedExpression, null, fromClause, imports);
}
});
return qs;
}
Index mockIndex(String indexName, IndexType indexType,String indexedExpression, String regionPath, String fromClause, String imports){
Index idx = mock(Index.class);
when(idx.getFromClause()).thenReturn(fromClause);
when(idx.getIndexedExpression()).thenReturn(indexedExpression);
when(idx.getName()).thenReturn(indexName);
when(idx.getType()).thenReturn(indexType);
if (fromClause != null && fromClause.length() >= 2) {
Region region = mock(Region.class);
String name = fromClause.substring(1).split(" ")[0];
when(region.getName()).thenReturn(name);
when(idx.getRegion()).thenReturn(region);
}
return idx;
}
public Map<String,Region> allRegions() {
return this.allRegions;
}
GatewaySender mockGatewaySender(String id, int remoteId) {
GatewaySender gwSender = mock(GatewaySender.class);
when(gwSender.getId()).thenReturn(id);
when(gwSender.getRemoteDSId()).thenReturn(remoteId);
return gwSender;
}
/**
* @param props
*/
public void setProperties(Properties props) {
this.properties = props;
}
}

View File

@@ -0,0 +1,352 @@
/*
* Copyright 2002-2012 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;
import java.io.IOException;
import java.util.Set;
import com.gemstone.gemfire.cache.ClientSession;
import com.gemstone.gemfire.cache.InterestRegistrationListener;
import com.gemstone.gemfire.cache.server.CacheServer;
import com.gemstone.gemfire.cache.server.ClientSubscriptionConfig;
import com.gemstone.gemfire.cache.server.ServerLoadProbe;
import com.gemstone.gemfire.distributed.DistributedMember;
import static org.mockito.Mockito.*;
/**
* @author David Turanski
*
*/
public class StubCacheServer implements CacheServer {
private boolean isRunning;
private int port;
private String bindAddress;
private String hostNameForClients;
private boolean notifyBySubscription;
private int socketBufferSize;
private int maximumTimeBetweenPings;
private int maxConnections;
private int maxThreads;
private int maximumMessageCount;
private int messageTimeToLive;
private String[] groups;
private ServerLoadProbe serverLoadProbe;
private long loadPollInterval;
private ClientSubscriptionConfig clientSubscriptionConfig = mockClientSubscriptionConfig();
private ClientSession clientSession;
private Set<ClientSession> clientSessions;
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getPort()
*/
@Override
public int getPort() {
return port;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setPort(int)
*/
@Override
public void setPort(int port) {
this.port = port;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getBindAddress()
*/
@Override
public String getBindAddress() {
return bindAddress;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setBindAddress(java.lang.String)
*/
@Override
public void setBindAddress(String address) {
this.bindAddress = address;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getHostnameForClients()
*/
@Override
public String getHostnameForClients() {
return this.hostNameForClients;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setHostnameForClients(java.lang.String)
*/
@Override
public void setHostnameForClients(String name) {
this.hostNameForClients = name;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setNotifyBySubscription(boolean)
*/
@Override
@Deprecated
public void setNotifyBySubscription(boolean b) {
this.notifyBySubscription = b;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getNotifyBySubscription()
*/
@Override
@Deprecated
public boolean getNotifyBySubscription() {
return this.notifyBySubscription;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setSocketBufferSize(int)
*/
@Override
public void setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getSocketBufferSize()
*/
@Override
public int getSocketBufferSize() {
return this.socketBufferSize;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setMaximumTimeBetweenPings(int)
*/
@Override
public void setMaximumTimeBetweenPings(int maximumTimeBetweenPings) {
this.maximumTimeBetweenPings = maximumTimeBetweenPings;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getMaximumTimeBetweenPings()
*/
@Override
public int getMaximumTimeBetweenPings() {
return this.maximumTimeBetweenPings;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#start()
*/
@Override
public void start() throws IOException {
isRunning = true;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#isRunning()
*/
@Override
public boolean isRunning() {
return isRunning;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#stop()
*/
@Override
public void stop() {
isRunning = false;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getMaxConnections()
*/
@Override
public int getMaxConnections() {
return this.maxConnections;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setMaxConnections(int)
*/
@Override
public void setMaxConnections(int maxCons) {
this.maxConnections = maxCons;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getMaxThreads()
*/
@Override
public int getMaxThreads() {
return this.maxThreads;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setMaxThreads(int)
*/
@Override
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getMaximumMessageCount()
*/
@Override
public int getMaximumMessageCount() {
return this.maximumMessageCount;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setMaximumMessageCount(int)
*/
@Override
public void setMaximumMessageCount(int maxMessageCount) {
this.maximumMessageCount = maxMessageCount;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getMessageTimeToLive()
*/
@Override
public int getMessageTimeToLive() {
return this.messageTimeToLive;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setMessageTimeToLive(int)
*/
@Override
public void setMessageTimeToLive(int messageTimeToLive) {
this.messageTimeToLive = messageTimeToLive;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setGroups(java.lang.String[])
*/
@Override
public void setGroups(String[] groups) {
this.groups = groups;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getGroups()
*/
@Override
public String[] getGroups() {
return this.groups;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getLoadProbe()
*/
@Override
public ServerLoadProbe getLoadProbe() {
return this.serverLoadProbe;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setLoadProbe(com.gemstone.gemfire.cache.server.ServerLoadProbe)
*/
@Override
public void setLoadProbe(ServerLoadProbe loadProbe) {
this.serverLoadProbe = serverLoadProbe;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getLoadPollInterval()
*/
@Override
public long getLoadPollInterval() {
return this.loadPollInterval;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#setLoadPollInterval(long)
*/
@Override
public void setLoadPollInterval(long loadPollInterval) {
this.loadPollInterval = loadPollInterval;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getClientSubscriptionConfig()
*/
@Override
public ClientSubscriptionConfig getClientSubscriptionConfig() {
return this.clientSubscriptionConfig;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getClientSession(com.gemstone.gemfire.distributed.DistributedMember)
*/
@Override
public ClientSession getClientSession(DistributedMember member) {
return this.clientSession;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getClientSession(java.lang.String)
*/
@Override
public ClientSession getClientSession(String durableClientId) {
return this.clientSession;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getAllClientSessions()
*/
@Override
public Set<ClientSession> getAllClientSessions() {
return this.clientSessions;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#registerInterestRegistrationListener(com.gemstone.gemfire.cache.InterestRegistrationListener)
*/
@Override
public void registerInterestRegistrationListener(InterestRegistrationListener listener) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#unregisterInterestRegistrationListener(com.gemstone.gemfire.cache.InterestRegistrationListener)
*/
@Override
public void unregisterInterestRegistrationListener(InterestRegistrationListener listener) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.server.CacheServer#getInterestRegistrationListeners()
*/
@Override
public Set<InterestRegistrationListener> getInterestRegistrationListeners() {
// TODO Auto-generated method stub
return null;
}
/**
* @return
*/
ClientSubscriptionConfig mockClientSubscriptionConfig() {
// TODO Auto-generated method stub
return mock(ClientSubscriptionConfig.class);
}
}

View File

@@ -0,0 +1,207 @@
/*
* Copyright 2002-2012 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;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.util.CollectionUtils;
import com.gemstone.gemfire.cache.CacheTransactionManager;
import com.gemstone.gemfire.cache.CommitConflictException;
import com.gemstone.gemfire.cache.TransactionEvent;
import com.gemstone.gemfire.cache.TransactionId;
import com.gemstone.gemfire.cache.TransactionListener;
import com.gemstone.gemfire.cache.TransactionWriter;
import com.gemstone.gemfire.cache.TransactionWriterException;
import com.sun.tools.javac.code.Attribute.Array;
/**
* @author David Turanski
*
*/
public class StubCacheTransactionMananger implements CacheTransactionManager {
private List<TransactionListener> listeners = new ArrayList<TransactionListener>();
private TransactionWriter writer;
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#begin()
*/
@Override
public void begin() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#commit()
*/
@Override
public void commit() throws CommitConflictException {
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#rollback()
*/
@Override
public void rollback() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#suspend()
*/
@Override
public TransactionId suspend() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#resume(com.gemstone.gemfire.cache.TransactionId)
*/
@Override
public void resume(TransactionId transactionId) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#isSuspended(com.gemstone.gemfire.cache.TransactionId)
*/
@Override
public boolean isSuspended(TransactionId transactionId) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#tryResume(com.gemstone.gemfire.cache.TransactionId)
*/
@Override
public boolean tryResume(TransactionId transactionId) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#tryResume(com.gemstone.gemfire.cache.TransactionId, long, java.util.concurrent.TimeUnit)
*/
@Override
public boolean tryResume(TransactionId transactionId, long time, TimeUnit unit) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#exists(com.gemstone.gemfire.cache.TransactionId)
*/
@Override
public boolean exists(TransactionId transactionId) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#exists()
*/
@Override
public boolean exists() {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#getTransactionId()
*/
@Override
public TransactionId getTransactionId() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#getListener()
*/
@Override
@Deprecated
public TransactionListener getListener() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#getListeners()
*/
@Override
public TransactionListener[] getListeners() {
return listeners.toArray(new TransactionListener[listeners.size()]);
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#setListener(com.gemstone.gemfire.cache.TransactionListener)
*/
@Override
@Deprecated
public TransactionListener setListener(TransactionListener newListener) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#addListener(com.gemstone.gemfire.cache.TransactionListener)
*/
@Override
public void addListener(TransactionListener aListener) {
this.listeners.add(aListener);
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#removeListener(com.gemstone.gemfire.cache.TransactionListener)
*/
@Override
public void removeListener(TransactionListener aListener) {
this.listeners.remove(aListener);
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#initListeners(com.gemstone.gemfire.cache.TransactionListener[])
*/
@Override
public void initListeners(TransactionListener[] newListeners) {
this.listeners = Arrays.asList(newListeners);
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#setWriter(com.gemstone.gemfire.cache.TransactionWriter)
*/
@Override
public void setWriter(TransactionWriter writer) {
this.writer = writer;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CacheTransactionManager#getWriter()
*/
@Override
public TransactionWriter getWriter() {
return this.writer;
}
}

View File

@@ -0,0 +1,249 @@
/*
* Copyright 2002-2012 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;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.gemstone.gemfire.cache.DiskStore;
import com.gemstone.gemfire.cache.DiskStoreFactory;
/**
* @author David Turanski
*
*/
public class StubDiskStore implements DiskStore, DiskStoreFactory {
static Map<String,DiskStore> diskStores = new HashMap<String,DiskStore>();
private String name;
private boolean autoCompact;
private int compactionThreshold;
private boolean allowForceCompaction;
private long maxOpLogSize;
private long timeInterval;
private int writeBufferSize;
private File[] diskDirs;
private int[] diskDirSizes;
private UUID diskStoreUUID;
private int queueSize;
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getName()
*/
@Override
public String getName() {
return this.name;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getAutoCompact()
*/
@Override
public boolean getAutoCompact() {
return this.autoCompact;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getCompactionThreshold()
*/
@Override
public int getCompactionThreshold() {
return this.compactionThreshold;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getAllowForceCompaction()
*/
@Override
public boolean getAllowForceCompaction() {
return this.allowForceCompaction;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getMaxOplogSize()
*/
@Override
public long getMaxOplogSize() {
return this.maxOpLogSize;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getTimeInterval()
*/
@Override
public long getTimeInterval() {
return this.timeInterval;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getWriteBufferSize()
*/
@Override
public int getWriteBufferSize() {
return this.writeBufferSize;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getDiskDirs()
*/
@Override
public File[] getDiskDirs() {
return this.diskDirs;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getDiskDirSizes()
*/
@Override
public int[] getDiskDirSizes() {
return this.diskDirSizes;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getDiskStoreUUID()
*/
@Override
public UUID getDiskStoreUUID() {
return this.diskStoreUUID;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#getQueueSize()
*/
@Override
public int getQueueSize() {
return this.queueSize;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#flush()
*/
@Override
public void flush() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#forceRoll()
*/
@Override
public void forceRoll() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStore#forceCompaction()
*/
@Override
public boolean forceCompaction() {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setAutoCompact(boolean)
*/
@Override
public DiskStoreFactory setAutoCompact(boolean isAutoCompact) {
this.autoCompact = isAutoCompact;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setCompactionThreshold(int)
*/
@Override
public DiskStoreFactory setCompactionThreshold(int compactionThreshold) {
this.compactionThreshold = compactionThreshold;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setAllowForceCompaction(boolean)
*/
@Override
public DiskStoreFactory setAllowForceCompaction(boolean allowForceCompaction) {
this.allowForceCompaction = allowForceCompaction;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setMaxOplogSize(long)
*/
@Override
public DiskStoreFactory setMaxOplogSize(long maxOplogSize) {
this.maxOpLogSize = maxOplogSize;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setTimeInterval(long)
*/
@Override
public DiskStoreFactory setTimeInterval(long timeInterval) {
this.timeInterval = timeInterval;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setWriteBufferSize(int)
*/
@Override
public DiskStoreFactory setWriteBufferSize(int writeBufferSize) {
this.writeBufferSize = writeBufferSize;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setQueueSize(int)
*/
@Override
public DiskStoreFactory setQueueSize(int queueSize) {
this.queueSize = queueSize;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setDiskDirs(java.io.File[])
*/
@Override
public DiskStoreFactory setDiskDirs(File[] diskDirs) {
this.diskDirs = diskDirs;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#setDiskDirsAndSizes(java.io.File[], int[])
*/
@Override
public DiskStoreFactory setDiskDirsAndSizes(File[] diskDirs, int[] diskDirSizes) {
this.diskDirs = diskDirs;
this.diskDirSizes = diskDirSizes;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.DiskStoreFactory#create(java.lang.String)
*/
@Override
public DiskStore create(String name) {
this.name = name;
diskStores.put(name,this);
return this;
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright 2002-2012 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;
import java.util.ArrayList;
import java.util.List;
import com.gemstone.gemfire.cache.wan.GatewayReceiver;
import com.gemstone.gemfire.cache.wan.GatewayReceiverFactory;
import com.gemstone.gemfire.cache.wan.GatewayTransportFilter;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author David Turanski
*
*/
public class StubGatewayReceiverFactory implements GatewayReceiverFactory {
private int startPort;
private int endPort;
private String bindAddress;
private List<GatewayTransportFilter> gatewayTransportFilters = new ArrayList<GatewayTransportFilter>();
private int maximumTimeBetweenPings;
private int socketBufferSize;
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.wan.GatewayReceiverFactory#setStartPort(int)
*/
@Override
public GatewayReceiverFactory setStartPort(int startPort) {
this.startPort = startPort;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.wan.GatewayReceiverFactory#setEndPort(int)
*/
@Override
public GatewayReceiverFactory setEndPort(int endPort) {
this.endPort = endPort;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.wan.GatewayReceiverFactory#setSocketBufferSize(int)
*/
@Override
public GatewayReceiverFactory setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.wan.GatewayReceiverFactory#setBindAddress(java.lang.String)
*/
@Override
public GatewayReceiverFactory setBindAddress(String address) {
this.bindAddress = address;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.wan.GatewayReceiverFactory#addGatewayTransportFilter(com.gemstone.gemfire.cache.wan.GatewayTransportFilter)
*/
@Override
public GatewayReceiverFactory addGatewayTransportFilter(GatewayTransportFilter filter) {
this.gatewayTransportFilters.add(filter);
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.wan.GatewayReceiverFactory#removeGatewayTransportFilter(com.gemstone.gemfire.cache.wan.GatewayTransportFilter)
*/
@Override
public GatewayReceiverFactory removeGatewayTransportFilter(GatewayTransportFilter filter) {
this.gatewayTransportFilters.remove(filter);
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.wan.GatewayReceiverFactory#setMaximumTimeBetweenPings(int)
*/
@Override
public GatewayReceiverFactory setMaximumTimeBetweenPings(int time) {
this.maximumTimeBetweenPings = time;
return this;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.wan.GatewayReceiverFactory#create()
*/
@Override
public GatewayReceiver create() {
GatewayReceiver gatewayReceiver = mock(GatewayReceiver.class);
when(gatewayReceiver.getBindAddress()).thenReturn(this.bindAddress);
when(gatewayReceiver.getEndPort()).thenReturn(this.endPort);
when(gatewayReceiver.getGatewayTransportFilters()).thenReturn(this.gatewayTransportFilters);
when(gatewayReceiver.getMaximumTimeBetweenPings()).thenReturn(this.maximumTimeBetweenPings);
when(gatewayReceiver.getSocketBufferSize()).thenReturn(this.socketBufferSize);
when(gatewayReceiver.getStartPort()).thenReturn(this.startPort);
return gatewayReceiver;
}
}

View File

@@ -0,0 +1,193 @@
/*
* Copyright 2002-2012 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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import com.gemstone.gemfire.cache.util.Gateway.OrderPolicy;
import com.gemstone.gemfire.cache.wan.GatewayEventFilter;
import com.gemstone.gemfire.cache.wan.GatewaySender;
import com.gemstone.gemfire.cache.wan.GatewaySenderFactory;
import com.gemstone.gemfire.cache.wan.GatewayTransportFilter;
/**
* @author David Turanski
*
*/
public class StubGatewaySenderFactory implements GatewaySenderFactory {
private int alertThreshold;
private boolean batchConflationEnabled;
private int batchSize;
private int batchTimeInterval;
private String diskStoreName;
private boolean diskSynchronous;
private int dispatcherThreads;
private boolean manualStart;
private int maxQueueMemory;
private OrderPolicy orderPolicy;
private boolean parallel;
private boolean persistenceEnabled;
private int socketBufferSize;
private int socketReadTimeout;
private List<GatewayEventFilter> eventFilters;
private List<GatewayTransportFilter> transportFilters;
private String name;
private int remoteSystemId;
public StubGatewaySenderFactory() {
this.eventFilters = new ArrayList<GatewayEventFilter>();
this.transportFilters = new ArrayList<GatewayTransportFilter>();
}
@Override
public GatewaySenderFactory addGatewayEventFilter(GatewayEventFilter filter) {
eventFilters.add(filter);
return this;
}
@Override
public GatewaySenderFactory addGatewayTransportFilter(GatewayTransportFilter filter) {
transportFilters.add(filter);
return this;
}
@Override
public GatewaySender create(String name, int remoteSystemId) {
GatewaySender gatewaySender = mock(GatewaySender.class);
this.name = name;
this.remoteSystemId = remoteSystemId;
when(gatewaySender.getId()).thenReturn(this.name);
when(gatewaySender.getRemoteDSId()).thenReturn(this.remoteSystemId);
when(gatewaySender.getAlertThreshold()).thenReturn(this.alertThreshold);
when(gatewaySender.getBatchSize()).thenReturn(this.batchSize);
when(gatewaySender.getBatchTimeInterval()).thenReturn(this.batchTimeInterval);
when(gatewaySender.getDiskStoreName()).thenReturn(this.diskStoreName);
when(gatewaySender.getDispatcherThreads()).thenReturn(this.dispatcherThreads);
when(gatewaySender.getGatewayEventFilters()).thenReturn(this.eventFilters);
when(gatewaySender.getGatewayTransportFilters()).thenReturn(this.transportFilters);
when(gatewaySender.getMaximumQueueMemory()).thenReturn(this.maxQueueMemory);
when(gatewaySender.getOrderPolicy()).thenReturn(this.orderPolicy);
when(gatewaySender.getSocketBufferSize()).thenReturn(this.socketBufferSize);
when(gatewaySender.getSocketReadTimeout()).thenReturn(this.socketReadTimeout);
when(gatewaySender.isManualStart()).thenReturn(this.manualStart);
when(gatewaySender.isBatchConflationEnabled()).thenReturn(this.batchConflationEnabled);
when(gatewaySender.isDiskSynchronous()).thenReturn(this.diskSynchronous);
when(gatewaySender.isParallel()).thenReturn(this.parallel);
when(gatewaySender.isPersistenceEnabled()).thenReturn(this.persistenceEnabled);
return gatewaySender;
}
@Override
public GatewaySenderFactory removeGatewayEventFilter(GatewayEventFilter filter) {
this.eventFilters.remove(filter);
return this;
}
@Override
public GatewaySenderFactory setAlertThreshold(int alertThreshold) {
this.alertThreshold = alertThreshold;
return this;
}
@Override
public GatewaySenderFactory setBatchConflationEnabled(boolean batchConflationEnabled) {
this.batchConflationEnabled = batchConflationEnabled;
return this;
}
@Override
public GatewaySenderFactory setBatchSize(int batchSize) {
this.batchSize = batchSize;
return this;
}
@Override
public GatewaySenderFactory setBatchTimeInterval(int batchTimeInterval) {
this.batchTimeInterval = batchTimeInterval;
return this;
}
@Override
public GatewaySenderFactory setDiskStoreName(String diskStoreName) {
this.diskStoreName = diskStoreName;
return this;
}
@Override
public GatewaySenderFactory setDiskSynchronous(boolean diskSynchronous) {
this.diskSynchronous = diskSynchronous;
return this;
}
@Override
public GatewaySenderFactory setDispatcherThreads(int dispatcherThreads) {
this.dispatcherThreads = dispatcherThreads;
return this;
}
@Override
public GatewaySenderFactory setManualStart(boolean manualStart) {
this.manualStart = manualStart;
return this;
}
@Override
public GatewaySenderFactory setMaximumQueueMemory(int maxQueueMemory) {
this.maxQueueMemory = maxQueueMemory;
return this;
}
@Override
public GatewaySenderFactory setOrderPolicy(OrderPolicy orderPolicy) {
this.orderPolicy = orderPolicy;
return this;
}
@Override
public GatewaySenderFactory setParallel(boolean parallel) {
this.parallel = parallel;
return this;
}
@Override
public GatewaySenderFactory setPersistenceEnabled(boolean persistenceEnabled) {
this.persistenceEnabled = persistenceEnabled;
return this;
}
@Override
public GatewaySenderFactory setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
return this;
}
@Override
public GatewaySenderFactory setSocketReadTimeout(int socketReadTimeout) {
this.socketReadTimeout = socketReadTimeout;
return this;
}
@Override
public GatewaySenderFactory removeGatewayTransportFilter(GatewayTransportFilter arg0) {
// TODO Auto-generated method stub
return null;
}
}