From 127b62e7220f94e07ed2e46e46b90e5017dde80d Mon Sep 17 00:00:00 2001 From: John Blum Date: Wed, 9 Mar 2016 18:43:06 -0800 Subject: [PATCH] SGF-416 - Avoid eager creation of a GemFire DistributedSystem in the PoolFactoryBean by creating a ClientCache first. --- .../data/gemfire/CacheFactoryBean.java | 874 +++++++------ .../data/gemfire/GemfireUtils.java | 66 +- .../client/ClientCacheFactoryBean.java | 535 ++++++-- .../client/ClientRegionFactoryBean.java | 71 +- .../data/gemfire/client/PoolAdapter.java | 180 +++ .../data/gemfire/client/PoolFactoryBean.java | 453 +++++-- .../DefaultableDelegatingPoolAdapter.java | 333 +++++ .../client/support/DelegatingPoolAdapter.java | 254 ++++ .../support/FactoryDefaultsPoolAdapter.java | 186 +++ .../data/gemfire/config/CacheParser.java | 23 +- .../gemfire/config/ClientCacheParser.java | 9 - ...ertiesSyncingBeanFactoryPostProcessor.java | 2 +- ...rRegistrationBeanFactoryPostProcessor.java | 17 +- .../data/gemfire/config/GemfireConstants.java | 2 +- .../config/GemfireDataSourceParser.java | 45 +- .../data/gemfire/config/PoolParser.java | 87 +- .../ContinuousQueryListenerContainer.java | 57 +- .../gemfire/support/ConnectionEndpoint.java | 12 + .../support/ConnectionEndpointList.java | 135 +- .../data/gemfire/util/CacheUtils.java | 129 ++ .../gemfire/util/DistributedSystemUtils.java | 9 +- .../data/gemfire/util/SpringUtils.java | 68 + .../data/gemfire/CacheFactoryBeanTest.java | 393 ++++-- .../data/gemfire/CacheIntegrationTest.java | 3 +- .../data/gemfire/ForkUtil.java | 3 - .../data/gemfire/GemfireUtilsTest.java | 122 +- ...leSupportFunctionBasedIntegrationTest.java | 4 + .../client/ClientCacheFactoryBeanTest.java | 1165 +++++++++++++---- .../data/gemfire/client/ClientCacheTest.java | 33 +- .../client/ClientReadyForEventsTest.java | 49 - .../client/ClientRegionFactoryBeanTest.java | 33 +- .../GemFireDataSourceIntegrationTest.java | 24 +- ...onfiguredGemFireServerIntegrationTest.java | 2 + .../gemfire/client/PoolFactoryBeanTest.java | 463 +++++-- ...orsAndServersPropertyPlaceholdersTest.java | 172 ++- .../support/DelegatingPoolAdapterTest.java | 266 ++++ .../FactoryDefaultsPoolAdapterTest.java | 145 ++ .../gemfire/config/CacheNamespaceTest.java | 11 +- .../config/ClientCacheNamespaceTest.java | 4 +- .../gemfire/config/ClientCacheParserTest.java | 29 +- ...esSyncingBeanFactoryPostProcessorTest.java | 1 + .../config/ClientRegionNamespaceTest.java | 3 +- ...istrationBeanFactoryPostProcessorTest.java | 44 +- .../gemfire/config/PoolNamespaceTest.java | 20 +- .../data/gemfire/config/PoolParserTest.java | 425 ++++-- .../FunctionExecutionClientCacheTests.java | 26 +- .../adapter/ContainerXmlSetupTest.java | 53 +- .../config/RepositoryClientRegionTests.java | 8 +- .../support/ClientCacheManagerTest.java | 22 +- .../support/ConnectionEndpointListTest.java | 258 +++- .../support/ConnectionEndpointTest.java | 54 +- .../test/GemfireTestBeanPostProcessor.java | 2 +- .../gemfire/test/MockCacheFactoryBean.java | 74 +- .../test/MockClientCacheFactoryBean.java | 80 +- .../gemfire/test/MockClientRegionFactory.java | 3 +- .../data/gemfire/test/StubCache.java | 4 +- .../data/gemfire/basic-cache.xml | 4 +- ...lientCacheVariableLocatorsTest-context.xml | 2 +- ...ClientCacheVariableServersTest-context.xml | 4 +- ...mFireDataSourceIntegrationTest-context.xml | 10 +- ...taSourceIntegrationTest-server-context.xml | 16 +- ...erversPropertyPlaceholdersTest-context.xml | 13 +- .../gemfire/client/client-cache-no-close.xml | 5 +- .../client/client-cache-ready-for-events.xml | 26 - .../data/gemfire/client/client-cache.xml | 8 +- ...-with-region-using-cache-loader-writer.xml | 4 - .../ClientCacheNamespaceTest-context.xml | 6 - ...ListenerContainerNamespaceTest-context.xml | 5 +- .../data/gemfire/config/client-ns.xml | 8 +- .../data/gemfire/config/pool-ns.xml | 2 - ...nctionExecutionIntegrationTest-context.xml | 2 +- ...ctionExecutionCacheClientTests-context.xml | 27 +- .../FunctionIntegrationTests-context.xml | 10 +- .../data/gemfire/listener/container.xml | 6 +- .../support/cache-manager-client-cache.xml | 28 +- 75 files changed, 5797 insertions(+), 1934 deletions(-) create mode 100644 src/main/java/org/springframework/data/gemfire/client/PoolAdapter.java create mode 100644 src/main/java/org/springframework/data/gemfire/client/support/DefaultableDelegatingPoolAdapter.java create mode 100644 src/main/java/org/springframework/data/gemfire/client/support/DelegatingPoolAdapter.java create mode 100644 src/main/java/org/springframework/data/gemfire/client/support/FactoryDefaultsPoolAdapter.java create mode 100644 src/main/java/org/springframework/data/gemfire/util/CacheUtils.java create mode 100644 src/main/java/org/springframework/data/gemfire/util/SpringUtils.java delete mode 100644 src/test/java/org/springframework/data/gemfire/client/ClientReadyForEventsTest.java create mode 100644 src/test/java/org/springframework/data/gemfire/client/support/DelegatingPoolAdapterTest.java create mode 100644 src/test/java/org/springframework/data/gemfire/client/support/FactoryDefaultsPoolAdapterTest.java delete mode 100644 src/test/resources/org/springframework/data/gemfire/client/client-cache-ready-for-events.xml diff --git a/src/main/java/org/springframework/data/gemfire/CacheFactoryBean.java b/src/main/java/org/springframework/data/gemfire/CacheFactoryBean.java index f4feedb0..806ef71e 100644 --- a/src/main/java/org/springframework/data/gemfire/CacheFactoryBean.java +++ b/src/main/java/org/springframework/data/gemfire/CacheFactoryBean.java @@ -33,11 +33,13 @@ import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.Phased; import org.springframework.core.io.Resource; import org.springframework.dao.DataAccessException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.data.gemfire.util.CollectionUtils; import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; import com.gemstone.gemfire.GemFireCheckedException; import com.gemstone.gemfire.GemFireException; @@ -75,137 +77,67 @@ import com.gemstone.gemfire.pdx.PdxSerializer; * @see org.springframework.beans.factory.FactoryBean * @see org.springframework.beans.factory.InitializingBean * @see org.springframework.beans.factory.DisposableBean + * @see org.springframework.context.Phased * @see org.springframework.dao.support.PersistenceExceptionTranslator * @see com.gemstone.gemfire.cache.Cache * @see com.gemstone.gemfire.cache.CacheFactory - * @see com.gemstone.gemfire.cache.DynamicRegionFactory * @see com.gemstone.gemfire.cache.GemFireCache * @see com.gemstone.gemfire.distributed.DistributedMember * @see com.gemstone.gemfire.distributed.DistributedSystem */ @SuppressWarnings("unused") public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, BeanNameAware, FactoryBean, - InitializingBean, DisposableBean, PersistenceExceptionTranslator { + Phased, InitializingBean, DisposableBean, PersistenceExceptionTranslator { - protected boolean close = true; - protected boolean useBeanFactoryLocator = false; + private boolean close = true; + private boolean useBeanFactoryLocator = false; + + private int phase = -1; protected final Log log = LogFactory.getLog(getClass()); - protected BeanFactory beanFactory; + private BeanFactory beanFactory; - protected Boolean copyOnRead; - protected Boolean enableAutoReconnect; - protected Boolean pdxIgnoreUnreadFields; - protected Boolean pdxPersistent; - protected Boolean pdxReadSerialized; - protected Boolean useClusterConfiguration; + private Boolean copyOnRead; + private Boolean enableAutoReconnect; + private Boolean pdxIgnoreUnreadFields; + private Boolean pdxPersistent; + private Boolean pdxReadSerialized; + private Boolean useClusterConfiguration; - protected Cache cache; + private Cache cache; - protected ClassLoader beanClassLoader; + private ClassLoader beanClassLoader; - protected DynamicRegionSupport dynamicRegionSupport; + private DynamicRegionSupport dynamicRegionSupport; - protected Float criticalHeapPercentage; - protected Float evictionHeapPercentage; + private Float criticalHeapPercentage; + private Float evictionHeapPercentage; protected GemfireBeanFactoryLocator beanFactoryLocator; - protected Integer lockLease; - protected Integer lockTimeout; - protected Integer messageSyncInterval; - protected Integer searchTimeout; + private Integer lockLease; + private Integer lockTimeout; + private Integer messageSyncInterval; + private Integer searchTimeout; - protected List jndiDataSources; + private List jndiDataSources; - protected List transactionListeners; + private List transactionListeners; // Declared with type 'Object' for backward compatibility - protected Object gatewayConflictResolver; - protected Object pdxSerializer; + private Object gatewayConflictResolver; + private Object pdxSerializer; - protected Properties properties; + private Properties properties; - protected Resource cacheXml; + private Resource cacheXml; - protected String beanName; + private String beanName; private String cacheResolutionMessagePrefix; - protected String pdxDiskStoreName; + private String pdxDiskStoreName; - protected TransactionWriter transactionWriter; - - public static class DynamicRegionSupport { - - private Boolean persistent = Boolean.TRUE; - private Boolean registerInterest = Boolean.TRUE; - - private String diskDirectory; - private String poolName; - - public String getDiskDir() { - return diskDirectory; - } - - public void setDiskDir(String diskDirectory) { - this.diskDirectory = diskDirectory; - } - - public Boolean getPersistent() { - return persistent; - } - - public void setPersistent(Boolean persistent) { - this.persistent = persistent; - } - - public String getPoolName() { - return poolName; - } - - public void setPoolName(String poolName) { - this.poolName = poolName; - } - - public Boolean getRegisterInterest() { - return registerInterest; - } - - public void setRegisterInterest(Boolean registerInterest) { - this.registerInterest = registerInterest; - } - - public void initializeDynamicRegionFactory() { - File localDiskDirectory = (this.diskDirectory == null ? null : new File(this.diskDirectory)); - - DynamicRegionFactory.Config config = new DynamicRegionFactory.Config(localDiskDirectory, poolName, - persistent, registerInterest); - - DynamicRegionFactory.get().open(config); - } - } - - public static class JndiDataSource { - - private List props; - private Map attributes; - - public Map getAttributes() { - return attributes; - } - - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - - public List getProps() { - return props; - } - - public void setProps(List props) { - this.props = props; - } - } + private TransactionWriter transactionWriter; /* * (non-Javadoc) @@ -213,12 +145,11 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, */ @Override public void afterPropertiesSet() throws Exception { - postProcessPropertiesBeforeInitialization(getProperties()); - init(); + postProcessBeforeCacheInitialization(resolveProperties()); } /* (non-Javadoc) */ - protected void postProcessPropertiesBeforeInitialization(Properties gemfireProperties) { + protected void postProcessBeforeCacheInitialization(Properties gemfireProperties) { if (GemfireUtils.isGemfireVersion8OrAbove()) { gemfireProperties.setProperty("disable-auto-reconnect", String.valueOf( !Boolean.TRUE.equals(getEnableAutoReconnect()))); @@ -228,7 +159,27 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, } /* (non-Javadoc) */ - private Cache init() throws Exception { + protected void setCache(Cache cache) { + this.cache = cache; + } + + /* (non-Javadoc) */ + @SuppressWarnings("unchecked") + protected T getCache() { + return (T) cache; + } + + /* + * (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ + @Override + public Cache getObject() throws Exception { + return (cache != null ? cache : init()); + } + + /* (non-Javadoc) */ + Cache init() throws Exception { initBeanFactoryLocator(); final ClassLoader currentThreadContextClassLoader = Thread.currentThread().getContextClassLoader(); @@ -237,7 +188,7 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, // use bean ClassLoader to load Spring configured, GemFire Declarable classes Thread.currentThread().setContextClassLoader(beanClassLoader); - this.cache = postProcess(resolveCache()); + cache = postProcess(resolveCache()); DistributedSystem system = cache.getDistributedSystem(); @@ -321,7 +272,7 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, * @see #getProperties() */ protected Properties resolveProperties() { - return getProperties(); + return (properties != null ? properties : (properties = new Properties())); } /** @@ -346,11 +297,22 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, * @see #isPdxOptionsSpecified() */ protected Object prepareFactory(Object factory) { - if (isPdxOptionsSpecified()) { - CacheFactory cacheFactory = (CacheFactory) factory; + return initializePdx((CacheFactory) factory); + } + /** + * Initialize the PDX settings on the {@link CacheFactory}. + * + * @param cacheFactory the GemFire {@link CacheFactory} used to configure and create a GemFire {@link Cache}. + * @see com.gemstone.gemfire.cache.CacheFactory + */ + CacheFactory initializePdx(CacheFactory cacheFactory) { + if (isPdxOptionsSpecified()) { if (pdxSerializer != null) { - Assert.isAssignable(PdxSerializer.class, pdxSerializer.getClass(), "Invalid pdx serializer used"); + Assert.isInstanceOf(PdxSerializer.class, pdxSerializer, + String.format("[%1$s] of type [%2$s] is not a PdxSerializer", pdxSerializer, + ObjectUtils.nullSafeClassName(pdxSerializer))); + cacheFactory.setPdxSerializer((PdxSerializer) pdxSerializer); } if (pdxDiskStoreName != null) { @@ -367,7 +329,7 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, } } - return factory; + return cacheFactory; } /** @@ -512,10 +474,43 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, } } + /* (non-Javadoc) */ protected void close(GemFireCache cache) { cache.close(); } + /* + * (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ + @Override + public Class getObjectType() { + return (cache != null ? cache.getClass() : Cache.class); + } + + /* (non-Javadoc) */ + protected void setPhase(int phase) { + this.phase = phase; + } + + /* + * (non-Javadoc) + * @see org.springframework.context.Phased#getPhase() + */ + @Override + public int getPhase() { + return phase; + } + + /* + * (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#isSingleton() + */ + @Override + public boolean isSingleton() { + return true; + } + @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { if (e instanceof GemFireException) { @@ -541,249 +536,21 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return null; } + /** + * Sets a reference to the {@link ClassLoader} used to load and create bean classes in the Spring container. + * + * @param classLoader the {@link ClassLoader} used to load and create beans in the Spring container. + * @see java.lang.ClassLoader + */ @Override public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - } - - @Override - public void setBeanName(String name) { - this.beanName = name; - } - /** - * Sets the Cache configuration. + * Gets a reference to the {@link ClassLoader} used to load and create bean classes in the Spring container. * - * @param cacheXml the cache.xml Resource used to initialize the GemFire Cache. - * @see org.springframework.core.io.Resource - */ - public void setCacheXml(Resource cacheXml) { - this.cacheXml = cacheXml; - } - - /** - * Sets the cache properties. - * - * @param properties the properties to set - */ - public void setProperties(Properties properties) { - this.properties = properties; - } - - /** - * Indicates whether a bean factory locator is enabled (default) for this - * cache definition or not. The locator stores the enclosing bean factory - * reference to allow auto-wiring of Spring beans into GemFire managed - * classes. Usually disabled when the same cache is used in multiple - * application context/bean factories inside the same VM. - * - * @param usage true if the bean factory locator is used underneath or not - */ - public void setUseBeanFactoryLocator(boolean usage) { - this.useBeanFactoryLocator = usage; - } - - /** - * Set whether the Cache should be closed. - * - * @param close set to false if destroy() should not close the cache - */ - public void setClose(boolean close) { - this.close = close; - } - - /** - * Set the copyOnRead attribute of the Cache. - * - * @param copyOnRead a boolean value indicating whether the object stored in the Cache is copied on gets. - */ - public void setCopyOnRead(Boolean copyOnRead) { - this.copyOnRead = copyOnRead; - } - - /** - * Set the Cache's critical heap percentage attribute. - * - * @param criticalHeapPercentage floating point value indicating the critical heap percentage. - */ - public void setCriticalHeapPercentage(Float criticalHeapPercentage) { - this.criticalHeapPercentage = criticalHeapPercentage; - } - - /** - * Sets an instance of the DynamicRegionSupport to support Dynamic Regions in this GemFire Cache. - * - * @param dynamicRegionSupport the DynamicRegionSupport class to setup Dynamic Regions in this Cache. - */ - public void setDynamicRegionSupport(DynamicRegionSupport dynamicRegionSupport) { - this.dynamicRegionSupport = dynamicRegionSupport; - } - - /** - * Controls whether auto-reconnect functionality introduced in GemFire 8 is enabled or not. - * - * @param enableAutoReconnect a boolean value to enable/disable auto-reconnect functionality. - * @since GemFire 8.0 - */ - public void setEnableAutoReconnect(Boolean enableAutoReconnect) { - this.enableAutoReconnect = enableAutoReconnect; - } - - /** - * Set the Cache's eviction heap percentage attribute. - * - * @param evictionHeapPercentage float-point value indicating the Cache's heap use percentage to trigger eviction. - */ - public void setEvictionHeapPercentage(Float evictionHeapPercentage) { - this.evictionHeapPercentage = evictionHeapPercentage; - } - - /** - * Requires GemFire 7.0 or higher - * @param gatewayConflictResolver defined as Object in the signature for backward - * compatibility with Gemfire 6 compatibility. This must be an instance of - * {@link com.gemstone.gemfire.cache.util.GatewayConflictResolver} - */ - public void setGatewayConflictResolver(Object gatewayConflictResolver) { - this.gatewayConflictResolver = gatewayConflictResolver; - } - - /** - * @param jndiDataSources the list of configured JndiDataSources to use with this Cache. - */ - public void setJndiDataSources(List jndiDataSources) { - this.jndiDataSources = jndiDataSources; - } - - /** - * Sets the number of seconds for implicit and explicit object lock leases to timeout. - * - * @param lockLease an integer value indicating the object lock lease timeout. - */ - public void setLockLease(Integer lockLease) { - this.lockLease = lockLease; - } - - /** - * Sets the number of seconds in which the implicit object lock request will timeout. - * - * @param lockTimeout an integer value specifying the object lock request timeout. - */ - public void setLockTimeout(Integer lockTimeout) { - this.lockTimeout = lockTimeout; - } - - /** - * Set for client subscription queue synchronization when this member acts as a server to clients - * and server redundancy is used. Sets the frequency (in seconds) at which the primary server sends messages - * to its secondary servers to remove queued events that have already been processed by the clients. - * - * @param messageSyncInterval an integer value specifying the number of seconds in which the primary server - * sends messages to secondary servers. - */ - public void setMessageSyncInterval(Integer messageSyncInterval) { - this.messageSyncInterval = messageSyncInterval; - } - - /** - * Sets the {@link PdxSerializable} for this cache. Applicable on GemFire - * 6.6 or higher. The argument is of type object for compatibility with - * GemFire 6.5. - * - * @param serializer pdx serializer configured for this cache. - */ - public void setPdxSerializer(Object serializer) { - this.pdxSerializer = serializer; - } - - /** - * Sets the object preference to PdxInstance. Applicable on GemFire 6.6 or higher. - * - * @param pdxReadSerialized a boolean value indicating the PDX instance should be returned from Region.get(key) - * when available. - */ - public void setPdxReadSerialized(Boolean pdxReadSerialized) { - this.pdxReadSerialized = pdxReadSerialized; - } - - /** - * Controls whether type metadata for PDX objects is persisted to disk. Applicable on GemFire 6.6 or higher. - * - * @param pdxPersistent a boolean value indicating that PDX type meta-data should be persisted to disk. - */ - public void setPdxPersistent(Boolean pdxPersistent) { - this.pdxPersistent = pdxPersistent; - } - - /** - * Controls whether pdx ignores fields that were unread during - * deserialization. Applicable on GemFire 6.6 or higher. - * - * @param pdxIgnoreUnreadFields the pdxIgnoreUnreadFields to set - */ - public void setPdxIgnoreUnreadFields(Boolean pdxIgnoreUnreadFields) { - this.pdxIgnoreUnreadFields = pdxIgnoreUnreadFields; - } - - /** - * Set the disk store that is used for PDX meta data. Applicable on GemFire - * 6.6 or higher. - * - * @param pdxDiskStoreName the pdxDiskStoreName to set - */ - public void setPdxDiskStoreName(String pdxDiskStoreName) { - this.pdxDiskStoreName = pdxDiskStoreName; - } - - /** - * Set the number of seconds a netSearch operation can wait for data before timing out. - * - * @param searchTimeout an integer value indicating the netSearch timeout value. - */ - public void setSearchTimeout(Integer searchTimeout) { - this.searchTimeout = searchTimeout; - } - - /** - * Sets the list of TransactionListeners used to configure the Cache to receive transaction events after - * the transaction is processed (committed, rolled back). - * - * @param transactionListeners the list of GemFire TransactionListeners listening for transaction events. - * @see com.gemstone.gemfire.cache.TransactionListener - */ - public void setTransactionListeners(List transactionListeners) { - this.transactionListeners = transactionListeners; - } - - /** - * Sets the TransactionWriter used to configure the Cache for handling transaction events, such as to veto - * the transaction or update an external DB before the commit. - * - * @param transactionWriter the GemFire TransactionWriter callback receiving transaction events. - * @see com.gemstone.gemfire.cache.TransactionWriter - */ - public void setTransactionWriter(TransactionWriter transactionWriter) { - this.transactionWriter = transactionWriter; - } - - /** - * Sets the state of the use-shared-configuration GemFire distribution config setting. - * - * @param useSharedConfiguration a boolean value to set the use-shared-configuration GemFire distribution property. - */ - public void setUseClusterConfiguration(Boolean useSharedConfiguration) { - this.useClusterConfiguration = useSharedConfiguration; - } - - /** - * Gets a reference to the JRE ClassLoader used to load and create bean classes in the Spring container. - * - * @return the JRE ClassLoader used to load and created beans in the Spring container. + * @return the {@link ClassLoader} used to load and create beans in the Spring container. * @see java.lang.ClassLoader */ public ClassLoader getBeanClassLoader() { @@ -791,10 +558,23 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, } /** - * Gets a reference to the Spring BeanFactory that created this GemFire Cache FactoryBean. + * Sets a reference to the Spring {@link BeanFactory} containing this GemFire {@link Cache} {@link FactoryBean}. * - * @return a reference to the Spring BeanFactory. + * @param beanFactory a reference to the Spring {@link BeanFactory}. * @see org.springframework.beans.factory.BeanFactory + * @see #getBeanFactory() + */ + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + } + + /** + * Gets a reference to the Spring BeanFactory containing this GemFire {@link Cache} {@link FactoryBean}. + * + * @return a reference to the Spring {@link BeanFactory}. + * @see org.springframework.beans.factory.BeanFactory + * @see #setBeanFactory(BeanFactory) */ public BeanFactory getBeanFactory() { return beanFactory; @@ -806,18 +586,38 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, } /** - * Gets the Spring bean name for the GemFire Cache. + * Sets the Spring bean name for this GemFire {@link Cache}. * - * @return a String value indicating the Spring container bean name for the GemFire Cache object/component. + * @param name a String value indicating the Spring container bean name for the GemFire {@link Cache} object. + */ + @Override + public void setBeanName(String name) { + this.beanName = name; + } + + /** + * Gets the Spring bean name for this GemFire {@link Cache}. + * + * @return a String value indicating the Spring container bean name for the GemFire {@link Cache} object. */ public String getBeanName() { return beanName; } /** - * Gets a reference to the GemFire native cache.xml file as a Spring Resource. + * Sets the {@link Cache} configuration meta-data. * - * @return the a reference to the GemFire native cache.xml as a Spring Resource. + * @param cacheXml the cache.xml {@link Resource} used to initialize the GemFire {@link Cache}. + * @see org.springframework.core.io.Resource + */ + public void setCacheXml(Resource cacheXml) { + this.cacheXml = cacheXml; + } + + /** + * Gets a reference to the GemFire native cache.xml file as a Spring {@link Resource}. + * + * @return the a reference to the GemFire native cache.xml as a Spring {@link Resource}. * @see org.springframework.core.io.Resource */ public Resource getCacheXml() { @@ -845,6 +645,15 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, } } + /** + * Sets the cache properties. + * + * @param properties the properties to set + */ + public void setProperties(Properties properties) { + this.properties = properties; + } + /** * Gets a reference to the GemFire System Properties. * @@ -852,22 +661,32 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, * @see java.util.Properties */ public Properties getProperties() { - return (properties != null ? properties : (properties = new Properties())); + return properties; } - @Override - public Cache getObject() throws Exception { - return cache; + /** + * Set whether the Cache should be closed. + * + * @param close set to false if destroy() should not close the cache + */ + public void setClose(boolean close) { + this.close = close; } - @Override - public Class getObjectType() { - return (cache != null ? cache.getClass() : Cache.class); + /** + * @return close. + */ + public Boolean getClose() { + return close; } - @Override - public boolean isSingleton() { - return true; + /** + * Set the copyOnRead attribute of the Cache. + * + * @param copyOnRead a boolean value indicating whether the object stored in the Cache is copied on gets. + */ + public void setCopyOnRead(Boolean copyOnRead) { + this.copyOnRead = copyOnRead; } /** @@ -877,6 +696,15 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return copyOnRead; } + /** + * Set the Cache's critical heap percentage attribute. + * + * @param criticalHeapPercentage floating point value indicating the critical heap percentage. + */ + public void setCriticalHeapPercentage(Float criticalHeapPercentage) { + this.criticalHeapPercentage = criticalHeapPercentage; + } + /** * @return the criticalHeapPercentage */ @@ -884,6 +712,15 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return criticalHeapPercentage; } + /** + * Sets an instance of the DynamicRegionSupport to support Dynamic Regions in this GemFire Cache. + * + * @param dynamicRegionSupport the DynamicRegionSupport class to setup Dynamic Regions in this Cache. + */ + public void setDynamicRegionSupport(DynamicRegionSupport dynamicRegionSupport) { + this.dynamicRegionSupport = dynamicRegionSupport; + } + /** * @return the dynamicRegionSupport */ @@ -891,6 +728,16 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return dynamicRegionSupport; } + /** + * Controls whether auto-reconnect functionality introduced in GemFire 8 is enabled or not. + * + * @param enableAutoReconnect a boolean value to enable/disable auto-reconnect functionality. + * @since GemFire 8.0 + */ + public void setEnableAutoReconnect(Boolean enableAutoReconnect) { + this.enableAutoReconnect = enableAutoReconnect; + } + /** * Gets the value for the auto-reconnect setting. * @@ -901,6 +748,15 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return enableAutoReconnect; } + /** + * Set the Cache's eviction heap percentage attribute. + * + * @param evictionHeapPercentage float-point value indicating the Cache's heap use percentage to trigger eviction. + */ + public void setEvictionHeapPercentage(Float evictionHeapPercentage) { + this.evictionHeapPercentage = evictionHeapPercentage; + } + /** * @return the evictionHeapPercentage */ @@ -908,6 +764,16 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return evictionHeapPercentage; } + /** + * Requires GemFire 7.0 or higher + * @param gatewayConflictResolver defined as Object in the signature for backward + * compatibility with Gemfire 6 compatibility. This must be an instance of + * {@link com.gemstone.gemfire.cache.util.GatewayConflictResolver} + */ + public void setGatewayConflictResolver(Object gatewayConflictResolver) { + this.gatewayConflictResolver = gatewayConflictResolver; + } + /** * @return the gatewayConflictResolver */ @@ -915,6 +781,13 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return gatewayConflictResolver; } + /** + * @param jndiDataSources the list of configured JndiDataSources to use with this Cache. + */ + public void setJndiDataSources(List jndiDataSources) { + this.jndiDataSources = jndiDataSources; + } + /** * @return the list of configured JndiDataSources. */ @@ -923,38 +796,12 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, } /** - * @return the pdxSerializer + * Sets the number of seconds for implicit and explicit object lock leases to timeout. + * + * @param lockLease an integer value indicating the object lock lease timeout. */ - public Object getPdxSerializer() { - return pdxSerializer; - } - - /** - * @return the pdxReadSerialized - */ - public Boolean getPdxReadSerialized() { - return pdxReadSerialized; - } - - /** - * @return the pdxPersistent - */ - public Boolean getPdxPersistent() { - return pdxPersistent; - } - - /** - * @return the pdxIgnoreUnreadFields - */ - public Boolean getPdxIgnoreUnreadFields() { - return pdxIgnoreUnreadFields; - } - - /** - * @return the pdxDiskStoreName - */ - public String getPdxDiskStoreName() { - return pdxDiskStoreName; + public void setLockLease(Integer lockLease) { + this.lockLease = lockLease; } /** @@ -964,6 +811,15 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return lockLease; } + /** + * Sets the number of seconds in which the implicit object lock request will timeout. + * + * @param lockTimeout an integer value specifying the object lock request timeout. + */ + public void setLockTimeout(Integer lockTimeout) { + this.lockTimeout = lockTimeout; + } + /** * @return the lockTimeout */ @@ -971,6 +827,18 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return lockTimeout; } + /** + * Set for client subscription queue synchronization when this member acts as a server to clients + * and server redundancy is used. Sets the frequency (in seconds) at which the primary server sends messages + * to its secondary servers to remove queued events that have already been processed by the clients. + * + * @param messageSyncInterval an integer value specifying the number of seconds in which the primary server + * sends messages to secondary servers. + */ + public void setMessageSyncInterval(Integer messageSyncInterval) { + this.messageSyncInterval = messageSyncInterval; + } + /** * @return the messageSyncInterval */ @@ -978,6 +846,100 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return messageSyncInterval; } + /** + * Set the disk store that is used for PDX meta data. Applicable on GemFire + * 6.6 or higher. + * + * @param pdxDiskStoreName the pdxDiskStoreName to set + */ + public void setPdxDiskStoreName(String pdxDiskStoreName) { + this.pdxDiskStoreName = pdxDiskStoreName; + } + + /** + * @return the pdxDiskStoreName + */ + public String getPdxDiskStoreName() { + return pdxDiskStoreName; + } + + /** + * Controls whether pdx ignores fields that were unread during + * deserialization. Applicable on GemFire 6.6 or higher. + * + * @param pdxIgnoreUnreadFields the pdxIgnoreUnreadFields to set + */ + public void setPdxIgnoreUnreadFields(Boolean pdxIgnoreUnreadFields) { + this.pdxIgnoreUnreadFields = pdxIgnoreUnreadFields; + } + + /** + * @return the pdxIgnoreUnreadFields + */ + public Boolean getPdxIgnoreUnreadFields() { + return pdxIgnoreUnreadFields; + } + + /** + * Controls whether type metadata for PDX objects is persisted to disk. Applicable on GemFire 6.6 or higher. + * + * @param pdxPersistent a boolean value indicating that PDX type meta-data should be persisted to disk. + */ + public void setPdxPersistent(Boolean pdxPersistent) { + this.pdxPersistent = pdxPersistent; + } + + /** + * @return the pdxPersistent + */ + public Boolean getPdxPersistent() { + return pdxPersistent; + } + + /** + * Sets the object preference to PdxInstance. Applicable on GemFire 6.6 or higher. + * + * @param pdxReadSerialized a boolean value indicating the PDX instance should be returned from Region.get(key) + * when available. + */ + public void setPdxReadSerialized(Boolean pdxReadSerialized) { + this.pdxReadSerialized = pdxReadSerialized; + } + + /** + * @return the pdxReadSerialized + */ + public Boolean getPdxReadSerialized() { + return pdxReadSerialized; + } + + /** + * Sets the {@link PdxSerializable} for this cache. Applicable on GemFire + * 6.6 or higher. The argument is of type object for compatibility with + * GemFire 6.5. + * + * @param serializer pdx serializer configured for this cache. + */ + public void setPdxSerializer(Object serializer) { + this.pdxSerializer = serializer; + } + + /** + * @return the pdxSerializer + */ + public Object getPdxSerializer() { + return pdxSerializer; + } + + /** + * Set the number of seconds a netSearch operation can wait for data before timing out. + * + * @param searchTimeout an integer value indicating the netSearch timeout value. + */ + public void setSearchTimeout(Integer searchTimeout) { + this.searchTimeout = searchTimeout; + } + /** * @return the searchTimeout */ @@ -985,6 +947,17 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return searchTimeout; } + /** + * Sets the list of TransactionListeners used to configure the Cache to receive transaction events after + * the transaction is processed (committed, rolled back). + * + * @param transactionListeners the list of GemFire TransactionListeners listening for transaction events. + * @see com.gemstone.gemfire.cache.TransactionListener + */ + public void setTransactionListeners(List transactionListeners) { + this.transactionListeners = transactionListeners; + } + /** * @return the transactionListeners */ @@ -992,6 +965,17 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return transactionListeners; } + /** + * Sets the TransactionWriter used to configure the Cache for handling transaction events, such as to veto + * the transaction or update an external DB before the commit. + * + * @param transactionWriter the GemFire TransactionWriter callback receiving transaction events. + * @see com.gemstone.gemfire.cache.TransactionWriter + */ + public void setTransactionWriter(TransactionWriter transactionWriter) { + this.transactionWriter = transactionWriter; + } + /** * @return the transactionWriter */ @@ -1000,7 +984,35 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, } /** - * Gets the value fo the use-shared-configuration GemFire setting. + * Indicates whether a bean factory locator is enabled for this cache definition or not. The locator stores + * the enclosing bean factory reference to allow auto-wiring of Spring beans into GemFire managed classes. + * Usually disabled when the same cache is used in multiple application context/bean factories inside + * the same VM. + * + * @param usage true if the bean factory locator is to be used underneath the hood. + */ + public void setUseBeanFactoryLocator(boolean usage) { + this.useBeanFactoryLocator = usage; + } + + /** + * @return useBeanFactoryLocator + */ + public boolean isUseBeanFactoryLocator() { + return useBeanFactoryLocator; + } + + /** + * Sets the state of the use-shared-configuration GemFire distribution config setting. + * + * @param useSharedConfiguration a boolean value to set the use-shared-configuration GemFire distribution property. + */ + public void setUseClusterConfiguration(Boolean useSharedConfiguration) { + this.useClusterConfiguration = useSharedConfiguration; + } + + /** + * Gets the value of the use-shared-configuration GemFire configuration setting. * * @return a boolean value indicating whether shared configuration use has been enabled or not. */ @@ -1008,4 +1020,76 @@ public class CacheFactoryBean implements BeanClassLoaderAware, BeanFactoryAware, return this.useClusterConfiguration; } + public static class DynamicRegionSupport { + + private Boolean persistent = Boolean.TRUE; + private Boolean registerInterest = Boolean.TRUE; + + private String diskDirectory; + private String poolName; + + public String getDiskDir() { + return diskDirectory; + } + + public void setDiskDir(String diskDirectory) { + this.diskDirectory = diskDirectory; + } + + public Boolean getPersistent() { + return persistent; + } + + public void setPersistent(Boolean persistent) { + this.persistent = persistent; + } + + public String getPoolName() { + return poolName; + } + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + public Boolean getRegisterInterest() { + return registerInterest; + } + + public void setRegisterInterest(Boolean registerInterest) { + this.registerInterest = registerInterest; + } + + public void initializeDynamicRegionFactory() { + File localDiskDirectory = (this.diskDirectory == null ? null : new File(this.diskDirectory)); + + DynamicRegionFactory.Config config = new DynamicRegionFactory.Config(localDiskDirectory, poolName, + persistent, registerInterest); + + DynamicRegionFactory.get().open(config); + } + } + + public static class JndiDataSource { + + private List props; + private Map attributes; + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + public List getProps() { + return props; + } + + public void setProps(List props) { + this.props = props; + } + } + } diff --git a/src/main/java/org/springframework/data/gemfire/GemfireUtils.java b/src/main/java/org/springframework/data/gemfire/GemfireUtils.java index 214ae037..0162a2fe 100644 --- a/src/main/java/org/springframework/data/gemfire/GemfireUtils.java +++ b/src/main/java/org/springframework/data/gemfire/GemfireUtils.java @@ -18,17 +18,11 @@ package org.springframework.data.gemfire; import java.util.concurrent.ConcurrentMap; -import org.springframework.data.gemfire.util.DistributedSystemUtils; +import org.springframework.data.gemfire.util.CacheUtils; import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; -import com.gemstone.gemfire.cache.Cache; -import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.client.ClientCache; -import com.gemstone.gemfire.cache.client.ClientCacheFactory; -import com.gemstone.gemfire.distributed.DistributedSystem; /** * GemfireUtils is an abstract utility class encapsulating common functionality to access features and capabilities @@ -36,72 +30,22 @@ import com.gemstone.gemfire.distributed.DistributedSystem; * * @author John Blum * @see org.springframework.data.gemfire.util.DistributedSystemUtils - * @see com.gemstone.gemfire.cache.Cache * @see com.gemstone.gemfire.cache.CacheFactory * @see com.gemstone.gemfire.cache.Region - * @see com.gemstone.gemfire.cache.client.ClientCache - * @see com.gemstone.gemfire.cache.client.ClientCacheFactory - * @see com.gemstone.gemfire.distributed.DistributedSystem * @since 1.3.3 */ @SuppressWarnings("unused") -public abstract class GemfireUtils extends DistributedSystemUtils { +public abstract class GemfireUtils extends CacheUtils { public final static String GEMFIRE_VERSION = CacheFactory.getVersion(); - public static boolean isDurable(ClientCache clientCache) { - DistributedSystem distributedSystem = getDistributedSystem(clientCache); - - // NOTE technically the following code snippet would be more useful/valuable but is not "testable"! - //((InternalDistributedSystem) distributedSystem).getConfig().getDurableClientId(); - - return (isConnected(distributedSystem) && StringUtils.hasText(distributedSystem.getProperties() - .getProperty(DURABLE_CLIENT_ID_PROPERTY_NAME, null))); - } - - public static boolean closeCache() { - try { - CacheFactory.getAnyInstance().close(); - return true; - } - catch (Exception ignore) { - return false; - } - } - - public static boolean closeClientCache() { - try { - ClientCacheFactory.getAnyInstance().close(); - return true; - } - catch (Exception ignore) { - return false; - } - } - - public static Cache getCache() { - try { - return CacheFactory.getAnyInstance(); - } - catch (CacheClosedException ignore) { - return null; - } - } - - public static ClientCache getClientCache() { - try { - return ClientCacheFactory.getAnyInstance(); - } - catch (CacheClosedException ignore) { - return null; - } - } - + /* (non-Javadoc) */ public static boolean isGemfireVersionGreaterThanEqualTo(double expectedVersion) { double actualVersion = Double.parseDouble(GEMFIRE_VERSION.substring(0, 3)); return actualVersion >= expectedVersion; } + /* (non-Javadoc) */ public static boolean isGemfireVersion65OrAbove() { // expected 'major.minor' try { @@ -114,6 +58,7 @@ public abstract class GemfireUtils extends DistributedSystemUtils { } } + /* (non-Javadoc) */ public static boolean isGemfireVersion7OrAbove() { try { return isGemfireVersionGreaterThanEqualTo(7.0); @@ -125,6 +70,7 @@ public abstract class GemfireUtils extends DistributedSystemUtils { } } + /* (non-Javadoc) */ public static boolean isGemfireVersion8OrAbove() { try { return isGemfireVersionGreaterThanEqualTo(8.0); diff --git a/src/main/java/org/springframework/data/gemfire/client/ClientCacheFactoryBean.java b/src/main/java/org/springframework/data/gemfire/client/ClientCacheFactoryBean.java index f48335ef..142de7cf 100644 --- a/src/main/java/org/springframework/data/gemfire/client/ClientCacheFactoryBean.java +++ b/src/main/java/org/springframework/data/gemfire/client/ClientCacheFactoryBean.java @@ -16,16 +16,25 @@ package org.springframework.data.gemfire.client; +import java.net.InetSocketAddress; +import java.util.Map; import java.util.Properties; import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.data.gemfire.CacheFactoryBean; import org.springframework.data.gemfire.GemfireUtils; +import org.springframework.data.gemfire.client.support.DefaultableDelegatingPoolAdapter; +import org.springframework.data.gemfire.client.support.DelegatingPoolAdapter; import org.springframework.data.gemfire.config.GemfireConstants; +import org.springframework.data.gemfire.support.ConnectionEndpoint; +import org.springframework.data.gemfire.support.ConnectionEndpointList; +import org.springframework.data.gemfire.util.SpringUtils; import org.springframework.util.Assert; -import org.springframework.util.StringUtils; +import org.springframework.util.ObjectUtils; import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.GemFireCache; @@ -45,28 +54,54 @@ import com.gemstone.gemfire.pdx.PdxSerializer; * @see org.springframework.context.ApplicationListener * @see org.springframework.context.event.ContextRefreshedEvent * @see org.springframework.data.gemfire.CacheFactoryBean + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see org.springframework.data.gemfire.support.ConnectionEndpointList * @see com.gemstone.gemfire.cache.GemFireCache * @see com.gemstone.gemfire.cache.client.ClientCache * @see com.gemstone.gemfire.cache.client.ClientCacheFactory * @see com.gemstone.gemfire.cache.client.Pool * @see com.gemstone.gemfire.cache.client.PoolManager * @see com.gemstone.gemfire.distributed.DistributedSystem + * @see com.gemstone.gemfire.pdx.PdxSerializer */ @SuppressWarnings("unused") public class ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener { - protected Boolean keepAlive = false; - protected Boolean readyForEvents; + private Boolean keepAlive = false; + private Boolean multiUserAuthentication; + private Boolean prSingleHopEnabled; + private Boolean readyForEvents; + private Boolean subscriptionEnabled; + private Boolean threadLocalConnections; - protected Integer durableClientTimeout; + private ConnectionEndpointList locators = new ConnectionEndpointList(); + private ConnectionEndpointList servers = new ConnectionEndpointList(); + + private Integer durableClientTimeout; + private Integer freeConnectionTimeout; + private Integer loadConditioningInterval; + private Integer maxConnections; + private Integer minConnections; + private Integer readTimeout; + private Integer retryAttempts; + private Integer socketBufferSize; + private Integer statisticsInterval; + private Integer subscriptionAckInterval; + private Integer subscriptionMessageTrackingTimeout; + private Integer subscriptionRedundancy; + + private Long idleTimeout; + private Long pingInterval; private Pool pool; - protected String durableClientId; - protected String poolName; + private String durableClientId; + private String poolName; + private String serverGroup; + private String serverName; @Override - protected void postProcessPropertiesBeforeInitialization(Properties gemfireProperties) { + protected void postProcessBeforeCacheInitialization(Properties gemfireProperties) { } /** @@ -82,7 +117,8 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat @Override @SuppressWarnings("unchecked") protected T fetchCache() { - return (T) ClientCacheFactory.getAnyInstance(); + ClientCache cache = getCache(); + return (T) (cache != null ? cache : ClientCacheFactory.getAnyInstance()); } /** @@ -137,83 +173,132 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat */ @Override protected Object prepareFactory(final Object factory) { - if (isPdxOptionsSpecified()) { - ClientCacheFactory clientCacheFactory = (ClientCacheFactory) factory; + return initializePool(initializePdx((ClientCacheFactory) factory)); + } - if (pdxSerializer != null) { - Assert.isAssignable(PdxSerializer.class, pdxSerializer.getClass(), "Invalid pdx serializer used"); - clientCacheFactory.setPdxSerializer((PdxSerializer) pdxSerializer); + /** + * Initialize the PDX settings on the {@link ClientCacheFactory}. + * + * @param clientCacheFactory the GemFire {@link ClientCacheFactory} used to configure and create + * a GemFire {@link ClientCache}. + * @see com.gemstone.gemfire.cache.client.ClientCacheFactory + */ + ClientCacheFactory initializePdx(ClientCacheFactory clientCacheFactory) { + if (isPdxOptionsSpecified()) { + if (getPdxSerializer() != null) { + Assert.isInstanceOf(PdxSerializer.class, getPdxSerializer(), + String.format("[%1$s] of type [%2$s] is not a PdxSerializer;", getPdxSerializer(), + ObjectUtils.nullSafeClassName(getPdxSerializer()))); + + clientCacheFactory.setPdxSerializer((PdxSerializer) getPdxSerializer()); } - if (pdxDiskStoreName != null) { - clientCacheFactory.setPdxDiskStore(pdxDiskStoreName); + if (getPdxDiskStoreName() != null) { + clientCacheFactory.setPdxDiskStore(getPdxDiskStoreName()); } - if (pdxIgnoreUnreadFields != null) { - clientCacheFactory.setPdxIgnoreUnreadFields(pdxIgnoreUnreadFields); + if (getPdxIgnoreUnreadFields() != null) { + clientCacheFactory.setPdxIgnoreUnreadFields(getPdxIgnoreUnreadFields()); } - if (pdxPersistent != null) { - clientCacheFactory.setPdxPersistent(pdxPersistent); + if (getPdxPersistent() != null) { + clientCacheFactory.setPdxPersistent(getPdxPersistent()); } - if (pdxReadSerialized != null) { - clientCacheFactory.setPdxReadSerialized(pdxReadSerialized); + if (getPdxReadSerialized() != null) { + clientCacheFactory.setPdxReadSerialized(getPdxReadSerialized()); } } - return factory; - } - - /** - * Creates a new GemFire cache instance using the provided factory. - * - * @param parameterized Class type extension of GemFireCache. - * @param factory the appropriate GemFire factory used to create a cache instance. - * @return an instance of the GemFire cache. - * @see com.gemstone.gemfire.cache.GemFireCache - * @see com.gemstone.gemfire.cache.client.ClientCacheFactory#create() - */ - @Override - @SuppressWarnings("unchecked") - protected T createCache(Object factory) { - return (T) initializePool((ClientCacheFactory) factory).create(); - } - - /** - * Initialize the Pool settings on the ClientCacheFactory. - * - * @param clientCacheFactory the GemFire ClientCacheFactory used to configure and create a GemFire ClientCache. - * @see com.gemstone.gemfire.cache.client.ClientCacheFactory - */ - private ClientCacheFactory initializePool(ClientCacheFactory clientCacheFactory) { - resolvePool(pool); return clientCacheFactory; } /** - * Resolves the appropriate GemFire Pool from configuration used to configure the ClientCache. + * Initialize the {@link Pool} settings on the {@link ClientCacheFactory} with a given {@link Pool} instance + * or named {@link Pool}. * - * @param pool the preferred GemFire Pool to use in the configuration of the ClientCache. - * @return the resolved GemFire Pool. + * @param clientCacheFactory the GemFire {@link ClientCacheFactory} used to configure and create + * a GemFire {@link ClientCache}. + * @see com.gemstone.gemfire.cache.client.ClientCacheFactory * @see com.gemstone.gemfire.cache.client.Pool - * @see com.gemstone.gemfire.cache.client.PoolManager#find(String) */ - private Pool resolvePool(final Pool pool) { - Pool localPool = pool; + ClientCacheFactory initializePool(ClientCacheFactory clientCacheFactory) { + DefaultableDelegatingPoolAdapter pool = DefaultableDelegatingPoolAdapter.from( + DelegatingPoolAdapter.from(resolvePool())).preferDefault(); + + clientCacheFactory.setPoolFreeConnectionTimeout(pool.getFreeConnectionTimeout(getFreeConnectionTimeout())); + clientCacheFactory.setPoolIdleTimeout(pool.getIdleTimeout(getIdleTimeout())); + clientCacheFactory.setPoolLoadConditioningInterval(pool.getLoadConditioningInterval(getLoadConditioningInterval())); + clientCacheFactory.setPoolMaxConnections(pool.getMaxConnections(getMaxConnections())); + clientCacheFactory.setPoolMinConnections(pool.getMinConnections(getMinConnections())); + clientCacheFactory.setPoolMultiuserAuthentication(pool.getMultiuserAuthentication(getMultiUserAuthentication())); + clientCacheFactory.setPoolPRSingleHopEnabled(pool.getPRSingleHopEnabled(getPrSingleHopEnabled())); + clientCacheFactory.setPoolPingInterval(pool.getPingInterval(getPingInterval())); + clientCacheFactory.setPoolReadTimeout(pool.getReadTimeout(getReadTimeout())); + clientCacheFactory.setPoolRetryAttempts(pool.getRetryAttempts(getRetryAttempts())); + clientCacheFactory.setPoolServerGroup(pool.getServerGroup(getServerGroup())); + clientCacheFactory.setPoolSocketBufferSize(pool.getSocketBufferSize(getSocketBufferSize())); + clientCacheFactory.setPoolStatisticInterval(pool.getStatisticInterval(getStatisticsInterval())); + clientCacheFactory.setPoolSubscriptionAckInterval(pool.getSubscriptionAckInterval(getSubscriptionAckInterval())); + clientCacheFactory.setPoolSubscriptionEnabled(pool.getSubscriptionEnabled(getSubscriptionEnabled())); + clientCacheFactory.setPoolSubscriptionMessageTrackingTimeout(pool.getSubscriptionMessageTrackingTimeout(getSubscriptionMessageTrackingTimeout())); + clientCacheFactory.setPoolSubscriptionRedundancy(pool.getSubscriptionRedundancy(getSubscriptionRedundancy())); + clientCacheFactory.setPoolThreadLocalConnections(pool.getThreadLocalConnections(getThreadLocalConnections())); + + boolean noServers = getServers().isEmpty(); + boolean hasServers = !noServers; + boolean noLocators = getLocators().isEmpty(); + boolean hasLocators = !noLocators; + + if (hasServers || noLocators) { + Iterable servers = pool.getServers(getServers().toInetSocketAddresses()); + + for (InetSocketAddress server : servers) { + clientCacheFactory.addPoolServer(server.getHostName(), server.getPort()); + noServers = false; + } + } + + if (hasLocators || noServers) { + Iterable locators = pool.getLocators(getLocators().toInetSocketAddresses()); + + for (InetSocketAddress locator : locators) { + clientCacheFactory.addPoolLocator(locator.getHostName(), locator.getPort()); + } + } + + return clientCacheFactory; + } + + /** + * Resolves the appropriate GemFire {@link Pool} from Spring configuration that will be used to configure + * the GemFire {@link ClientCache}. + * + * @return the resolved GemFire {@link Pool}. + * @see com.gemstone.gemfire.cache.client.PoolManager#find(String) + * @see com.gemstone.gemfire.cache.client.Pool + */ + Pool resolvePool() { + Pool localPool = getPool(); if (localPool == null) { - localPool = PoolManager.find(poolName); + String poolName = SpringUtils.defaultIfNull(getPoolName(), GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME); + + localPool = findPool(poolName); if (localPool == null) { - if (StringUtils.hasText(poolName) && getBeanFactory().isTypeMatch(poolName, Pool.class)) { - localPool = getBeanFactory().getBean(poolName, Pool.class); - } - else { + BeanFactory beanFactory = getBeanFactory(); + + if (beanFactory instanceof ListableBeanFactory) { try { - localPool = getBeanFactory().getBean(Pool.class); - this.poolName = localPool.getName(); + Map poolFactoryBeanMap = + ((ListableBeanFactory) beanFactory).getBeansOfType(PoolFactoryBean.class, false, false); + + String dereferencedPoolName = SpringUtils.dereferenceBean(poolName); + + if (poolFactoryBeanMap.containsKey(dereferencedPoolName)) { + return poolFactoryBeanMap.get(dereferencedPoolName).getPool(); + } } - catch (BeansException ignore) { - log.info(String.format("no bean of type '%1$s' having name '%2$s' was found", - Pool.class.getName(), (StringUtils.hasText(poolName) ? poolName - : GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME))); + catch (BeansException e) { + log.info(String.format("unable to resolve bean of type [%1$s] with name [%2$s]", + PoolFactoryBean.class.getName(), poolName)); } } } @@ -222,6 +307,34 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat return localPool; } + /** + * Attempts to find a GemFire {@link Pool} with the given name. + * + * @param name a String indicating the name of the GemFire {@link Pool} to find. + * @return a {@link Pool} instance with the given name registered in GemFire or null if no {@link Pool} + * with name exists. + * @see com.gemstone.gemfire.cache.client.PoolManager#find(String) + * @see com.gemstone.gemfire.cache.client.Pool + */ + Pool findPool(String name) { + return PoolManager.find(name); + } + + /** + * Creates a new GemFire cache instance using the provided factory. + * + * @param parameterized Class type extension of {@link GemFireCache}. + * @param factory the appropriate GemFire factory used to create a cache instance. + * @return an instance of the GemFire cache. + * @see com.gemstone.gemfire.cache.client.ClientCacheFactory#create() + * @see com.gemstone.gemfire.cache.GemFireCache + */ + @Override + @SuppressWarnings("unchecked") + protected T createCache(Object factory) { + return (T) ((ClientCacheFactory) factory).create(); + } + /** * Inform the GemFire cluster that this client cache is ready to receive events iff the client is non-durable. * @@ -240,23 +353,42 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat // thrown if clientCache.readyForEvents() is called on a non-durable client } catch (CacheClosedException ignore) { + // cache is closed or was shutdown so ready-for-events is moot } } } + /* (non-Javadoc) */ @Override - protected void close(final GemFireCache cache) { + protected void close(GemFireCache cache) { ((ClientCache) cache).close(isKeepAlive()); } + /* (non-Javadoc) */ @Override public Class getObjectType() { + ClientCache cache = getCache(); return (cache != null ? cache.getClass() : ClientCache.class); } - @Override - public final void setEnableAutoReconnect(final Boolean enableAutoReconnect) { - throw new UnsupportedOperationException("Auto-reconnect is not supported on ClientCache."); + /* (non-Javadoc) */ + public void addLocators(ConnectionEndpoint... locators) { + this.locators.add(locators); + } + + /* (non-Javadoc) */ + public void addLocators(Iterable locators) { + this.locators.add(locators); + } + + /* (non-Javadoc) */ + public void addServers(ConnectionEndpoint... servers) { + this.servers.add(servers); + } + + /* (non-Javadoc) */ + public void addServers(Iterable servers) { + this.servers.add(servers); } /** @@ -264,7 +396,7 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat * * @param durableClientId a String value indicating the durable client id. */ - public void setDurableClientId(final String durableClientId) { + public void setDurableClientId(String durableClientId) { this.durableClientId = durableClientId; } @@ -285,7 +417,7 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat * @param durableClientTimeout an Integer value indicating the timeout in seconds for the server to keep * the durable client's queue around. */ - public void setDurableClientTimeout(final Integer durableClientTimeout) { + public void setDurableClientTimeout(Integer durableClientTimeout) { this.durableClientTimeout = durableClientTimeout; } @@ -300,11 +432,38 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat return durableClientTimeout; } + /* (non-Javadoc) */ + @Override + public final void setEnableAutoReconnect(final Boolean enableAutoReconnect) { + throw new UnsupportedOperationException("Auto-reconnect does not apply to clients."); + } + + /* (non-Javadoc) */ @Override public final Boolean getEnableAutoReconnect() { return Boolean.FALSE; } + /* (non-Javadoc) */ + public void setFreeConnectionTimeout(Integer freeConnectionTimeout) { + this.freeConnectionTimeout = freeConnectionTimeout; + } + + /* (non-Javadoc) */ + public Integer getFreeConnectionTimeout() { + return freeConnectionTimeout; + } + + /* (non-Javadoc) */ + public void setIdleTimeout(Long idleTimeout) { + this.idleTimeout = idleTimeout; + } + + /* (non-Javadoc) */ + public Long getIdleTimeout() { + return idleTimeout; + } + /** * Sets whether the server(s) should keep the durable client's queue alive for the duration of the timeout * when the client voluntarily disconnects. @@ -335,35 +494,132 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat return Boolean.TRUE.equals(getKeepAlive()); } + /* (non-Javadoc) */ + public void setLoadConditioningInterval(Integer loadConditioningInterval) { + this.loadConditioningInterval = loadConditioningInterval; + } + + /* (non-Javadoc) */ + public Integer getLoadConditioningInterval() { + return loadConditioningInterval; + } + + /* (non-Javadoc) */ + public void setLocators(ConnectionEndpoint[] locators) { + setLocators(ConnectionEndpointList.from(locators)); + } + + /* (non-Javadoc) */ + public void setLocators(Iterable locators) { + getLocators().clear(); + addLocators(locators); + } + + /* (non-Javadoc) */ + protected ConnectionEndpointList getLocators() { + return locators; + } + + /* (non-Javadoc) */ + public void setMaxConnections(Integer maxConnections) { + this.maxConnections = maxConnections; + } + + /* (non-Javadoc) */ + public Integer getMaxConnections() { + return maxConnections; + } + + /* (non-Javadoc) */ + public void setMinConnections(Integer minConnections) { + this.minConnections = minConnections; + } + + /* (non-Javadoc) */ + public Integer getMinConnections() { + return minConnections; + } + + /* (non-Javadoc) */ + public void setMultiUserAuthentication(Boolean multiUserAuthentication) { + this.multiUserAuthentication = multiUserAuthentication; + } + + /* (non-Javadoc) */ + public Boolean getMultiUserAuthentication() { + return multiUserAuthentication; + } + /** - * Sets the pool used by this client. + * Sets the {@link Pool} used by this cache client to obtain connections to the GemFire cluster. * - * @param pool the GemFire pool used by the Client Cache to obtain connections to the GemFire cluster. + * @param pool the GemFire {@link Pool} used by this {@link ClientCache} to obtain connections + * to the GemFire cluster. + * @throws IllegalArgumentException if the {@link Pool} is null. */ public void setPool(Pool pool) { - Assert.notNull(pool, "GemFire Pool must not be null"); this.pool = pool; } /** - * Sets the pool name used by this client. + * Gets the {@link Pool} used by this cache client to obtain connections to the GemFire cluster. * - * @param poolName set the name of the GemFire Pool used by the GemFire Client Cache. + * @return the GemFire {@link Pool} used by this {@link ClientCache} to obtain connections + * to the GemFire cluster. + */ + public Pool getPool() { + return pool; + } + + /** + * Sets the name of the {@link Pool} used by this cache client to obtain connections to the GemFire cluster. + * + * @param poolName set the name of the GemFire {@link Pool} used by this GemFire {@link ClientCache}. + * @throws IllegalArgumentException if the {@link Pool} name is unspecified. */ public void setPoolName(String poolName) { - Assert.hasText(poolName, "Pool 'name' is required"); this.poolName = poolName; } /** - * Gets the pool name used by this client. + * Gets the name of the GemFire {@link Pool} used by this GemFire cache client. * - * @return the name of the GemFire Pool used by the GemFire Client Cache. + * @return the name of the GemFire {@link Pool} used by this GemFire cache client. */ public String getPoolName() { return poolName; } + /* (non-Javadoc) */ + public void setPingInterval(Long pingInterval) { + this.pingInterval = pingInterval; + } + + /* (non-Javadoc) */ + public Long getPingInterval() { + return pingInterval; + } + + /* (non-Javadoc) */ + public void setPrSingleHopEnabled(Boolean prSingleHopEnabled) { + this.prSingleHopEnabled = prSingleHopEnabled; + } + + /* (non-Javadoc) */ + public Boolean getPrSingleHopEnabled() { + return prSingleHopEnabled; + } + + /* (non-Javadoc) */ + public void setReadTimeout(Integer readTimeout) { + this.readTimeout = readTimeout; + } + + /* (non-Javadoc) */ + public Integer getReadTimeout() { + return readTimeout; + } + /** * Sets the readyForEvents property to indicate whether the cache client should notify the server * that it is ready to receive updates. @@ -385,7 +641,14 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat return readyForEvents; } - /* (non-Javadoc) */ + /** + * Determines whether this GemFire cache client is ready for events. If 'readyForEvents' was explicitly set, + * then it takes precedence over all other considerations (e.g. durability). + * + * @return a boolean value indicating whether this GemFire cache client is ready for events. + * @see org.springframework.data.gemfire.GemfireUtils#isDurable(ClientCache) + * @see #getReadyForEvents() + */ public boolean isReadyForEvents() { Boolean readyForEvents = getReadyForEvents(); @@ -402,11 +665,119 @@ public class ClientCacheFactoryBean extends CacheFactoryBean implements Applicat } } - @Override - public final void setUseClusterConfiguration(Boolean useClusterConfiguration) { - throw new UnsupportedOperationException("Shared, cluster configuration is not applicable to clients."); + /* (non-Javadoc) */ + public void setRetryAttempts(Integer retryAttempts) { + this.retryAttempts = retryAttempts; } + /* (non-Javadoc) */ + public Integer getRetryAttempts() { + return retryAttempts; + } + + /* (non-Javadoc) */ + public void setServerGroup(String serverGroup) { + this.serverGroup = serverGroup; + } + + /* (non-Javadoc) */ + public String getServerGroup() { + return serverGroup; + } + + /* (non-Javadoc) */ + public void setServers(ConnectionEndpoint[] servers) { + setServers(ConnectionEndpointList.from(servers)); + } + + /* (non-Javadoc) */ + public void setServers(Iterable servers) { + getServers().clear(); + addServers(servers); + } + + /* (non-Javadoc) */ + protected ConnectionEndpointList getServers() { + return servers; + } + + /* (non-Javadoc) */ + public void setSocketBufferSize(Integer socketBufferSize) { + this.socketBufferSize = socketBufferSize; + } + + /* (non-Javadoc) */ + public Integer getSocketBufferSize() { + return socketBufferSize; + } + + /* (non-Javadoc) */ + public void setStatisticsInterval(Integer statisticsInterval) { + this.statisticsInterval = statisticsInterval; + } + + /* (non-Javadoc) */ + public Integer getStatisticsInterval() { + return statisticsInterval; + } + + /* (non-Javadoc) */ + public void setSubscriptionAckInterval(Integer subscriptionAckInterval) { + this.subscriptionAckInterval = subscriptionAckInterval; + } + + /* (non-Javadoc) */ + public Integer getSubscriptionAckInterval() { + return subscriptionAckInterval; + } + + /* (non-Javadoc) */ + public void setSubscriptionEnabled(Boolean subscriptionEnabled) { + this.subscriptionEnabled = subscriptionEnabled; + } + + /* (non-Javadoc) */ + public Boolean getSubscriptionEnabled() { + return subscriptionEnabled; + } + + /* (non-Javadoc) */ + public void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout) { + this.subscriptionMessageTrackingTimeout = subscriptionMessageTrackingTimeout; + } + + /* (non-Javadoc) */ + public Integer getSubscriptionMessageTrackingTimeout() { + return subscriptionMessageTrackingTimeout; + } + + /* (non-Javadoc) */ + public void setSubscriptionRedundancy(Integer subscriptionRedundancy) { + this.subscriptionRedundancy = subscriptionRedundancy; + } + + /* (non-Javadoc) */ + public Integer getSubscriptionRedundancy() { + return subscriptionRedundancy; + } + + /* (non-Javadoc) */ + public void setThreadLocalConnections(Boolean threadLocalConnections) { + this.threadLocalConnections = threadLocalConnections; + } + + /* (non-Javadoc) */ + public Boolean getThreadLocalConnections() { + return threadLocalConnections; + } + + /* (non-Javadoc) */ + @Override + public final void setUseClusterConfiguration(Boolean useClusterConfiguration) { + throw new UnsupportedOperationException("Shared, cluster-based configuration is not applicable for clients."); + } + + /* (non-Javadoc) */ @Override public final Boolean getUseClusterConfiguration() { return Boolean.FALSE; diff --git a/src/main/java/org/springframework/data/gemfire/client/ClientRegionFactoryBean.java b/src/main/java/org/springframework/data/gemfire/client/ClientRegionFactoryBean.java index dac37d56..f6d5dea9 100644 --- a/src/main/java/org/springframework/data/gemfire/client/ClientRegionFactoryBean.java +++ b/src/main/java/org/springframework/data/gemfire/client/ClientRegionFactoryBean.java @@ -24,7 +24,9 @@ import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.core.io.Resource; import org.springframework.data.gemfire.DataPolicyConverter; +import org.springframework.data.gemfire.GemfireUtils; import org.springframework.data.gemfire.RegionLookupFactoryBean; +import org.springframework.data.gemfire.config.GemfireConstants; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -41,7 +43,6 @@ import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.ClientRegionFactory; import com.gemstone.gemfire.cache.client.ClientRegionShortcut; import com.gemstone.gemfire.cache.client.Pool; -import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; /** * Client extension for GemFire Regions. @@ -53,14 +54,20 @@ import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; * @see org.springframework.beans.factory.BeanFactoryAware * @see org.springframework.beans.factory.DisposableBean * @see org.springframework.data.gemfire.RegionLookupFactoryBean + * @see com.gemstone.gemfire.cache.CacheListener + * @see com.gemstone.gemfire.cache.CacheLoader + * @see com.gemstone.gemfire.cache.CacheWriter + * @see com.gemstone.gemfire.cache.DataPolicy * @see com.gemstone.gemfire.cache.GemFireCache + * @see com.gemstone.gemfire.cache.Region + * @see com.gemstone.gemfire.cache.RegionAttributes * @see com.gemstone.gemfire.cache.client.ClientCache * @see com.gemstone.gemfire.cache.client.ClientRegionFactory * @see com.gemstone.gemfire.cache.client.ClientRegionShortcut */ @SuppressWarnings("unused") -public class ClientRegionFactoryBean extends RegionLookupFactoryBean implements BeanFactoryAware, - DisposableBean { +public class ClientRegionFactoryBean extends RegionLookupFactoryBean + implements BeanFactoryAware, DisposableBean { private static final Log log = LogFactory.getLog(ClientRegionFactoryBean.class); @@ -99,17 +106,11 @@ public class ClientRegionFactoryBean extends RegionLookupFactoryBean @Override @SuppressWarnings("all") protected Region lookupFallback(GemFireCache cache, String regionName) throws Exception { - Assert.isTrue(cache instanceof ClientCache, String.format("Unable to create Regions from %1$s!", cache)); + Assert.isTrue(GemfireUtils.isClient(cache), "A ClientCache is required to create a client Region"); - if (cache instanceof GemFireCacheImpl) { - Assert.isTrue(((GemFireCacheImpl) cache).isClient(), "A ClientCache instance is required!"); - } + ClientRegionFactory clientRegionFactory = ((ClientCache) cache).createClientRegionFactory( + resolveClientRegionShortcut()); - ClientCache clientCache = (ClientCache) cache; - - ClientRegionFactory clientRegionFactory = clientCache.createClientRegionFactory(resolveClientRegionShortcut()); - - // map Region attributes onto the ClientRegionFactory... if (attributes != null) { clientRegionFactory.setCloningEnabled(attributes.getCloningEnabled()); clientRegionFactory.setCompressor(attributes.getCompressor()); @@ -132,19 +133,14 @@ public class ClientRegionFactoryBean extends RegionLookupFactoryBean clientRegionFactory.setValueConstraint(attributes.getValueConstraint()); } - addCacheListeners(clientRegionFactory); + String poolName = resolvePoolName(); if (StringUtils.hasText(poolName)) { - // try to eagerly initialize the pool name, if defined as a bean - if (beanFactory.isTypeMatch(poolName, Pool.class)) { - if (log.isDebugEnabled()) { - log.debug(String.format("Found bean definition for pool '%1$s'; Eagerly initializing...", poolName)); - } - beanFactory.getBean(poolName, Pool.class); - } - clientRegionFactory.setPoolName(poolName); + clientRegionFactory.setPoolName(eagerlyInitializePool(poolName)); } + addCacheListeners(clientRegionFactory); + if (diskStoreName != null) { clientRegionFactory.setDiskStoreName(diskStoreName); } @@ -169,7 +165,8 @@ public class ClientRegionFactoryBean extends RegionLookupFactoryBean return clientRegion; } - protected ClientRegionShortcut resolveClientRegionShortcut() { + /* (non-Javadoc) */ + ClientRegionShortcut resolveClientRegionShortcut() { ClientRegionShortcut resolvedShortcut = this.shortcut; if (resolvedShortcut == null) { @@ -205,6 +202,36 @@ public class ClientRegionFactoryBean extends RegionLookupFactoryBean return resolvedShortcut; } + /* (non-Javadoc) */ + String resolvePoolName() { + String poolName = this.poolName; + + if (!StringUtils.hasText(poolName)) { + String defaultPoolName = GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME; + poolName = (beanFactory.containsBean(defaultPoolName) ? defaultPoolName : poolName); + } + + return poolName; + } + + /* (non-Javadoc) */ + String eagerlyInitializePool(String poolName) { + try { + if (beanFactory.isTypeMatch(poolName, Pool.class)) { + if (log.isDebugEnabled()) { + log.debug(String.format("Found bean definition for Pool [%1$s]; Eagerly initializing...", poolName)); + } + + beanFactory.getBean(poolName, Pool.class); + } + } + catch (BeansException ignore) { + log.warn(ignore.getMessage()); + } + + return poolName; + } + /** * Validates that the settings for ClientRegionShortcut and the 'persistent' attribute in <gfe:*-region> elements * are compatible. diff --git a/src/main/java/org/springframework/data/gemfire/client/PoolAdapter.java b/src/main/java/org/springframework/data/gemfire/client/PoolAdapter.java new file mode 100644 index 00000000..bb89d72b --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/client/PoolAdapter.java @@ -0,0 +1,180 @@ +/* + * Copyright 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.client; + +import java.net.InetSocketAddress; +import java.util.List; + +import com.gemstone.gemfire.cache.client.Pool; +import com.gemstone.gemfire.cache.query.QueryService; + +/** + * The PoolAdapter class is an abstract, default no-op implementation of the GemFire {@link Pool} interface + * that conveniently enables implementing classes to extend this adapter to adapt their interfaces and serve + * as a {@link Pool}. + * + * For instance, one possible implementation is Spring Data GemFire's {@link PoolFactoryBean}, which can act as + * a {@link Pool} in a context where only the {@link Pool}'s "configuration" and meta-data are required, + * but not actual connections or operating state information (e.g. pendingEventCount). + * + * @author John Blum + * @see org.springframework.data.gemfire.client.PoolFactoryBean + * @see com.gemstone.gemfire.cache.client.Pool + * @since 1.8.0 + */ +@SuppressWarnings("unused") +public abstract class PoolAdapter implements Pool { + + public static final String NOT_IMPLEMENTED = "Not Implemented"; + + /* (non-Javadoc) */ + public boolean isDestroyed() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getFreeConnectionTimeout() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public long getIdleTimeout() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getLoadConditioningInterval() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public List getLocators() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getMaxConnections() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getMinConnections() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public boolean getMultiuserAuthentication() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public String getName() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public boolean getPRSingleHopEnabled() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getPendingEventCount() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public long getPingInterval() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public QueryService getQueryService() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getReadTimeout() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getRetryAttempts() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public String getServerGroup() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public List getServers() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getSocketBufferSize() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getStatisticInterval() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getSubscriptionAckInterval() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public boolean getSubscriptionEnabled() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getSubscriptionMessageTrackingTimeout() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public int getSubscriptionRedundancy() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public boolean getThreadLocalConnections() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public void destroy() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public void destroy(final boolean keepAlive) { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /* (non-Javadoc) */ + public void releaseThreadLocalConnection() { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + +} diff --git a/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java b/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java index f6c3cdc9..ce119a2b 100644 --- a/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java +++ b/src/main/java/org/springframework/data/gemfire/client/PoolFactoryBean.java @@ -17,41 +17,41 @@ package org.springframework.data.gemfire.client; import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.Properties; +import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; +import org.springframework.data.gemfire.GemfireUtils; import org.springframework.data.gemfire.support.ConnectionEndpoint; import org.springframework.data.gemfire.support.ConnectionEndpointList; -import org.springframework.data.gemfire.util.CollectionUtils; import org.springframework.data.gemfire.util.DistributedSystemUtils; import org.springframework.util.Assert; import org.springframework.util.StringUtils; +import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.Pool; import com.gemstone.gemfire.cache.client.PoolFactory; import com.gemstone.gemfire.cache.client.PoolManager; +import com.gemstone.gemfire.cache.query.QueryService; import com.gemstone.gemfire.distributed.DistributedSystem; /** - * FactoryBean for easy declaration and configuration of a GemFire Pool. If a new Pool is created, - * its lifecycle is bound to that of the declaring container. + * FactoryBean for easy declaration and configuration of a GemFire {@link Pool}. If a new {@link Pool} is created, + * its lifecycle is bound to that of this declaring factory. * - * Note, if the Pool already exists, the existing Pool will be returned as is without any modifications - * and its lifecycle will be unaffected by this factory. + * Note, if a {@link Pool} having the configured name already exists, then the existing {@link Pool} will be returned + * as is without any modifications and its lifecycle will be unaffected by this factory. * * @author Costin Leau * @author John Blum * @see java.net.InetSocketAddress - * @see org.springframework.beans.factory.BeanFactory - * @see org.springframework.beans.factory.BeanFactoryAware * @see org.springframework.beans.factory.BeanNameAware * @see org.springframework.beans.factory.DisposableBean * @see org.springframework.beans.factory.FactoryBean @@ -61,7 +61,6 @@ import com.gemstone.gemfire.distributed.DistributedSystem; * @see com.gemstone.gemfire.cache.client.Pool * @see com.gemstone.gemfire.cache.client.PoolFactory * @see com.gemstone.gemfire.cache.client.PoolManager - * @see com.gemstone.gemfire.distributed.DistributedSystem */ @SuppressWarnings("unused") public class PoolFactoryBean implements FactoryBean, InitializingBean, DisposableBean, @@ -73,16 +72,14 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis private static final Log log = LogFactory.getLog(PoolFactoryBean.class); // indicates whether the Pool has been created internally (by this FactoryBean) or not - private volatile boolean springBasedPool = true; + volatile boolean springBasedPool = true; private BeanFactory beanFactory; private ConnectionEndpointList locators = new ConnectionEndpointList(); private ConnectionEndpointList servers = new ConnectionEndpointList(); - private Pool pool; - - private Properties gemfireProperties; + private volatile Pool pool; private String beanName; private String name; @@ -111,18 +108,28 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis private String serverGroup = PoolFactory.DEFAULT_SERVER_GROUP; + /** + * Constructs and initializes a GemFire {@link Pool}. + * + * @throws Exception if the {@link Pool} creation and initialization fails. + * @see com.gemstone.gemfire.cache.client.Pool + * @see com.gemstone.gemfire.cache.client.PoolFactory + * @see com.gemstone.gemfire.cache.client.PoolManager + * @see #createPoolFactory() + */ + @Override public void afterPropertiesSet() throws Exception { if (!StringUtils.hasText(name)) { Assert.hasText(beanName, "Pool 'name' is required"); name = beanName; } - // first check the configured pools + // check for an existing, configured Pool with name first Pool existingPool = PoolManager.find(name); if (existingPool != null) { if (log.isDebugEnabled()) { - log.debug(String.format("A Pool with name '%1$s' already exists; using existing Pool.", name)); + log.debug(String.format("A Pool with name [%1$s] already exists; using existing Pool.", name)); } springBasedPool = false; @@ -130,14 +137,38 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis } else { if (log.isDebugEnabled()) { - log.debug(String.format("No Pool with name '%1$s' was found. Creating a new Pool...", name)); - } - - if (locators.isEmpty() && servers.isEmpty()) { - throw new IllegalArgumentException("at least one GemFire Locator or Server is required"); + log.debug(String.format("No Pool with name [%1$s] was found. Creating new Pool.", name)); } springBasedPool = true; + } + } + + /** + * Destroys the GemFire {@link Pool} if created by this {@link PoolFactoryBean} and releases all system resources + * used by the {@link Pool}. + * + * @throws Exception if the {@link Pool} destruction caused an error. + * @see DisposableBean#destroy() + */ + @Override + public void destroy() throws Exception { + if (springBasedPool && pool != null && !pool.isDestroyed()) { + pool.releaseThreadLocalConnection(); + pool.destroy(keepAlive); + pool = null; + + if (log.isDebugEnabled()) { + log.debug(String.format("Destroyed Pool [%1$s]", name)); + } + } + } + + /* (non-Javadoc) */ + @Override + public Pool getObject() throws Exception { + if (pool == null) { + eagerlyInitializeClientCacheIfNotPresent(); PoolFactory poolFactory = createPoolFactory(); @@ -168,218 +199,400 @@ public class PoolFactoryBean implements FactoryBean, InitializingBean, Dis poolFactory.addServer(server.getHost(), server.getPort()); } - // eagerly initialize the GemFire DistributedSystem (if needed) - resolveDistributedSystem(); - pool = poolFactory.create(name); } + + return pool; + } + + /** + * Attempts to eagerly initialize the GemFire {@link ClientCache} if not already present so that the single + * {@link com.gemstone.gemfire.distributed.DistributedSystem} will exists, which is required to create + * a {@link Pool} instance. + * + * @see org.springframework.beans.factory.BeanFactory#getBean(Class) + * @see com.gemstone.gemfire.cache.client.ClientCache + */ + void eagerlyInitializeClientCacheIfNotPresent() { + if (!isDistributedSystemPresent()) { + getBeanFactory().getBean(ClientCache.class); + } } /** - * Creates an instance of the GemFire PoolFactory interface to construct, configure and initialize a GemFire Pool. + * Determines whether the GemFire DistributedSystem exists yet or not. * - * @return a PoolFactory implementation to create Pool. - * @see com.gemstone.gemfire.cache.client.PoolFactory + * @return a boolean value indicating whether the single, GemFire DistributedSystem has been created already. + * @see org.springframework.data.gemfire.GemfireUtils#getDistributedSystem() + * @see org.springframework.data.gemfire.GemfireUtils#isConnected(DistributedSystem) + * @see com.gemstone.gemfire.distributed.DistributedSystem + */ + boolean isDistributedSystemPresent() { + return GemfireUtils.isConnected(GemfireUtils.getDistributedSystem()); + } + + /** + * Creates an instance of the GemFire {@link PoolFactory} interface to construct, configure and initialize + * a GemFire {@link Pool}. + * + * @return a {@link PoolFactory} implementation to create a {@link Pool}. * @see com.gemstone.gemfire.cache.client.PoolManager#createFactory() + * @see com.gemstone.gemfire.cache.client.PoolFactory */ protected PoolFactory createPoolFactory() { return PoolManager.createFactory(); } - /** - * Attempts to find an existing, running GemFire {@link DistributedSystem} or proceeds to create - * a new {@link DistributedSystem} if one does not exist. - * - * @see DistributedSystemUtils#getDistributedSystem() - * @see #resolveGemfireProperties() - * @see #doDistributedSystemConnect(Properties) - */ - protected void resolveDistributedSystem() { - if (DistributedSystemUtils.isNotConnected(DistributedSystemUtils.getDistributedSystem())) { - doDistributedSystemConnect(resolveGemfireProperties()); - } - } - - /** - * Attempts to resolve existing GemFire System properties from the {@link ClientCacheFactoryBean} - * if set by the user. - * - * @return a {@link Properties} object containing GemFire System properties - * or null if no properties were configured. - * @see ClientCacheFactoryBean#resolveProperties() - * @see java.util.Properties - */ - protected Properties resolveGemfireProperties() { - gemfireProperties = (gemfireProperties != null ? gemfireProperties : new Properties()); - - try { - ClientCacheFactoryBean clientCacheFactoryBean = beanFactory.getBean(ClientCacheFactoryBean.class); - CollectionUtils.mergePropertiesIntoMap(clientCacheFactoryBean.resolveProperties(), gemfireProperties); - } - catch (Exception ignore) { - } - - return gemfireProperties; - } - - /** - * A workaround to create a Pool if no ClientCache has been created yet. Initialize a cache client-like - * DistributedSystem before initializing the Pool. - * - * @param properties GemFire System Properties. - * @see java.util.Properties - * @see com.gemstone.gemfire.distributed.DistributedSystem#connect(java.util.Properties) - */ - @SuppressWarnings("deprecation") - void doDistributedSystemConnect(Properties properties) { - Properties gemfireProperties = (properties != null ? (Properties) properties.clone() : new Properties()); - gemfireProperties.setProperty("locators", ""); - gemfireProperties.setProperty("mcast-port", "0"); - DistributedSystem.connect(gemfireProperties); - } - - public void destroy() throws Exception { - if (springBasedPool && pool != null && !pool.isDestroyed()) { - pool.releaseThreadLocalConnection(); - pool.destroy(keepAlive); - pool = null; - - if (log.isDebugEnabled()) { - log.debug(String.format("Destroyed Pool '%1$s'.", name)); - } - } - } - - public Pool getObject() throws Exception { - return pool; - } - + /* (non-Javadoc) */ + @Override public Class getObjectType() { return (pool != null ? pool.getClass() : Pool.class); } + /* (non-Javadoc) */ + @Override public boolean isSingleton() { return true; } - public void setBeanFactory(BeanFactory beanFactory) { + /* (non-Javadoc) */ + public void addLocators(ConnectionEndpoint... locators) { + this.locators.add(locators); + } + + /* (non-Javadoc) */ + public void addLocators(Iterable locators) { + this.locators.add(locators); + } + + /* (non-Javadoc) */ + public void addServers(ConnectionEndpoint... servers) { + this.servers.add(servers); + } + + /* (non-Javadoc) */ + public void addServers(Iterable servers) { + this.servers.add(servers); + } + + /* (non-Javadoc) */ + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } + /* (non-Javadoc) */ + protected BeanFactory getBeanFactory() { + return beanFactory; + } + + /* (non-Javadoc) */ public void setBeanName(String name) { this.beanName = name; } + /* (non-Javadoc) */ public void setName(String name) { this.name = name; } + /* (non-Javadoc) */ + String getName() { + return name; + } + + /* (non-Javadoc) */ public void setPool(Pool pool) { this.pool = pool; } + /* (non-Javadoc) */ + public Pool getPool() { + return (pool != null ? pool : new PoolAdapter() { + @Override + public boolean isDestroyed() { + Pool pool = PoolFactoryBean.this.pool; + return (pool != null && pool.isDestroyed()); + } + + @Override + public int getFreeConnectionTimeout() { + return PoolFactoryBean.this.freeConnectionTimeout; + } + + @Override + public long getIdleTimeout() { + return PoolFactoryBean.this.idleTimeout; + } + + @Override + public int getLoadConditioningInterval() { + return PoolFactoryBean.this.loadConditioningInterval; + } + + @Override + public List getLocators() { + return PoolFactoryBean.this.locators.toInetSocketAddresses(); + } + + @Override + public int getMaxConnections() { + return PoolFactoryBean.this.maxConnections; + } + + @Override + public int getMinConnections() { + return PoolFactoryBean.this.minConnections; + } + + @Override + public boolean getMultiuserAuthentication() { + return PoolFactoryBean.this.multiUserAuthentication; + } + + @Override + public String getName() { + String name = PoolFactoryBean.this.name; + name = (StringUtils.hasText(name) ? name : PoolFactoryBean.this.beanName); + return name; + } + + @Override + public int getPendingEventCount() { + Pool pool = PoolFactoryBean.this.pool; + if (pool != null) { + return pool.getPendingEventCount(); + } + throw new IllegalStateException("The Pool is not initialized"); + } + + @Override + public long getPingInterval() { + return PoolFactoryBean.this.pingInterval; + } + + @Override + public boolean getPRSingleHopEnabled() { + return PoolFactoryBean.this.prSingleHopEnabled; + } + + @Override + public QueryService getQueryService() { + Pool pool = PoolFactoryBean.this.pool; + if (pool != null) { + return pool.getQueryService(); + } + throw new IllegalStateException("The Pool is not initialized"); + } + + @Override + public int getReadTimeout() { + return PoolFactoryBean.this.readTimeout; + } + + @Override + public int getRetryAttempts() { + return PoolFactoryBean.this.retryAttempts; + } + + @Override + public String getServerGroup() { + return PoolFactoryBean.this.serverGroup; + } + + @Override + public List getServers() { + return PoolFactoryBean.this.servers.toInetSocketAddresses(); + } + + @Override + public int getSocketBufferSize() { + return PoolFactoryBean.this.socketBufferSize; + } + + @Override + public int getStatisticInterval() { + return PoolFactoryBean.this.statisticInterval; + } + + @Override + public int getSubscriptionAckInterval() { + return PoolFactoryBean.this.subscriptionAckInterval; + } + + @Override + public boolean getSubscriptionEnabled() { + return PoolFactoryBean.this.subscriptionEnabled; + } + + @Override + public int getSubscriptionMessageTrackingTimeout() { + return PoolFactoryBean.this.subscriptionMessageTrackingTimeout; + } + + @Override + public int getSubscriptionRedundancy() { + return PoolFactoryBean.this.subscriptionRedundancy; + } + + @Override + public boolean getThreadLocalConnections() { + return PoolFactoryBean.this.threadLocalConnections; + } + + @Override + public void destroy() { + destroy(false); + } + + @Override + public void destroy(final boolean keepAlive) { + try { + PoolFactoryBean.this.destroy(); + } + catch (Exception ignore) { + Pool pool = PoolFactoryBean.this.pool; + if (pool != null) { + pool.destroy(keepAlive); + } + } + } + + @Override + public void releaseThreadLocalConnection() { + Pool pool = PoolFactoryBean.this.pool; + if (pool != null) { + pool.releaseThreadLocalConnection(); + } + else { + throw new IllegalStateException("The Pool is not initialized"); + } + } + }); + } + + /* (non-Javadoc) */ public void setFreeConnectionTimeout(int freeConnectionTimeout) { this.freeConnectionTimeout = freeConnectionTimeout; } + /* (non-Javadoc) */ public void setIdleTimeout(long idleTimeout) { this.idleTimeout = idleTimeout; } + /* (non-Javadoc) */ public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; } - @Deprecated - public void setLocators(Iterable locators) { - setLocatorEndpoints(ConnectionEndpointList.from(locators)); - } - - public void setLocatorEndpoints(Iterable endpoints) { - this.locators.add(endpoints); - } - - public void setLocatorEndpointList(ConnectionEndpointList endpointList) { - setLocatorEndpoints(endpointList); - } - + /* (non-Javadoc) */ public void setLoadConditioningInterval(int loadConditioningInterval) { this.loadConditioningInterval = loadConditioningInterval; } + /* (non-Javadoc) */ + public void setLocators(ConnectionEndpoint[] connectionEndpoints) { + setLocators(ConnectionEndpointList.from(connectionEndpoints)); + } + + /* (non-Javadoc) */ + public void setLocators(Iterable connectionEndpoints) { + getLocators().clear(); + getLocators().add(connectionEndpoints); + } + + /* (non-Javadoc) */ + ConnectionEndpointList getLocators() { + return locators; + } + + /* (non-Javadoc) */ public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } + /* (non-Javadoc) */ public void setMinConnections(int minConnections) { this.minConnections = minConnections; } + /* (non-Javadoc) */ public void setMultiUserAuthentication(boolean multiUserAuthentication) { this.multiUserAuthentication = multiUserAuthentication; } + /* (non-Javadoc) */ public void setPingInterval(long pingInterval) { this.pingInterval = pingInterval; } - public void setProperties(Properties gemfireProperties) { - this.gemfireProperties = gemfireProperties; - } - + /* (non-Javadoc) */ public void setPrSingleHopEnabled(boolean prSingleHopEnabled) { this.prSingleHopEnabled = prSingleHopEnabled; } + /* (non-Javadoc) */ public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } + /* (non-Javadoc) */ public void setRetryAttempts(int retryAttempts) { this.retryAttempts = retryAttempts; } + /* (non-Javadoc) */ public void setServerGroup(String serverGroup) { this.serverGroup = serverGroup; } - @Deprecated - public void setServers(Collection servers) { - setServerEndpoints(ConnectionEndpointList.from(servers)); + /* (non-Javadoc) */ + public void setServers(ConnectionEndpoint[] connectionEndpoints) { + setServers(ConnectionEndpointList.from(connectionEndpoints)); } - public void setServerEndpoints(Iterable endpoints) { - this.servers.add(endpoints); + /* (non-Javadoc) */ + public void setServers(Iterable connectionEndpoints) { + getServers().clear(); + getServers().add(connectionEndpoints); } - public void setServerEndpointList(ConnectionEndpointList endpointList) { - setServerEndpoints(endpointList); + /* (non-Javadoc) */ + ConnectionEndpointList getServers() { + return servers; } + /* (non-Javadoc) */ public void setSocketBufferSize(int socketBufferSize) { this.socketBufferSize = socketBufferSize; } + /* (non-Javadoc) */ public void setStatisticInterval(int statisticInterval) { this.statisticInterval = statisticInterval; } + /* (non-Javadoc) */ public void setSubscriptionAckInterval(int subscriptionAckInterval) { this.subscriptionAckInterval = subscriptionAckInterval; } + /* (non-Javadoc) */ public void setSubscriptionEnabled(boolean subscriptionEnabled) { this.subscriptionEnabled = subscriptionEnabled; } + /* (non-Javadoc) */ public void setSubscriptionMessageTrackingTimeout(int subscriptionMessageTrackingTimeout) { this.subscriptionMessageTrackingTimeout = subscriptionMessageTrackingTimeout; } + /* (non-Javadoc) */ public void setSubscriptionRedundancy(int subscriptionRedundancy) { this.subscriptionRedundancy = subscriptionRedundancy; } + /* (non-Javadoc) */ public void setThreadLocalConnections(boolean threadLocalConnections) { this.threadLocalConnections = threadLocalConnections; } diff --git a/src/main/java/org/springframework/data/gemfire/client/support/DefaultableDelegatingPoolAdapter.java b/src/main/java/org/springframework/data/gemfire/client/support/DefaultableDelegatingPoolAdapter.java new file mode 100644 index 00000000..7789c669 --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/client/support/DefaultableDelegatingPoolAdapter.java @@ -0,0 +1,333 @@ +/* + * Copyright 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.client.support; + +import java.net.InetSocketAddress; +import java.util.Collection; +import java.util.List; + +import org.springframework.data.gemfire.util.SpringUtils; +import org.springframework.util.Assert; + +import com.gemstone.gemfire.cache.client.Pool; +import com.gemstone.gemfire.cache.query.QueryService; + +/** + * The DefaultableDelegatingPoolAdapter class... + * + * @author John Blum + * @since 1.0.0 + */ +@SuppressWarnings("unused") +public abstract class DefaultableDelegatingPoolAdapter { + + private final Pool delegate; + + private Preference preference = Preference.PREFER_POOL; + + /* (non-Javadoc) */ + public static DefaultableDelegatingPoolAdapter from(Pool delegate) { + return new DefaultableDelegatingPoolAdapter(delegate) { }; + } + + /* (non-Javadoc) */ + protected DefaultableDelegatingPoolAdapter(Pool delegate) { + Assert.notNull(delegate, "'delegate' must not be null"); + this.delegate = delegate; + } + + /* (non-Javadoc) */ + protected Pool getDelegate() { + return delegate; + } + + /* (non-Javadoc) */ + protected DefaultableDelegatingPoolAdapter setPreference(Preference preference) { + this.preference = preference; + return this; + } + + /* (non-Javadoc) */ + protected Preference getPreference() { + return this.preference; + } + + /* (non-Javadoc) */ + protected T defaultIfNull(T defaultValue, ValueProvider valueProvider) { + return (prefersPool() ? SpringUtils.defaultIfNull(valueProvider.getValue(), defaultValue) : + (defaultValue != null ? defaultValue : valueProvider.getValue())); + } + + /* (non-Javadoc) */ + protected > T defaultIfEmpty(T defaultValue, ValueProvider valueProvider) { + if (prefersPool()) { + T value = valueProvider.getValue(); + return (value == null || value.isEmpty() ? defaultValue : value); + } + else { + return (defaultValue == null || defaultValue.isEmpty() ? valueProvider.getValue() : defaultValue); + } + } + + /* (non-Javadoc) */ + public DefaultableDelegatingPoolAdapter preferDefault() { + return setPreference(Preference.PREFER_DEFAULT); + } + + /* (non-Javadoc) */ + protected boolean prefersDefault() { + return Preference.PREFER_DEFAULT.equals(getPreference()); + } + + /* (non-Javadoc) */ + public DefaultableDelegatingPoolAdapter preferPool() { + return setPreference(Preference.PREFER_POOL); + } + + /* (non-Javadoc) */ + protected boolean prefersPool() { + return Preference.PREFER_POOL.equals(getPreference()); + } + + /* (non-Javadoc) */ + public boolean isDestroyed() { + return getDelegate().isDestroyed(); + } + + /* (non-Javadoc) */ + public int getFreeConnectionTimeout(Integer defaultFreeConnectionTimeout) { + return defaultIfNull(defaultFreeConnectionTimeout, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getFreeConnectionTimeout(); + } + }); + } + + /* (non-Javadoc) */ + public long getIdleTimeout(Long defaultIdleTimeout) { + return defaultIfNull(defaultIdleTimeout, new ValueProvider() { + @Override public Long getValue() { + return getDelegate().getIdleTimeout(); + } + }); + } + + /* (non-Javadoc) */ + public int getLoadConditioningInterval(Integer defaultLoadConditioningInterval) { + return defaultIfNull(defaultLoadConditioningInterval, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getLoadConditioningInterval(); + } + }); + } + + /* (non-Javadoc) */ + public List getLocators(List defaultLocators) { + return defaultIfEmpty(defaultLocators, new ValueProvider>() { + @Override public List getValue() { + return getDelegate().getLocators(); + } + }); + } + + /* (non-Javadoc) */ + public int getMaxConnections(Integer defaultMaxConnections) { + return defaultIfNull(defaultMaxConnections, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getMaxConnections(); + } + }); + } + + /* (non-Javadoc) */ + public int getMinConnections(Integer defaultMinConnections) { + return defaultIfNull(defaultMinConnections, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getMinConnections(); + } + }); + } + + /* (non-Javadoc) */ + public boolean getMultiuserAuthentication(Boolean defaultMultiUserAuthentication) { + return defaultIfNull(defaultMultiUserAuthentication, new ValueProvider() { + @Override public Boolean getValue() { + return getDelegate().getMultiuserAuthentication(); + } + }); + } + + /* (non-Javadoc) */ + public String getName() { + return getDelegate().getName(); + } + + /* (non-Javadoc) */ + public int getPendingEventCount() { + return getDelegate().getPendingEventCount(); + } + + /* (non-Javadoc) */ + public long getPingInterval(Long defaultPingInterval) { + return defaultIfNull(defaultPingInterval, new ValueProvider() { + @Override public Long getValue() { + return getDelegate().getPingInterval(); + } + }); + } + + /* (non-Javadoc) */ + public boolean getPRSingleHopEnabled(Boolean defaultPrSingleHopEnabled) { + return defaultIfNull(defaultPrSingleHopEnabled, new ValueProvider() { + @Override public Boolean getValue() { + return getDelegate().getPRSingleHopEnabled(); + } + }); + } + + /* (non-Javadoc) */ + public QueryService getQueryService() { + return getDelegate().getQueryService(); + } + + /* (non-Javadoc) */ + public int getReadTimeout(Integer defaultReadTimeout) { + return defaultIfNull(defaultReadTimeout, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getReadTimeout(); + } + }); + } + + /* (non-Javadoc) */ + public int getRetryAttempts(Integer defaultRetryAttempts) { + return defaultIfNull(defaultRetryAttempts, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getRetryAttempts(); + } + }); + } + + /* (non-Javadoc) */ + public String getServerGroup(String defaultServerGroup) { + return defaultIfNull(defaultServerGroup, new ValueProvider() { + @Override public String getValue() { + return getDelegate().getServerGroup(); + } + }); + } + + /* (non-Javadoc) */ + public List getServers(List defaultServers) { + return defaultIfEmpty(defaultServers, new ValueProvider>() { + @Override public List getValue() { + return getDelegate().getServers(); + } + }); + } + + /* (non-Javadoc) */ + public int getSocketBufferSize(Integer defaultSocketBufferSize) { + return defaultIfNull(defaultSocketBufferSize, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getSocketBufferSize(); + } + }); + } + + /* (non-Javadoc) */ + public int getStatisticInterval(Integer defaultStatisticInterval) { + return defaultIfNull(defaultStatisticInterval, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getStatisticInterval(); + } + }); + } + + /* (non-Javadoc) */ + public int getSubscriptionAckInterval(Integer defaultSubscriptionAckInterval) { + return defaultIfNull(defaultSubscriptionAckInterval, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getSubscriptionAckInterval(); + } + }); + } + + /* (non-Javadoc) */ + public boolean getSubscriptionEnabled(Boolean defaultSubscriptionEnabled) { + return defaultIfNull(defaultSubscriptionEnabled, new ValueProvider() { + @Override public Boolean getValue() { + return getDelegate().getSubscriptionEnabled(); + } + }); + } + + /* (non-Javadoc) */ + public int getSubscriptionMessageTrackingTimeout(Integer defaultSubscriptionMessageTrackingTimeout) { + return defaultIfNull(defaultSubscriptionMessageTrackingTimeout, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getSubscriptionMessageTrackingTimeout(); + } + }); + } + + /* (non-Javadoc) */ + public int getSubscriptionRedundancy(Integer defaultSubscriptionRedundancy) { + return defaultIfNull(defaultSubscriptionRedundancy, new ValueProvider() { + @Override public Integer getValue() { + return getDelegate().getSubscriptionRedundancy(); + } + }); + } + + /* (non-Javadoc) */ + public boolean getThreadLocalConnections(Boolean defaultThreadLocalConnections) { + return defaultIfNull(defaultThreadLocalConnections, new ValueProvider() { + @Override public Boolean getValue() { + return getDelegate().getThreadLocalConnections(); + } + }); + } + + /* (non-Javadoc) */ + public void destroy() { + getDelegate().destroy(); + } + + /* (non-Javadoc) */ + public void destroy(final boolean keepAlive) { + getDelegate().destroy(keepAlive); + } + + /* (non-Javadoc) */ + public void releaseThreadLocalConnection() { + getDelegate().releaseThreadLocalConnection(); + } + + /* (non-Javadoc) */ + enum Preference { + PREFER_DEFAULT, + PREFER_POOL; + } + + /* (non-Javadoc) */ + interface ValueProvider { + T getValue(); + } + +} diff --git a/src/main/java/org/springframework/data/gemfire/client/support/DelegatingPoolAdapter.java b/src/main/java/org/springframework/data/gemfire/client/support/DelegatingPoolAdapter.java new file mode 100644 index 00000000..a60c621b --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/client/support/DelegatingPoolAdapter.java @@ -0,0 +1,254 @@ +/* + * Copyright 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.client.support; + +import java.net.InetSocketAddress; +import java.util.List; + +import com.gemstone.gemfire.cache.client.Pool; +import com.gemstone.gemfire.cache.query.QueryService; + +/** + * DelegatingPoolAdapter is an abstract implementation of GemFire's {@link Pool} interface and extension of + * {@link FactoryDefaultsPoolAdapter} that delegates operations to the provided {@link Pool} instance. + * + * However, this implementation guards against a potentially null {@link Pool} reference by returning + * default factory settings for the {@link Pool}'s configuration properties along with default behavior for operations + * when the {@link Pool} reference is null. + * + * @author John Blum + * @see FactoryDefaultsPoolAdapter + * @see com.gemstone.gemfire.cache.client.Pool + * @since 1.8.0 + */ +@SuppressWarnings("unused") +public abstract class DelegatingPoolAdapter extends FactoryDefaultsPoolAdapter { + + private final Pool delegate; + + /* (non-Javadoc) */ + public static DelegatingPoolAdapter from(Pool delegate) { + return new DelegatingPoolAdapter(delegate) { }; + } + + public DelegatingPoolAdapter(Pool delegate) { + this.delegate = delegate; + } + + /* (non-Javadoc) */ + protected Pool getDelegate() { + return delegate; + } + + /* (non-Javadoc) */ + @Override + public boolean isDestroyed() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.isDestroyed() : super.isDestroyed()); + } + + /* (non-Javadoc) */ + @Override + public int getFreeConnectionTimeout() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getFreeConnectionTimeout() : super.getFreeConnectionTimeout()); + } + + /* (non-Javadoc) */ + @Override + public long getIdleTimeout() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getIdleTimeout() : super.getIdleTimeout()); + } + + /* (non-Javadoc) */ + @Override + public int getLoadConditioningInterval() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getLoadConditioningInterval() : super.getLoadConditioningInterval()); + } + + /* (non-Javadoc) */ + @Override + public List getLocators() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getLocators() : super.getLocators()); + } + + /* (non-Javadoc) */ + @Override + public int getMaxConnections() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getMaxConnections() : super.getMaxConnections()); + } + + /* (non-Javadoc) */ + @Override + public int getMinConnections() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getMinConnections() : super.getMinConnections()); + } + + /* (non-Javadoc) */ + @Override + public boolean getMultiuserAuthentication() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getMultiuserAuthentication() : super.getMultiuserAuthentication()); + } + + /* (non-Javadoc) */ + @Override + public String getName() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getName() : super.getName()); + } + + /* (non-Javadoc) */ + @Override + public boolean getPRSingleHopEnabled() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getPRSingleHopEnabled() : super.getPRSingleHopEnabled()); + } + + /* (non-Javadoc) */ + @Override + public int getPendingEventCount() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getPendingEventCount() : 0); + } + + /* (non-Javadoc) */ + @Override + public long getPingInterval() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getPingInterval() : super.getPingInterval()); + } + + /* (non-Javadoc) */ + @Override + public QueryService getQueryService() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getQueryService() : super.getQueryService()); + } + + /* (non-Javadoc) */ + @Override + public int getReadTimeout() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getReadTimeout() : super.getReadTimeout()); + } + + /* (non-Javadoc) */ + @Override + public int getRetryAttempts() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getRetryAttempts() : super.getRetryAttempts()); + } + + /* (non-Javadoc) */ + @Override + public String getServerGroup() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getServerGroup() : super.getServerGroup()); + } + + /* (non-Javadoc) */ + @Override + public List getServers() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getServers() : super.getServers()); + } + + /* (non-Javadoc) */ + @Override + public int getSocketBufferSize() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getSocketBufferSize() : super.getSocketBufferSize()); + } + + /* (non-Javadoc) */ + @Override + public int getStatisticInterval() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getStatisticInterval() : super.getStatisticInterval()); + } + + /* (non-Javadoc) */ + @Override + public int getSubscriptionAckInterval() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getSubscriptionAckInterval() : super.getSubscriptionAckInterval()); + } + + /* (non-Javadoc) */ + @Override + public boolean getSubscriptionEnabled() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getSubscriptionEnabled() : super.getSubscriptionEnabled()); + } + + /* (non-Javadoc) */ + @Override + public int getSubscriptionMessageTrackingTimeout() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getSubscriptionMessageTrackingTimeout() + : super.getSubscriptionMessageTrackingTimeout()); + } + + /* (non-Javadoc) */ + @Override + public int getSubscriptionRedundancy() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getSubscriptionRedundancy() : super.getSubscriptionRedundancy()); + } + + /* (non-Javadoc) */ + @Override + public boolean getThreadLocalConnections() { + Pool delegate = getDelegate(); + return (delegate != null ? delegate.getThreadLocalConnections() : super.getThreadLocalConnections()); + } + + /* (non-Javadoc) */ + @Override + public void destroy() { + Pool delegate = getDelegate(); + if (delegate != null) { + delegate.destroy(); + } + } + + /* (non-Javadoc) */ + @Override + public void destroy(final boolean keepAlive) { + Pool delegate = getDelegate(); + if (delegate != null) { + delegate.destroy(keepAlive); + } + } + + /* (non-Javadoc) */ + @Override + public void releaseThreadLocalConnection() { + Pool delegate = getDelegate(); + if (delegate != null) { + delegate.releaseThreadLocalConnection(); + } + } + +} diff --git a/src/main/java/org/springframework/data/gemfire/client/support/FactoryDefaultsPoolAdapter.java b/src/main/java/org/springframework/data/gemfire/client/support/FactoryDefaultsPoolAdapter.java new file mode 100644 index 00000000..b5abd8a0 --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/client/support/FactoryDefaultsPoolAdapter.java @@ -0,0 +1,186 @@ +/* + * Copyright 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.client.support; + +import java.net.InetSocketAddress; +import java.util.Collections; +import java.util.List; + +import org.springframework.data.gemfire.GemfireUtils; +import org.springframework.data.gemfire.client.PoolAdapter; + +import com.gemstone.gemfire.cache.client.PoolFactory; +import com.gemstone.gemfire.cache.query.QueryService; + +/** + * FactoryDefaultsPoolAdapter is an abstract implementation of GemFire's {@link com.gemstone.gemfire.cache.client.Pool} + * interface and extension of {@link PoolAdapter} providing default factory values for all configuration properties + * (e.g. freeConnectionTimeout, idleTimeout, etc). + * + * @author John Blum + * @see org.springframework.data.gemfire.client.PoolAdapter + * @see com.gemstone.gemfire.cache.client.PoolFactory + * @see com.gemstone.gemfire.cache.client.Pool + * @since 1.8.0 + */ +@SuppressWarnings("unused") +public abstract class FactoryDefaultsPoolAdapter extends PoolAdapter { + + protected static final boolean DEFAULT_KEEP_ALIVE = false; + + protected static final String DEFAULT_POOL_NAME = "DEFAULT"; + protected static final String LOCALHOST = "localhost"; + + /* (non-Javadoc) */ + @Override + public int getFreeConnectionTimeout() { + return PoolFactory.DEFAULT_FREE_CONNECTION_TIMEOUT; + } + + /* (non-Javadoc) */ + @Override + public long getIdleTimeout() { + return PoolFactory.DEFAULT_IDLE_TIMEOUT; + } + + /* (non-Javadoc) */ + @Override + public int getLoadConditioningInterval() { + return PoolFactory.DEFAULT_LOAD_CONDITIONING_INTERVAL; + } + + /* (non-Javadoc) */ + @Override + public List getLocators() { + return Collections.emptyList(); + } + + /* (non-Javadoc) */ + @Override + public int getMaxConnections() { + return PoolFactory.DEFAULT_MAX_CONNECTIONS; + } + + /* (non-Javadoc) */ + @Override + public int getMinConnections() { + return PoolFactory.DEFAULT_MIN_CONNECTIONS; + } + + /* (non-Javadoc) */ + @Override + public boolean getMultiuserAuthentication() { + return PoolFactory.DEFAULT_MULTIUSER_AUTHENTICATION; + } + + /* (non-Javadoc) */ + @Override + public String getName() { + return DEFAULT_POOL_NAME; + } + + /* (non-Javadoc) */ + @Override + public boolean getPRSingleHopEnabled() { + return PoolFactory.DEFAULT_PR_SINGLE_HOP_ENABLED; + } + + /* (non-Javadoc) */ + @Override + public long getPingInterval() { + return PoolFactory.DEFAULT_PING_INTERVAL; + } + + /* (non-Javadoc) */ + @Override + public QueryService getQueryService() { + return null; + } + + /* (non-Javadoc) */ + @Override + public int getReadTimeout() { + return PoolFactory.DEFAULT_READ_TIMEOUT; + } + + /* (non-Javadoc) */ + @Override + public int getRetryAttempts() { + return PoolFactory.DEFAULT_RETRY_ATTEMPTS; + } + + /* (non-Javadoc) */ + @Override + public String getServerGroup() { + return PoolFactory.DEFAULT_SERVER_GROUP; + } + + /* (non-Javadoc) */ + @Override + public List getServers() { + return Collections.singletonList(new InetSocketAddress(LOCALHOST, GemfireUtils.DEFAULT_CACHE_SERVER_PORT)); + } + + /* (non-Javadoc) */ + @Override + public int getSocketBufferSize() { + return PoolFactory.DEFAULT_SOCKET_BUFFER_SIZE; + } + + /* (non-Javadoc) */ + @Override + public int getStatisticInterval() { + return PoolFactory.DEFAULT_STATISTIC_INTERVAL; + } + + /* (non-Javadoc) */ + @Override + public int getSubscriptionAckInterval() { + return PoolFactory.DEFAULT_SUBSCRIPTION_ACK_INTERVAL; + } + + /* (non-Javadoc) */ + @Override + public boolean getSubscriptionEnabled() { + return PoolFactory.DEFAULT_SUBSCRIPTION_ENABLED; + } + + /* (non-Javadoc) */ + @Override + public int getSubscriptionMessageTrackingTimeout() { + return PoolFactory.DEFAULT_SUBSCRIPTION_MESSAGE_TRACKING_TIMEOUT; + } + + /* (non-Javadoc) */ + @Override + public int getSubscriptionRedundancy() { + return PoolFactory.DEFAULT_SUBSCRIPTION_REDUNDANCY; + } + + /* (non-Javadoc) */ + @Override + public boolean getThreadLocalConnections() { + return PoolFactory.DEFAULT_THREAD_LOCAL_CONNECTIONS; + } + + /* (non-Javadoc) */ + public void destroy() { + destroy(DEFAULT_KEEP_ALIVE); + } + +} diff --git a/src/main/java/org/springframework/data/gemfire/config/CacheParser.java b/src/main/java/org/springframework/data/gemfire/config/CacheParser.java index 477e4949..7f358103 100644 --- a/src/main/java/org/springframework/data/gemfire/config/CacheParser.java +++ b/src/main/java/org/springframework/data/gemfire/config/CacheParser.java @@ -25,7 +25,7 @@ import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; -import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser; +import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.data.gemfire.CacheFactoryBean; import org.springframework.util.CollectionUtils; @@ -38,14 +38,14 @@ import org.w3c.dom.NamedNodeMap; import com.gemstone.gemfire.internal.datasource.ConfigProperty; /** - * Parser for <cache;gt; definitions. + * Parser for <cache> bean definitions. * * @author Costin Leau * @author Oliver Gierke * @author David Turanski * @author John Blum */ -class CacheParser extends AbstractSimpleBeanDefinitionParser { +class CacheParser extends AbstractSingleBeanDefinitionParser { @Override protected Class getBeanClass(Element element) { @@ -69,11 +69,11 @@ class CacheParser extends AbstractSimpleBeanDefinitionParser { ParsingUtils.setPropertyValue(element, builder, "lock-lease"); ParsingUtils.setPropertyValue(element, builder, "lock-timeout"); ParsingUtils.setPropertyValue(element, builder, "message-sync-interval"); - ParsingUtils.setPropertyReference(element, builder, "pdx-serializer-ref", "pdxSerializer"); - ParsingUtils.setPropertyValue(element, builder, "pdx-read-serialized"); - ParsingUtils.setPropertyValue(element, builder, "pdx-ignore-unread-fields"); - ParsingUtils.setPropertyValue(element, builder, "pdx-persistent"); parsePdxDiskStore(element, parserContext, builder); + ParsingUtils.setPropertyValue(element, builder, "pdx-ignore-unread-fields"); + ParsingUtils.setPropertyValue(element, builder, "pdx-read-serialized"); + ParsingUtils.setPropertyValue(element, builder, "pdx-persistent"); + ParsingUtils.setPropertyReference(element, builder, "pdx-serializer-ref", "pdxSerializer"); ParsingUtils.setPropertyValue(element, builder, "search-timeout"); ParsingUtils.setPropertyValue(element, builder, "use-cluster-configuration"); @@ -81,10 +81,12 @@ class CacheParser extends AbstractSimpleBeanDefinitionParser { if (!CollectionUtils.isEmpty(txListeners)) { ManagedList transactionListeners = new ManagedList(); + for (Element txListener : txListeners) { transactionListeners.add(ParsingUtils.parseRefOrNestedBeanDeclaration( parserContext, txListener, builder)); } + builder.addPropertyValue("transactionListeners", transactionListeners); } @@ -103,13 +105,6 @@ class CacheParser extends AbstractSimpleBeanDefinitionParser { parserContext, gatewayConflictResolver, builder)); } - Element function = DomUtils.getChildElementByTagName(element, "function"); - - if (function != null) { - builder.addPropertyValue("functions", ParsingUtils.parseRefOrNestedBeanDeclaration( - parserContext, function, builder)); - } - parseDynamicRegionFactory(element, builder); parseJndiBindings(element, builder); } diff --git a/src/main/java/org/springframework/data/gemfire/config/ClientCacheParser.java b/src/main/java/org/springframework/data/gemfire/config/ClientCacheParser.java index 26c38ebb..b7197e16 100644 --- a/src/main/java/org/springframework/data/gemfire/config/ClientCacheParser.java +++ b/src/main/java/org/springframework/data/gemfire/config/ClientCacheParser.java @@ -17,8 +17,6 @@ package org.springframework.data.gemfire.config; import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.data.gemfire.client.ClientCacheFactoryBean; import org.w3c.dom.Element; @@ -46,13 +44,6 @@ class ClientCacheParser extends CacheParser { ParsingUtils.setPropertyValue(element, builder, "keep-alive"); ParsingUtils.setPropertyValue(element, builder, "pool-name"); ParsingUtils.setPropertyValue(element, builder, "ready-for-events"); - registerClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor(getRegistry(parserContext)); - } - - /* (non-Javadoc) */ - void registerClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor(BeanDefinitionRegistry registry) { - BeanDefinitionReaderUtils.registerWithGeneratedName(BeanDefinitionBuilder.genericBeanDefinition( - ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor.class).getBeanDefinition(), registry); } @Override diff --git a/src/main/java/org/springframework/data/gemfire/config/ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor.java b/src/main/java/org/springframework/data/gemfire/config/ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor.java index 4b39d3f4..b89e36c0 100644 --- a/src/main/java/org/springframework/data/gemfire/config/ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor.java +++ b/src/main/java/org/springframework/data/gemfire/config/ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor.java @@ -40,7 +40,7 @@ import org.springframework.util.StringUtils; * @see org.springframework.data.gemfire.client.PoolFactoryBean * @since 1.8.0 */ -@SuppressWarnings("unused") +@Deprecated class ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor implements BeanFactoryPostProcessor { protected static final String PROPERTIES_PROPERTY_NAME = "properties"; diff --git a/src/main/java/org/springframework/data/gemfire/config/CustomEditorRegistrationBeanFactoryPostProcessor.java b/src/main/java/org/springframework/data/gemfire/config/CustomEditorRegistrationBeanFactoryPostProcessor.java index b3164740..97081cbf 100644 --- a/src/main/java/org/springframework/data/gemfire/config/CustomEditorRegistrationBeanFactoryPostProcessor.java +++ b/src/main/java/org/springframework/data/gemfire/config/CustomEditorRegistrationBeanFactoryPostProcessor.java @@ -16,9 +16,12 @@ package org.springframework.data.gemfire.config; +import java.beans.PropertyEditorSupport; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.core.convert.converter.Converter; import org.springframework.data.gemfire.EvictionActionConverter; import org.springframework.data.gemfire.EvictionPolicyConverter; import org.springframework.data.gemfire.EvictionPolicyType; @@ -32,6 +35,8 @@ import org.springframework.data.gemfire.ScopeConverter; import org.springframework.data.gemfire.client.InterestResultPolicyConverter; import org.springframework.data.gemfire.server.SubscriptionEvictionPolicy; import org.springframework.data.gemfire.server.SubscriptionEvictionPolicyConverter; +import org.springframework.data.gemfire.support.ConnectionEndpoint; +import org.springframework.data.gemfire.support.ConnectionEndpointList; import org.springframework.data.gemfire.wan.OrderPolicyConverter; import org.springframework.data.gemfire.wan.StartupPolicyConverter; import org.springframework.data.gemfire.wan.StartupPolicyType; @@ -56,7 +61,8 @@ import com.gemstone.gemfire.cache.util.Gateway; public class CustomEditorRegistrationBeanFactoryPostProcessor implements BeanFactoryPostProcessor { @Override - public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + beanFactory.registerCustomEditor(ConnectionEndpoint[].class, ConnectionEndpointArrayToIterableConverter.class); beanFactory.registerCustomEditor(EvictionAction.class, EvictionActionConverter.class); beanFactory.registerCustomEditor(EvictionPolicyType.class, EvictionPolicyConverter.class); beanFactory.registerCustomEditor(ExpirationAction.class, ExpirationActionConverter.class); @@ -70,4 +76,13 @@ public class CustomEditorRegistrationBeanFactoryPostProcessor implements BeanFac beanFactory.registerCustomEditor(SubscriptionEvictionPolicy.class, SubscriptionEvictionPolicyConverter.class); } + static final class ConnectionEndpointArrayToIterableConverter extends PropertyEditorSupport + implements Converter { + + @Override + public Iterable convert(ConnectionEndpoint[] source) { + return ConnectionEndpointList.from(source); + } + } + } diff --git a/src/main/java/org/springframework/data/gemfire/config/GemfireConstants.java b/src/main/java/org/springframework/data/gemfire/config/GemfireConstants.java index c68706e6..6ace0747 100644 --- a/src/main/java/org/springframework/data/gemfire/config/GemfireConstants.java +++ b/src/main/java/org/springframework/data/gemfire/config/GemfireConstants.java @@ -27,7 +27,7 @@ public interface GemfireConstants { static final String DEFAULT_GEMFIRE_CACHE_NAME = "gemfireCache"; static final String DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE = "gemfireIndexDefinitionQueryService"; static final String DEFAULT_GEMFIRE_FUNCTION_SERVICE_NAME = "gemfireFunctionService"; - static final String DEFAULT_GEMFIRE_POOL_NAME = "DEFAULT"; + static final String DEFAULT_GEMFIRE_POOL_NAME = "gemfirePool"; static final String DEFAULT_GEMFIRE_TRANSACTION_MANAGER_NAME = "gemfireTransactionManager"; @Deprecated diff --git a/src/main/java/org/springframework/data/gemfire/config/GemfireDataSourceParser.java b/src/main/java/org/springframework/data/gemfire/config/GemfireDataSourceParser.java index 381f3fbd..043b87c2 100644 --- a/src/main/java/org/springframework/data/gemfire/config/GemfireDataSourceParser.java +++ b/src/main/java/org/springframework/data/gemfire/config/GemfireDataSourceParser.java @@ -12,7 +12,10 @@ */ package org.springframework.data.gemfire.config; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; @@ -25,37 +28,37 @@ import org.w3c.dom.Element; * @author David Turanski * @author John Blum */ -public class GemfireDataSourceParser extends AbstractBeanDefinitionParser { +class GemfireDataSourceParser extends AbstractBeanDefinitionParser { + + static final String SUBSCRIPTION_ENABLED_ATTRIBUTE_NAME = "subscription-enabled"; + static final String SUBSCRIPTION_ENABLED_PROPERTY_NAME = "subscriptionEnabled"; + + protected final Log log = LogFactory.getLog(getClass()); /* (non-Javadoc) * @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#parseInternal(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) */ @Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { - AbstractBeanDefinition poolDefinition = (AbstractBeanDefinition) new PoolParser().parse(element, parserContext); - - MutablePropertyValues poolProperties = poolDefinition.getPropertyValues(); - - poolProperties.add("name", GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME); - - if (!element.hasAttribute("subscription-enabled")) { - poolProperties.add("subscriptionEnabled", true); - } - - parserContext.getRegistry().registerBeanDefinition(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME, poolDefinition); - - AbstractBeanDefinition clientCacheDefinition = (AbstractBeanDefinition) new ClientCacheParser() - .parse(element, parserContext); - - MutablePropertyValues clientCacheProperties = clientCacheDefinition.getPropertyValues(); - - clientCacheProperties.add("pool", poolDefinition); + BeanDefinition clientCacheDefinition = new ClientCacheParser().parse(element, parserContext); parserContext.getRegistry().registerBeanDefinition(GemfireConstants.DEFAULT_GEMFIRE_CACHE_NAME, clientCacheDefinition); - System.out.printf("Registered GemFire Client Cache bean '%1$s' of type '%2$s'%n", - GemfireConstants.DEFAULT_GEMFIRE_CACHE_NAME, clientCacheDefinition.getBeanClassName()); + BeanDefinition poolDefinition = new PoolParser().parse(element, parserContext); + + MutablePropertyValues poolProperties = poolDefinition.getPropertyValues(); + + if (!element.hasAttribute(SUBSCRIPTION_ENABLED_ATTRIBUTE_NAME)) { + poolProperties.add(SUBSCRIPTION_ENABLED_PROPERTY_NAME, true); + } + + parserContext.getRegistry().registerBeanDefinition(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME, poolDefinition); + + if (log.isDebugEnabled()) { + log.debug(String.format("Registered GemFire ClientCache bean [%1$s] of type [%2$s]%n", + GemfireConstants.DEFAULT_GEMFIRE_CACHE_NAME, clientCacheDefinition.getBeanClassName())); + } BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( GemfireDataSourcePostProcessor.class); diff --git a/src/main/java/org/springframework/data/gemfire/config/PoolParser.java b/src/main/java/org/springframework/data/gemfire/config/PoolParser.java index 26b3d5c1..4572ac33 100644 --- a/src/main/java/org/springframework/data/gemfire/config/PoolParser.java +++ b/src/main/java/org/springframework/data/gemfire/config/PoolParser.java @@ -23,15 +23,19 @@ import java.util.regex.Pattern; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.MethodInvokingBean; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.data.gemfire.GemfireUtils; import org.springframework.data.gemfire.client.PoolFactoryBean; import org.springframework.data.gemfire.support.ConnectionEndpoint; import org.springframework.data.gemfire.support.ConnectionEndpointList; -import org.springframework.data.gemfire.util.DistributedSystemUtils; +import org.springframework.data.gemfire.util.SpringUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; @@ -45,8 +49,8 @@ import org.w3c.dom.Element; */ class PoolParser extends AbstractSingleBeanDefinitionParser { - protected static final int DEFAULT_LOCATOR_PORT = DistributedSystemUtils.DEFAULT_LOCATOR_PORT; - protected static final int DEFAULT_SERVER_PORT = DistributedSystemUtils.DEFAULT_CACHE_SERVER_PORT; + protected static final int DEFAULT_LOCATOR_PORT = GemfireUtils.DEFAULT_LOCATOR_PORT; + protected static final int DEFAULT_SERVER_PORT = GemfireUtils.DEFAULT_CACHE_SERVER_PORT; protected static final Pattern PROPERTY_PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{.+\\}"); @@ -64,11 +68,11 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } @Override - protected void doParse(Element element, BeanDefinitionBuilder builder) { + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { ParsingUtils.setPropertyValue(element, builder, "free-connection-timeout"); ParsingUtils.setPropertyValue(element, builder, "idle-timeout"); - ParsingUtils.setPropertyValue(element, builder, "load-conditioning-interval"); ParsingUtils.setPropertyValue(element, builder, "keep-alive"); + ParsingUtils.setPropertyValue(element, builder, "load-conditioning-interval"); ParsingUtils.setPropertyValue(element, builder, "max-connections"); ParsingUtils.setPropertyValue(element, builder, "min-connections"); ParsingUtils.setPropertyValue(element, builder, "multi-user-authentication"); @@ -102,21 +106,21 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } } - locators.addAll(parseLocators(element, builder)); - servers.addAll(parseServers(element, builder)); + locators.addAll(parseLocators(element, getRegistry(parserContext))); + servers.addAll(parseServers(element, getRegistry(parserContext))); - // NOTE if neither Locators nor Servers were specified, then setup a default connection to a Locator - // listening on the default Locator port (10334), running on localhost + // NOTE if neither Locators nor Servers were specified, then setup a connection to a Server + // running on localhost, listening on the default CacheServer port, 40404 if (childElements.isEmpty() && !hasAttributes(element, LOCATORS_ATTRIBUTE_NAME, SERVERS_ATTRIBUTE_NAME)) { - locators.add(buildConnection(DEFAULT_HOST, String.valueOf(DEFAULT_LOCATOR_PORT), false)); + servers.add(buildConnection(DEFAULT_HOST, String.valueOf(DEFAULT_SERVER_PORT), false)); } if (!locators.isEmpty()) { - builder.addPropertyValue("locatorEndpoints", locators); + builder.addPropertyValue("locators", locators); } if (!servers.isEmpty()) { - builder.addPropertyValue("serverEndpoints", servers); + builder.addPropertyValue("servers", servers); } } @@ -131,6 +135,17 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { return false; } + /* (non-Javadoc) */ + boolean isPropertyPlaceholder(String value) { + return PROPERTY_PLACEHOLDER_PATTERN.matcher(value).matches(); + } + + /* (non-Javadoc) */ + BeanDefinitionRegistry getRegistry(ParserContext parserContext) { + return parserContext.getRegistry(); + } + + /* (non-Javadoc) */ BeanDefinition buildConnections(String propertyPlaceholder, boolean server) { BeanDefinitionBuilder connectionEndpointListBuilder = BeanDefinitionBuilder.genericBeanDefinition( ConnectionEndpointList.class); @@ -209,11 +224,6 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { return digits.toString(); } - /* (non-Javadoc) */ - boolean isPropertyPlaceholder(String value) { - return PROPERTY_PLACEHOLDER_PATTERN.matcher(value).matches(); - } - /* (non-Javadoc) */ BeanDefinition parseLocator(Element element) { return buildConnection(element.getAttribute(HOST_ATTRIBUTE_NAME), @@ -221,13 +231,24 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } /* (non-Javadoc) */ - List parseLocators(Element element, BeanDefinitionBuilder builder) { + List parseLocators(Element element, BeanDefinitionRegistry registry) { List beanDefinitions = Collections.emptyList(); String locatorsAttributeValue = element.getAttribute(LOCATORS_ATTRIBUTE_NAME); if (isPropertyPlaceholder(locatorsAttributeValue)) { - builder.addPropertyValue("locatorEndpointList", buildConnections(locatorsAttributeValue, false)); + BeanDefinitionBuilder addLocatorsMethodInvokingBeanBuilder = BeanDefinitionBuilder.genericBeanDefinition( + MethodInvokingBean.class); + + addLocatorsMethodInvokingBeanBuilder.addPropertyReference("targetObject", resolveDereferencedId(element)); + addLocatorsMethodInvokingBeanBuilder.addPropertyValue("targetMethod", "addLocators"); + addLocatorsMethodInvokingBeanBuilder.addPropertyValue("arguments", + buildConnections(locatorsAttributeValue, false)); + + AbstractBeanDefinition addLocatorsMethodInvokingBean = + addLocatorsMethodInvokingBeanBuilder.getBeanDefinition(); + + BeanDefinitionReaderUtils.registerWithGeneratedName(addLocatorsMethodInvokingBean, registry); } else { beanDefinitions = parseConnections(locatorsAttributeValue, false); @@ -243,13 +264,24 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { } /* (non-Javadoc) */ - List parseServers(Element element, BeanDefinitionBuilder builder) { + List parseServers(Element element, BeanDefinitionRegistry registry) { List beanDefinitions = Collections.emptyList(); String serversAttributeValue = element.getAttribute(SERVERS_ATTRIBUTE_NAME); if (isPropertyPlaceholder(serversAttributeValue)) { - builder.addPropertyValue("serverEndpointList", buildConnections(serversAttributeValue, true)); + BeanDefinitionBuilder addServersMethodInvokingBeanBuilder = BeanDefinitionBuilder.genericBeanDefinition( + MethodInvokingBean.class); + + addServersMethodInvokingBeanBuilder.addPropertyReference("targetObject", resolveDereferencedId(element)); + addServersMethodInvokingBeanBuilder.addPropertyValue("targetMethod", "addServers"); + addServersMethodInvokingBeanBuilder.addPropertyValue("arguments", + buildConnections(serversAttributeValue, true)); + + AbstractBeanDefinition addServersMethodInvokingBean = + addServersMethodInvokingBeanBuilder.getBeanDefinition(); + + BeanDefinitionReaderUtils.registerWithGeneratedName(addServersMethodInvokingBean, registry); } else { beanDefinitions = parseConnections(serversAttributeValue, true); @@ -258,6 +290,17 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { return beanDefinitions; } + /* (non-Javadoc) */ + String resolveId(Element element) { + String id = element.getAttribute(ID_ATTRIBUTE); + return (StringUtils.hasText(id) ? id : GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME); + } + + /* (non-Javadoc) */ + String resolveDereferencedId(Element element) { + return SpringUtils.dereferenceBean(resolveId(element)); + } + /* (non-Javadoc) */ @Override protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) @@ -267,8 +310,6 @@ class PoolParser extends AbstractSingleBeanDefinitionParser { if (!StringUtils.hasText(id)) { id = GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME; - // for backward compatibility - parserContext.getRegistry().registerAlias(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME, "gemfirePool"); parserContext.getRegistry().registerAlias(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME, "gemfire-pool"); } diff --git a/src/main/java/org/springframework/data/gemfire/listener/ContinuousQueryListenerContainer.java b/src/main/java/org/springframework/data/gemfire/listener/ContinuousQueryListenerContainer.java index d177d6de..9fc30044 100644 --- a/src/main/java/org/springframework/data/gemfire/listener/ContinuousQueryListenerContainer.java +++ b/src/main/java/org/springframework/data/gemfire/listener/ContinuousQueryListenerContainer.java @@ -24,6 +24,9 @@ import java.util.concurrent.Executor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; @@ -31,6 +34,8 @@ import org.springframework.context.SmartLifecycle; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.core.task.TaskExecutor; import org.springframework.data.gemfire.GemfireQueryException; +import org.springframework.data.gemfire.GemfireUtils; +import org.springframework.data.gemfire.config.GemfireConstants; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ErrorHandler; @@ -67,7 +72,8 @@ import com.gemstone.gemfire.cache.query.QueryService; * @see com.gemstone.gemfire.cache.query.QueryService */ @SuppressWarnings("unused") -public class ContinuousQueryListenerContainer implements BeanNameAware, InitializingBean, DisposableBean, SmartLifecycle { +public class ContinuousQueryListenerContainer implements BeanFactoryAware, BeanNameAware, + InitializingBean, DisposableBean, SmartLifecycle { // Default Thread name prefix is "ContinuousQueryListenerContainer-". public static final String DEFAULT_THREAD_NAME_PREFIX = String.format("%1$s-", ClassUtils.getShortName( @@ -81,6 +87,8 @@ public class ContinuousQueryListenerContainer implements BeanNameAware, Initiali private int phase = Integer.MAX_VALUE; + private BeanFactory beanFactory; + private ErrorHandler errorHandler; private Executor taskExecutor; @@ -97,7 +105,7 @@ public class ContinuousQueryListenerContainer implements BeanNameAware, Initiali private String poolName; public void afterPropertiesSet() { - initQueryService(); + initQueryService(eagerlyInitializePool(resolvePoolName())); initExecutor(); initContinuousQueries(continuousQueryDefinitions); initialized = true; @@ -107,12 +115,36 @@ public class ContinuousQueryListenerContainer implements BeanNameAware, Initiali } } - private void initQueryService() { - if (StringUtils.hasText(poolName)) { - Pool pool = PoolManager.find(poolName); - Assert.notNull(pool, String.format("No GemFire Pool with name '%1$s' was found.", poolName)); - queryService = pool.getQueryService(); + /* (non-Javadoc) */ + private String resolvePoolName() { + String poolName = this.poolName; + + if (!StringUtils.hasText(poolName)) { + String defaultPoolName = GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME; + poolName = (beanFactory != null && beanFactory.containsBean(defaultPoolName) ? defaultPoolName + : GemfireUtils.DEFAULT_POOL_NAME); } + + return poolName; + } + + /* (non-Javadoc) */ + private String eagerlyInitializePool(String poolName) { + try { + if (beanFactory != null && beanFactory.isTypeMatch(poolName, Pool.class)) { + beanFactory.getBean(poolName, Pool.class); + } + } + catch (BeansException ignore) { + Assert.notNull(PoolManager.find(poolName), String.format("No GemFire Pool with name [%1$s] was found.", + poolName)); + } + + return poolName; + } + + private void initQueryService(String poolName) { + queryService = PoolManager.find(poolName).getQueryService(); } private void initExecutor() { @@ -281,6 +313,17 @@ public class ContinuousQueryListenerContainer implements BeanNameAware, Initiali this.autoStartup = autoStartup; } + /** + * Sets the {@link BeanFactory} containing this bean. + * + * @param beanFactory the Spring {@link BeanFactory} containing this bean. + * @throws BeansException if an initialization error occurs. + */ + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + } + /** * Set the name of the bean in the bean factory that created this bean. *

Invoked after population of normal bean properties but before an diff --git a/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java b/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java index 9ea9a8a5..b2b21ad4 100644 --- a/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java +++ b/src/main/java/org/springframework/data/gemfire/support/ConnectionEndpoint.java @@ -150,6 +150,18 @@ public class ConnectionEndpoint implements Cloneable, Comparable { +public class ConnectionEndpointList extends AbstractList { private final List connectionEndpoints; /** - * Converts the array of InetSocketAddresses into an instance of ConnectionEndpointList. + * Factory method for creating a {@link ConnectionEndpointList} from an array of {@link ConnectionEndpoint}s. * - * @param socketAddresses the array of InetSocketAddresses used to initialize an instance of ConnectionEndpointList. - * @return a ConnectionEndpointList representing the array of InetSocketAddresses. + * @param connectionEndpoints the array of {@link ConnectionEndpoint}s used to initialize + * the {@link ConnectionEndpointList}. + * @return a {@link ConnectionEndpointList} initialized with the array of {@link ConnectionEndpoint}s. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + */ + public static ConnectionEndpointList from(ConnectionEndpoint... connectionEndpoints) { + return new ConnectionEndpointList(connectionEndpoints); + } + + /** + * Converts an array of {@link InetSocketAddress} into an instance of {@link ConnectionEndpointList}. + * + * @param socketAddresses the array of {@link InetSocketAddress} used to initialize + * an instance of {@link ConnectionEndpointList}. + * @return a {@link ConnectionEndpointList} initialized with the array of {@link InetSocketAddress}. * @see java.net.InetSocketAddress * @see #from(Iterable) */ @@ -53,11 +68,13 @@ public class ConnectionEndpointList implements Iterable { } /** - * Converts the Iterable collection of InetSocketAddresses into an instance of ConnectionEndpointList. + * Converts an {@link Iterable} collection of {@link InetSocketAddress} into an instance + * of {@link ConnectionEndpointList}. * - * @param socketAddresses in Iterable collection of InetSocketAddresses used to initialize an instance - * of ConnectionEndpointList. - * @return a ConnectionEndpointList representing the array of InetSocketAddresses. + * @param socketAddresses in {@link Iterable} collection of {@link InetSocketAddress} used to initialize + * an instance of {@link ConnectionEndpointList}. + * @return a {@link ConnectionEndpointList} initialized with the array of {@link InetSocketAddress}. + * @see java.lang.Iterable * @see java.net.InetSocketAddress */ public static ConnectionEndpointList from(Iterable socketAddresses) { @@ -119,6 +136,12 @@ public class ConnectionEndpointList implements Iterable { add(connectionEndpoints); } + /* (non-Javadoc) */ + @Override + public boolean add(ConnectionEndpoint connectionEndpoint) { + return (add(SpringUtils.toArray(connectionEndpoint)) == this); + } + /** * Adds the array of ConnectionEndpoints to this list. * @@ -148,6 +171,14 @@ public class ConnectionEndpointList implements Iterable { return this; } + /** + * Clears the current list of {@link ConnectionEndpoint}s. + */ + @Override + public void clear() { + this.connectionEndpoints.clear(); + } + /** * Finds all ConnectionEndpoints in this list with the specified hostname. * @@ -186,17 +217,75 @@ public class ConnectionEndpointList implements Iterable { return new ConnectionEndpointList(connectionEndpoints); } + /** + * Finds the first {@link ConnectionEndpoint} in the collection with the given host. + * + * @param host a String indicating the hostname of the {@link ConnectionEndpoint} to find. + * @return the first {@link ConnectionEndpoint} in this collection with the given host, + * or null if no {@link ConnectionEndpoint} exists with the given hostname. + * @see #findBy(String) + */ + public ConnectionEndpoint findOne(String host) { + ConnectionEndpointList connectionEndpoints = findBy(host); + return (connectionEndpoints.isEmpty() ? null : connectionEndpoints.connectionEndpoints.get(0)); + } + + /** + * Finds the first {@link ConnectionEndpoint} in the collection with the given port. + * + * @param port an integer indicating the port number of the {@link ConnectionEndpoint} to find. + * @return the first {@link ConnectionEndpoint} in this collection with the given port, + * or null if no {@link ConnectionEndpoint} exists with the given port number. + * @see #findBy(int) + */ + public ConnectionEndpoint findOne(int port) { + ConnectionEndpointList connectionEndpoints = findBy(port); + return (connectionEndpoints.isEmpty() ? null : connectionEndpoints.connectionEndpoints.get(0)); + } + + /** + * Gets the {@link ConnectionEndpoint} at the given index in this list. + * + * @param index an integer value indicating the index of the {@link ConnectionEndpoint} of interest. + * @return the {@link ConnectionEndpoint} at index in this list. + * @throws IndexOutOfBoundsException if the index is not within the bounds of this list. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see java.util.AbstractList#get(int) + */ + @Override + public ConnectionEndpoint get(int index) { + return connectionEndpoints.get(index); + } + + /** + * Sets the element at the given index in this list to the given {@link ConnectionEndpoint}. + * + * @param index the index in the list at which to set the {@link ConnectionEndpoint}. + * @param element the {@link ConnectionEndpoint} to set in this list at the given index. + * @return the old {@link ConnectionEndpoint} at index in this list or null if no {@link ConnectionEndpoint} + * at index existed. + * @throws IndexOutOfBoundsException if the index is not within the bounds of this list. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see java.util.AbstractList#set(int, Object) + */ + @Override + public ConnectionEndpoint set(int index, ConnectionEndpoint element) { + return connectionEndpoints.set(index, element); + } + /** * Determines whether this collection contains any ConnectionEndpoints. * * @return a boolean value indicating whether this collection contains any ConnectionEndpoints. */ + @Override public boolean isEmpty() { return connectionEndpoints.isEmpty(); } /* (non-Javadoc) */ @Override + @SuppressWarnings("all") public Iterator iterator() { return Collections.unmodifiableList(connectionEndpoints).iterator(); } @@ -206,10 +295,40 @@ public class ConnectionEndpointList implements Iterable { * * @return an integer value indicating the number of ConnectionEndpoints contained in this collection. */ + @Override public int size() { return connectionEndpoints.size(); } + /** + * Converts this collection of {@link ConnectionEndpoint}s into an array of {@link ConnectionEndpoint}s. + * + * @return an array of {@link ConnectionEndpoint}s representing this collection. + */ + @Override + @SuppressWarnings("all") + public ConnectionEndpoint[] toArray() { + return connectionEndpoints.toArray(new ConnectionEndpoint[connectionEndpoints.size()]); + } + + /** + * Converts this collection of {@link ConnectionEndpoint}s into a {@link List} of {@link InetSocketAddress}es. + * + * @return a {@link List} of {@link InetSocketAddress}es representing this collection of {@link ConnectionEndpoint}s. + * @see org.springframework.data.gemfire.support.ConnectionEndpoint#toInetSocketAddress() + * @see java.net.InetSocketAddress + * @see java.util.List + */ + public List toInetSocketAddresses() { + List inetSocketAddresses = new ArrayList(size()); + + for (ConnectionEndpoint connectionEndpoint : this) { + inetSocketAddresses.add(connectionEndpoint.toInetSocketAddress()); + } + + return inetSocketAddresses; + } + /* (non-Javadoc) */ @Override public String toString() { diff --git a/src/main/java/org/springframework/data/gemfire/util/CacheUtils.java b/src/main/java/org/springframework/data/gemfire/util/CacheUtils.java new file mode 100644 index 00000000..195e95d0 --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/util/CacheUtils.java @@ -0,0 +1,129 @@ +/* + * Copyright 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.util; + +import org.springframework.util.StringUtils; + +import com.gemstone.gemfire.cache.Cache; +import com.gemstone.gemfire.cache.CacheClosedException; +import com.gemstone.gemfire.cache.CacheFactory; +import com.gemstone.gemfire.cache.GemFireCache; +import com.gemstone.gemfire.cache.client.ClientCache; +import com.gemstone.gemfire.cache.client.ClientCacheFactory; +import com.gemstone.gemfire.distributed.DistributedSystem; +import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; + +/** + * CacheUtils is an abstract utility class encapsulating common operations for working with GemFire Cache + * and ClientCache instances. + * + * @author John Blum + * @see org.springframework.data.gemfire.util.DistributedSystemUtils + * @see com.gemstone.gemfire.cache.Cache + * @see com.gemstone.gemfire.cache.CacheFactory + * @see com.gemstone.gemfire.cache.GemFireCache + * @see com.gemstone.gemfire.cache.Region + * @see com.gemstone.gemfire.cache.client.ClientCache + * @see com.gemstone.gemfire.cache.client.ClientCacheFactory + * @see com.gemstone.gemfire.distributed.DistributedSystem + * @see com.gemstone.gemfire.internal.cache.GemFireCacheImpl + * @since 1.8.0 + */ +@SuppressWarnings("unused") +public abstract class CacheUtils extends DistributedSystemUtils { + + public static final String DEFAULT_POOL_NAME = "DEFAULT"; + + /* (non-Javadoc) */ + @SuppressWarnings("all") + public static boolean isClient(GemFireCache cache) { + boolean client = (cache instanceof ClientCache); + + if (cache instanceof GemFireCacheImpl) { + client &= ((GemFireCacheImpl) cache).isClient(); + } + + return client; + } + + /* (non-Javadoc) */ + public static boolean isDurable(ClientCache clientCache) { + DistributedSystem distributedSystem = getDistributedSystem(clientCache); + + // NOTE technically the following code snippet would be more useful/valuable but is not "testable"! + //((InternalDistributedSystem) distributedSystem).getConfig().getDurableClientId(); + + return (isConnected(distributedSystem) && StringUtils.hasText(distributedSystem.getProperties() + .getProperty(DURABLE_CLIENT_ID_PROPERTY_NAME, null))); + } + + /* (non-Javadoc) */ + @SuppressWarnings("all") + public static boolean isPeer(GemFireCache cache) { + boolean peer = (cache instanceof Cache); + + if (cache instanceof GemFireCacheImpl) { + peer &= !((GemFireCacheImpl) cache).isClient(); + } + + return peer; + } + + /* (non-Javadoc) */ + public static boolean closeCache() { + try { + CacheFactory.getAnyInstance().close(); + return true; + } + catch (Exception ignore) { + return false; + } + } + + /* (non-Javadoc) */ + public static boolean closeClientCache() { + try { + ClientCacheFactory.getAnyInstance().close(); + return true; + } + catch (Exception ignore) { + return false; + } + } + + /* (non-Javadoc) */ + public static Cache getCache() { + try { + return CacheFactory.getAnyInstance(); + } + catch (CacheClosedException ignore) { + return null; + } + } + + /* (non-Javadoc) */ + public static ClientCache getClientCache() { + try { + return ClientCacheFactory.getAnyInstance(); + } + catch (CacheClosedException ignore) { + return null; + } + } + +} diff --git a/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java b/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java index 2f6609fd..72002c5c 100644 --- a/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java +++ b/src/main/java/org/springframework/data/gemfire/util/DistributedSystemUtils.java @@ -34,10 +34,13 @@ import com.gemstone.gemfire.internal.DistributionLocator; * @author John Blum * @see com.gemstone.gemfire.cache.GemFireCache * @see com.gemstone.gemfire.distributed.DistributedSystem + * @see com.gemstone.gemfire.distributed.internal.DistributionConfig + * @see com.gemstone.gemfire.distributed.internal.InternalDistributedSystem + * @see com.gemstone.gemfire.internal.DistributionLocator * @since 1.7.0 */ @SuppressWarnings("unused") -public abstract class DistributedSystemUtils { +public abstract class DistributedSystemUtils extends SpringUtils { public static final int DEFAULT_CACHE_SERVER_PORT = CacheServer.DEFAULT_PORT; public static final int DEFAULT_LOCATOR_PORT = DistributionLocator.DEFAULT_LOCATOR_PORT; @@ -46,7 +49,9 @@ public abstract class DistributedSystemUtils { public static final String DURABLE_CLIENT_TIMEOUT_PROPERTY_NAME = DistributionConfig.DURABLE_CLIENT_TIMEOUT_NAME; /* (non-Javadoc) */ - public static Properties configureDurableClient(Properties gemfireProperties, String durableClientId, Integer durableClientTimeout) { + public static Properties configureDurableClient(Properties gemfireProperties, + String durableClientId, Integer durableClientTimeout) { + if (StringUtils.hasText(durableClientId)) { Assert.notNull(gemfireProperties, "gemfireProperties must not be null"); diff --git a/src/main/java/org/springframework/data/gemfire/util/SpringUtils.java b/src/main/java/org/springframework/data/gemfire/util/SpringUtils.java new file mode 100644 index 00000000..5ddd715b --- /dev/null +++ b/src/main/java/org/springframework/data/gemfire/util/SpringUtils.java @@ -0,0 +1,68 @@ +/* + * Copyright 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.util; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.util.StringUtils; + +/** + * SpringUtils is a utility class encapsulating common functionality on objects and other class types. + * + * @author John Blum + * @since 1.8.0 + */ +@SuppressWarnings("unused") +public abstract class SpringUtils { + + /* (non-Javadoc) */ + public static String defaultIfEmpty(String value, String defaultValue) { + return (StringUtils.hasText(value) ? value : defaultValue); + } + + /* (non-Javadoc) */ + public static T defaultIfNull(T value, T defaultValue) { + return (value != null ? value : defaultValue); + } + + /* (non-Javadoc) */ + public static String dereferenceBean(String beanName) { + return String.format("%1$s%2$s", BeanFactory.FACTORY_BEAN_PREFIX, beanName); + } + + /* (non-Javadoc) */ + public static T[] toArray(T... array) { + return array; + } + + /* (non-Javadoc) */ + public static > T[] sort(T[] array) { + Arrays.sort(array); + return array; + } + + /* (non-Javadoc) */ + public static > List sort(List list) { + Collections.sort(list); + return list; + } + +} diff --git a/src/test/java/org/springframework/data/gemfire/CacheFactoryBeanTest.java b/src/test/java/org/springframework/data/gemfire/CacheFactoryBeanTest.java index 2d6c274e..5a3da1ac 100644 --- a/src/test/java/org/springframework/data/gemfire/CacheFactoryBeanTest.java +++ b/src/test/java/org/springframework/data/gemfire/CacheFactoryBeanTest.java @@ -16,9 +16,13 @@ package org.springframework.data.gemfire; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -42,13 +46,16 @@ import java.util.Collections; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.access.BeanFactoryReference; import org.springframework.core.io.Resource; import org.springframework.data.util.ReflectionUtils; import com.gemstone.gemfire.cache.Cache; +import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.cache.CacheTransactionManager; import com.gemstone.gemfire.cache.GemFireCache; @@ -66,29 +73,152 @@ import com.gemstone.gemfire.pdx.PdxSerializer; * of the CacheFactoryBean class. * * @author John Blum - * @see org.mockito.Mockito + * @see org.junit.Rule * @see org.junit.Test + * @see org.junit.rules.ExpectedException + * @see org.mockito.Mockito * @see org.springframework.data.gemfire.CacheFactoryBean * @see com.gemstone.gemfire.cache.Cache * @since 1.7.0 */ public class CacheFactoryBeanTest { + @Rule + public ExpectedException exception = ExpectedException.none(); + @Test public void afterPropertiesSet() throws Exception { - BeanFactory mockBeanFactory = mock(BeanFactory.class, "SpringBeanFactory"); - Cache mockCache = mock(Cache.class, "GemFireCache"); - CacheTransactionManager mockCacheTransactionManager = mock(CacheTransactionManager.class, "GemFireTransactionManager"); - DistributedMember mockDistributedMember = mock(DistributedMember.class, "GemFireDistributedMember"); - DistributedSystem mockDistributedSystem = mock(DistributedSystem.class, "GemFireDistributedSystem"); - GatewayConflictResolver mockGatewayConflictResolver = mock(GatewayConflictResolver.class, "GemFireGatewayConflictResolver"); - PdxSerializer mockPdxSerializer = mock(PdxSerializer.class, "GemFirePdxSerializer"); - Resource mockCacheXml = mock(Resource.class, "GemFireCacheXml"); - ResourceManager mockResourceManager = mock(ResourceManager.class, "GemFireResourceManager"); - TransactionListener mockTransactionLister = mock(TransactionListener.class, "GemFireTransactionListener"); - TransactionWriter mockTransactionWriter = mock(TransactionWriter.class, "GemFireTransactionWriter"); + final AtomicBoolean postProcessBeforeCacheInitializationCalled = new AtomicBoolean(false); + final Properties gemfireProperties = new Properties(); - final CacheFactory mockCacheFactory = mock(CacheFactory.class, "GemFireCacheFactory"); + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { + @Override protected void postProcessBeforeCacheInitialization(Properties actualGemfireProperties) { + assertThat(actualGemfireProperties, is(sameInstance(gemfireProperties))); + postProcessBeforeCacheInitializationCalled.set(true); + } + }; + + cacheFactoryBean.setProperties(gemfireProperties); + cacheFactoryBean.afterPropertiesSet(); + + assertThat(postProcessBeforeCacheInitializationCalled.get(), is(true)); + } + + @Test + public void postProcessBeforeCacheInitializationUsingDefaults() { + assumeTrue(GemfireUtils.isGemfireVersion8OrAbove()); + + Properties gemfireProperties = new Properties(); + + new CacheFactoryBean().postProcessBeforeCacheInitialization(gemfireProperties); + + assertThat(gemfireProperties.size(), is(equalTo(2))); + assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true)); + assertThat(gemfireProperties.containsKey("use-cluster-configuration"), is(true)); + assertThat(gemfireProperties.getProperty("disable-auto-reconnect"), is(equalTo("true"))); + assertThat(gemfireProperties.getProperty("use-cluster-configuration"), is(equalTo("false"))); + } + + @Test + public void postProcessBeforeCacheInitializationWithAutoReconnectAndClusterConfigurationDisabled() { + assumeTrue(GemfireUtils.isGemfireVersion8OrAbove()); + + Properties gemfireProperties = new Properties(); + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); + + cacheFactoryBean.setEnableAutoReconnect(false); + cacheFactoryBean.setUseClusterConfiguration(false); + cacheFactoryBean.postProcessBeforeCacheInitialization(gemfireProperties); + + assertThat(gemfireProperties.size(), is(equalTo(2))); + assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true)); + assertThat(gemfireProperties.containsKey("use-cluster-configuration"), is(true)); + assertThat(gemfireProperties.getProperty("disable-auto-reconnect"), is(equalTo("true"))); + assertThat(gemfireProperties.getProperty("use-cluster-configuration"), is(equalTo("false"))); + } + + @Test + public void postProcessBeforeCacheInitializationWithAutoReconnectAndClusterConfigurationEnabled() { + assumeTrue(GemfireUtils.isGemfireVersion8OrAbove()); + + Properties gemfireProperties = new Properties(); + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); + + cacheFactoryBean.setEnableAutoReconnect(true); + cacheFactoryBean.setUseClusterConfiguration(true); + cacheFactoryBean.postProcessBeforeCacheInitialization(gemfireProperties); + + assertThat(gemfireProperties.size(), is(equalTo(2))); + assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true)); + assertThat(gemfireProperties.containsKey("use-cluster-configuration"), is(true)); + assertThat(gemfireProperties.getProperty("disable-auto-reconnect"), is(equalTo("false"))); + assertThat(gemfireProperties.getProperty("use-cluster-configuration"), is(equalTo("true"))); + } + + @Test + public void postProcessBeforeCacheInitializationWithAutoReconnectDisabledAndClusterConfigurationEnabled() { + assumeTrue(GemfireUtils.isGemfireVersion8OrAbove()); + + Properties gemfireProperties = new Properties(); + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); + + cacheFactoryBean.setEnableAutoReconnect(false); + cacheFactoryBean.setUseClusterConfiguration(true); + cacheFactoryBean.postProcessBeforeCacheInitialization(gemfireProperties); + + assertThat(gemfireProperties.size(), is(equalTo(2))); + assertThat(gemfireProperties.containsKey("disable-auto-reconnect"), is(true)); + assertThat(gemfireProperties.containsKey("use-cluster-configuration"), is(true)); + assertThat(gemfireProperties.getProperty("disable-auto-reconnect"), is(equalTo("true"))); + assertThat(gemfireProperties.getProperty("use-cluster-configuration"), is(equalTo("true"))); + } + + @Test + public void getObjectCallsInit() throws Exception { + final Cache mockCache = mock(Cache.class); + + final AtomicBoolean initCalled = new AtomicBoolean(false); + + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { + @Override Cache init() throws Exception { + initCalled.set(true); + return mockCache; + } + }; + + assertThat(cacheFactoryBean.getObject(), is(sameInstance(mockCache))); + assertThat(initCalled.get(), is(true)); + + verifyZeroInteractions(mockCache); + } + + @Test + public void getObjectReturnsExistingCache() throws Exception { + Cache mockCache = mock(Cache.class); + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); + + cacheFactoryBean.setCache(mockCache); + + assertThat(cacheFactoryBean.getObject(), is(sameInstance(mockCache))); + + verifyZeroInteractions(mockCache); + } + + @Test + public void init() throws Exception { + BeanFactory mockBeanFactory = mock(BeanFactory.class); + Cache mockCache = mock(Cache.class); + CacheTransactionManager mockCacheTransactionManager = mock(CacheTransactionManager.class); + DistributedMember mockDistributedMember = mock(DistributedMember.class); + DistributedSystem mockDistributedSystem = mock(DistributedSystem.class); + GatewayConflictResolver mockGatewayConflictResolver = mock(GatewayConflictResolver.class); + PdxSerializer mockPdxSerializer = mock(PdxSerializer.class); + Resource mockCacheXml = mock(Resource.class); + ResourceManager mockResourceManager = mock(ResourceManager.class); + TransactionListener mockTransactionLister = mock(TransactionListener.class); + TransactionWriter mockTransactionWriter = mock(TransactionWriter.class); + + final CacheFactory mockCacheFactory = mock(CacheFactory.class); when(mockCacheFactory.create()).thenReturn(mockCache); when(mockCache.getCacheTransactionManager()).thenReturn(mockCacheTransactionManager); @@ -109,8 +239,8 @@ public class CacheFactoryBeanTest { CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { @Override protected Object createFactory(final Properties actualGemfireProperties) { - assertSame(gemfireProperties, actualGemfireProperties); - assertSame(ClassLoader.getSystemClassLoader(), getBeanClassLoader()); + assertThat(actualGemfireProperties, is(equalTo(gemfireProperties))); + assertThat(getBeanClassLoader(), is(equalTo(ClassLoader.getSystemClassLoader()))); return mockCacheFactory; } }; @@ -129,36 +259,29 @@ public class CacheFactoryBeanTest { cacheFactoryBean.setLockLease(15000); cacheFactoryBean.setLockTimeout(5000); cacheFactoryBean.setMessageSyncInterval(20000); - cacheFactoryBean.setPdxSerializer(mockPdxSerializer); - cacheFactoryBean.setPdxReadSerialized(true); - cacheFactoryBean.setPdxPersistent(true); - cacheFactoryBean.setPdxIgnoreUnreadFields(false); cacheFactoryBean.setPdxDiskStoreName("TestPdxDiskStore"); + cacheFactoryBean.setPdxIgnoreUnreadFields(false); + cacheFactoryBean.setPdxPersistent(true); + cacheFactoryBean.setPdxReadSerialized(true); + cacheFactoryBean.setPdxSerializer(mockPdxSerializer); cacheFactoryBean.setProperties(gemfireProperties); cacheFactoryBean.setSearchTimeout(45000); cacheFactoryBean.setTransactionListeners(Collections.singletonList(mockTransactionLister)); cacheFactoryBean.setTransactionWriter(mockTransactionWriter); cacheFactoryBean.setUseBeanFactoryLocator(true); - assertTrue(gemfireProperties.isEmpty()); + cacheFactoryBean.init(); - cacheFactoryBean.afterPropertiesSet(); - - assertEquals(2, gemfireProperties.size()); - assertTrue(gemfireProperties.containsKey("disable-auto-reconnect")); - assertTrue(gemfireProperties.containsKey("use-cluster-configuration")); - assertEquals("true", gemfireProperties.getProperty("disable-auto-reconnect")); - assertEquals("false", gemfireProperties.getProperty("use-cluster-configuration")); - assertSame(expectedThreadContextClassLoader, Thread.currentThread().getContextClassLoader()); + assertThat(Thread.currentThread().getContextClassLoader(), is(sameInstance(expectedThreadContextClassLoader))); GemfireBeanFactoryLocator beanFactoryLocator = cacheFactoryBean.getBeanFactoryLocator(); - assertNotNull(beanFactoryLocator); + assertThat(beanFactoryLocator, is(notNullValue())); BeanFactoryReference beanFactoryReference = beanFactoryLocator.useBeanFactory("TestGemFireCache"); - assertNotNull(beanFactoryReference); - assertSame(mockBeanFactory, beanFactoryReference.getFactory()); + assertThat(beanFactoryReference, is(notNullValue())); + assertThat(beanFactoryReference.getFactory(), is(sameInstance(mockBeanFactory))); verify(mockCacheFactory, times(1)).setPdxDiskStore(eq("TestPdxDiskStore")); verify(mockCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false)); @@ -166,104 +289,96 @@ public class CacheFactoryBeanTest { verify(mockCacheFactory, times(1)).setPdxReadSerialized(eq(true)); verify(mockCacheFactory, times(1)).setPdxSerializer(eq(mockPdxSerializer)); verify(mockCacheFactory, times(1)).create(); + verify(mockCache, times(2)).getCacheTransactionManager(); verify(mockCache, times(1)).loadCacheXml(any(InputStream.class)); verify(mockCache, times(1)).setCopyOnRead(eq(true)); verify(mockCache, times(1)).setGatewayConflictResolver(same(mockGatewayConflictResolver)); verify(mockCache, times(1)).setLockLease(eq(15000)); verify(mockCache, times(1)).setLockTimeout(eq(5000)); verify(mockCache, times(1)).setMessageSyncInterval(eq(20000)); - verify(mockCache, times(1)).setSearchTimeout(eq(45000)); verify(mockCache, times(2)).getResourceManager(); + verify(mockCache, times(1)).setSearchTimeout(eq(45000)); verify(mockResourceManager, times(1)).setCriticalHeapPercentage(eq(0.90f)); verify(mockResourceManager, times(1)).setEvictionHeapPercentage(eq(0.75f)); - verify(mockCache, times(2)).getCacheTransactionManager(); verify(mockCacheTransactionManager, times(1)).addListener(same(mockTransactionLister)); verify(mockCacheTransactionManager, times(1)).setWriter(same(mockTransactionWriter)); } @Test - public void postProcessPropertiesBeforeInitializationDefaults() { - assumeTrue(GemfireUtils.isGemfireVersion8OrAbove()); + public void resolveCacheCallsFetchCacheReturnsMock() { + final Cache mockCache = mock(Cache.class); - Properties gemfireProperties = new Properties(); + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { + @Override @SuppressWarnings("unchecked ") + protected T fetchCache() { + return (T) mockCache; + } + }; - assertTrue(gemfireProperties.isEmpty()); + assertThat(cacheFactoryBean.resolveCache(), is(sameInstance(mockCache))); - CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); - - cacheFactoryBean.postProcessPropertiesBeforeInitialization(gemfireProperties); - - assertEquals(2, gemfireProperties.size()); - assertTrue(gemfireProperties.containsKey("disable-auto-reconnect")); - assertTrue(gemfireProperties.containsKey("use-cluster-configuration")); - assertEquals("true", gemfireProperties.getProperty("disable-auto-reconnect")); - assertEquals("false", gemfireProperties.getProperty("use-cluster-configuration")); + verifyZeroInteractions(mockCache); } @Test - public void postProcessPropertiesBeforeInitializationDisabled() { - assumeTrue(GemfireUtils.isGemfireVersion8OrAbove()); + public void resolveCacheCreatesCacheWhenFetchCacheThrowsCacheClosedException() { + final Cache mockCache = mock(Cache.class); + final CacheFactory mockCacheFactory = mock(CacheFactory.class); - Properties gemfireProperties = new Properties(); + when(mockCacheFactory.create()).thenReturn(mockCache); - assertTrue(gemfireProperties.isEmpty()); + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { + @Override protected T fetchCache() { + throw new CacheClosedException("test"); + } - CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); + @Override + protected Object createFactory(final Properties gemfireProperties) { + assertThat(gemfireProperties, is(sameInstance(getProperties()))); + return mockCacheFactory; + } + }; - cacheFactoryBean.setEnableAutoReconnect(false); - cacheFactoryBean.setUseClusterConfiguration(false); - cacheFactoryBean.postProcessPropertiesBeforeInitialization(gemfireProperties); + assertThat(cacheFactoryBean.resolveCache(), is(equalTo(mockCache))); - assertEquals(2, gemfireProperties.size()); - assertTrue(gemfireProperties.containsKey("disable-auto-reconnect")); - assertTrue(gemfireProperties.containsKey("use-cluster-configuration")); - assertEquals("true", gemfireProperties.getProperty("disable-auto-reconnect")); - assertEquals("false", gemfireProperties.getProperty("use-cluster-configuration")); - } - - @Test - public void postProcessPropertiesBeforeInitializationEnabled() { - assumeTrue(GemfireUtils.isGemfireVersion8OrAbove()); - - Properties gemfireProperties = new Properties(); - - assertTrue(gemfireProperties.isEmpty()); - - CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); - - cacheFactoryBean.setEnableAutoReconnect(true); - cacheFactoryBean.setUseClusterConfiguration(true); - cacheFactoryBean.postProcessPropertiesBeforeInitialization(gemfireProperties); - - assertEquals(2, gemfireProperties.size()); - assertTrue(gemfireProperties.containsKey("disable-auto-reconnect")); - assertTrue(gemfireProperties.containsKey("use-cluster-configuration")); - assertEquals("false", gemfireProperties.getProperty("disable-auto-reconnect")); - assertEquals("true", gemfireProperties.getProperty("use-cluster-configuration")); + verify(mockCacheFactory, times(1)).create(); + verifyZeroInteractions(mockCache); } @Test public void fetchExistingCache() throws Exception { - Cache mockCache = mock(Cache.class, "GemFireCache"); - + Cache mockCache = mock(Cache.class); CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); - ReflectionUtils.setField(CacheFactoryBean.class.getDeclaredField("cache"), cacheFactoryBean, mockCache); + cacheFactoryBean.setCache(mockCache); - Cache actualCache = cacheFactoryBean.resolveCache(); + Cache actualCache = cacheFactoryBean.fetchCache(); - assertSame(mockCache, actualCache); + assertThat(actualCache, is(sameInstance(mockCache))); + + verifyZeroInteractions(mockCache); } @Test public void resolveProperties() { Properties gemfireProperties = new Properties(); - CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); cacheFactoryBean.setProperties(gemfireProperties); - assertSame(gemfireProperties, cacheFactoryBean.resolveProperties()); + assertThat(cacheFactoryBean.resolveProperties(), is(sameInstance(gemfireProperties))); + } + + @Test + public void resolvePropertiesWhenNull() { + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); + + cacheFactoryBean.setProperties(null); + + Properties gemfireProperties = cacheFactoryBean.resolveProperties(); + + assertThat(gemfireProperties, is(notNullValue())); + assertThat(gemfireProperties.isEmpty(), is(true)); } @Test @@ -271,87 +386,93 @@ public class CacheFactoryBeanTest { Properties gemfireProperties = new Properties(); Object cacheFactoryReference = new CacheFactoryBean().createFactory(gemfireProperties); - assertTrue(gemfireProperties.isEmpty()); - assertTrue(cacheFactoryReference instanceof CacheFactory); + assertThat(cacheFactoryReference, is(instanceOf(CacheFactory.class))); + assertThat(gemfireProperties.isEmpty(), is(true)); CacheFactory cacheFactory = (CacheFactory) cacheFactoryReference; cacheFactory.set("name", "TestCreateCacheFactory"); - assertTrue(gemfireProperties.containsKey("name")); - assertEquals("TestCreateCacheFactory", gemfireProperties.getProperty("name")); + assertThat(gemfireProperties.containsKey("name"), is(true)); + assertThat(gemfireProperties.getProperty("name"), is(equalTo("TestCreateCacheFactory"))); } @Test public void prepareFactoryWithUnspecifiedPdxOptions() { - CacheFactory mockCacheFactory = mock(CacheFactory.class, "MockGemFireCacheFactory"); + CacheFactory mockCacheFactory = mock(CacheFactory.class); - assertSame(mockCacheFactory, new CacheFactoryBean().prepareFactory(mockCacheFactory)); + assertThat((CacheFactory) new CacheFactoryBean().prepareFactory(mockCacheFactory), + is(sameInstance(mockCacheFactory))); - verify(mockCacheFactory, never()).setPdxSerializer(any(PdxSerializer.class)); verify(mockCacheFactory, never()).setPdxDiskStore(any(String.class)); verify(mockCacheFactory, never()).setPdxIgnoreUnreadFields(any(Boolean.class)); verify(mockCacheFactory, never()).setPdxPersistent(any(Boolean.class)); verify(mockCacheFactory, never()).setPdxReadSerialized(any(Boolean.class)); + verify(mockCacheFactory, never()).setPdxSerializer(any(PdxSerializer.class)); } @Test - public void prepareFactoryWithPartialPdxOptions() { + public void prepareFactoryWithSpecificPdxOptions() { CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); - cacheFactoryBean.setPdxSerializer(mock(PdxSerializer.class, "MockGemFirePdxSerializer")); + cacheFactoryBean.setPdxSerializer(mock(PdxSerializer.class)); cacheFactoryBean.setPdxReadSerialized(true); cacheFactoryBean.setPdxIgnoreUnreadFields(false); - CacheFactory mockCacheFactory = mock(CacheFactory.class, "MockGemFireCacheFactory"); + CacheFactory mockCacheFactory = mock(CacheFactory.class); - assertSame(mockCacheFactory, cacheFactoryBean.prepareFactory(mockCacheFactory)); + assertThat((CacheFactory) cacheFactoryBean.prepareFactory(mockCacheFactory), + is(sameInstance(mockCacheFactory))); - verify(mockCacheFactory, times(1)).setPdxSerializer(any(PdxSerializer.class)); verify(mockCacheFactory, never()).setPdxDiskStore(any(String.class)); verify(mockCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false)); verify(mockCacheFactory, never()).setPdxPersistent(any(Boolean.class)); verify(mockCacheFactory, times(1)).setPdxReadSerialized(eq(true)); + verify(mockCacheFactory, times(1)).setPdxSerializer(any(PdxSerializer.class)); } @Test public void prepareFactoryWithAllPdxOptions() { CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); - cacheFactoryBean.setPdxSerializer(mock(PdxSerializer.class, "MockGemFirePdxSerializer")); cacheFactoryBean.setPdxDiskStoreName("testPdxDiskStoreName"); cacheFactoryBean.setPdxIgnoreUnreadFields(false); cacheFactoryBean.setPdxPersistent(true); cacheFactoryBean.setPdxReadSerialized(true); + cacheFactoryBean.setPdxSerializer(mock(PdxSerializer.class)); - CacheFactory mockCacheFactory = mock(CacheFactory.class, "MockGemFireCacheFactory"); + CacheFactory mockCacheFactory = mock(CacheFactory.class); - assertSame(mockCacheFactory, cacheFactoryBean.prepareFactory(mockCacheFactory)); + assertThat((CacheFactory) cacheFactoryBean.prepareFactory(mockCacheFactory), + is(sameInstance(mockCacheFactory))); - verify(mockCacheFactory, times(1)).setPdxSerializer(any(PdxSerializer.class)); verify(mockCacheFactory, times(1)).setPdxDiskStore(eq("testPdxDiskStoreName")); verify(mockCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false)); verify(mockCacheFactory, times(1)).setPdxPersistent(eq(true)); verify(mockCacheFactory, times(1)).setPdxReadSerialized(eq(true)); + verify(mockCacheFactory, times(1)).setPdxSerializer(any(PdxSerializer.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void prepareFactoryWithInvalidTypeForPdxSerializer() { - CacheFactory mockCacheFactory = mock(CacheFactory.class, "MockGemFireCacheFactory"); + CacheFactory mockCacheFactory = mock(CacheFactory.class); + + Object pdxSerializer = new Object(); try { CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); - cacheFactoryBean.setPdxSerializer(new Object()); + cacheFactoryBean.setPdxSerializer(pdxSerializer); cacheFactoryBean.setPdxIgnoreUnreadFields(false); cacheFactoryBean.setPdxReadSerialized(true); + + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage(containsString(String.format( + "[%1$s] of type [java.lang.Object] is not a PdxSerializer", pdxSerializer))); + cacheFactoryBean.prepareFactory(mockCacheFactory); } - catch (IllegalArgumentException expected) { - assertTrue(expected.getMessage().startsWith("Invalid pdx serializer used")); - assertNull(expected.getCause()); - throw expected; - } finally { verify(mockCacheFactory, never()).setPdxSerializer(any(PdxSerializer.class)); verify(mockCacheFactory, never()).setPdxDiskStore(any(String.class)); @@ -363,21 +484,22 @@ public class CacheFactoryBeanTest { @Test public void createCacheWithExistingCache() throws Exception { - Cache mockCache = mock(Cache.class, "MockGemFireCache"); - + Cache mockCache = mock(Cache.class); CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); - ReflectionUtils.setField(CacheFactoryBean.class.getDeclaredField("cache"), cacheFactoryBean, mockCache); + cacheFactoryBean.setCache(mockCache); - GemFireCache actualCache = cacheFactoryBean.createCache(null); + Cache actualCache = cacheFactoryBean.createCache(null); - assertSame(mockCache, actualCache); + assertThat(actualCache, is(sameInstance(mockCache))); + + verifyZeroInteractions(mockCache); } @Test public void createCacheWithNoExistingCache() { - Cache mockCache = mock(Cache.class, "MockGemFireCache"); - CacheFactory mockCacheFactory = mock(CacheFactory.class, "MockGemFireCacheFactory"); + Cache mockCache = mock(Cache.class); + CacheFactory mockCacheFactory = mock(CacheFactory.class); when(mockCacheFactory.create()).thenReturn(mockCache); @@ -385,9 +507,10 @@ public class CacheFactoryBeanTest { Cache actualCache = cacheFactoryBean.createCache(mockCacheFactory); - assertSame(mockCache, actualCache); + assertThat(actualCache, is(equalTo(mockCache))); verify(mockCacheFactory, times(1)).create(); + verifyZeroInteractions(mockCache); } @Test(expected = IllegalArgumentException.class) @@ -421,27 +544,19 @@ public class CacheFactoryBeanTest { } @Test - public void getObject() throws Exception { - final Cache mockCache = mock(Cache.class); - - CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { - @Override public void afterPropertiesSet() throws Exception { - this.cache = mockCache; - } - }; - - assertThat(cacheFactoryBean.getObject(), is(nullValue())); - - cacheFactoryBean.afterPropertiesSet(); - - assertThat(cacheFactoryBean.getObject(), is(equalTo(mockCache))); - - verifyZeroInteractions(mockCache); + @SuppressWarnings("unchecked") + public void getObjectType() { + assertThat((Class) new CacheFactoryBean().getObjectType(), is(equalTo(Cache.class))); } @Test - public void getObjectType() { - assertEquals(Cache.class, new CacheFactoryBean().getObjectType()); + public void getObjectTypeWithExistingCache() { + Cache mockCache = mock(Cache.class); + CacheFactoryBean cacheFactoryBean = new CacheFactoryBean(); + + cacheFactoryBean.setCache(mockCache); + + assertThat(cacheFactoryBean.getObjectType(), is(equalTo((Class) mockCache.getClass()))); } @Test diff --git a/src/test/java/org/springframework/data/gemfire/CacheIntegrationTest.java b/src/test/java/org/springframework/data/gemfire/CacheIntegrationTest.java index 677ea5fa..b7877f55 100644 --- a/src/test/java/org/springframework/data/gemfire/CacheIntegrationTest.java +++ b/src/test/java/org/springframework/data/gemfire/CacheIntegrationTest.java @@ -23,7 +23,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.data.gemfire.test.GemfireTestApplicationContextInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -39,7 +38,7 @@ import com.gemstone.gemfire.cache.Cache; * @author John Blum */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "basic-cache.xml", initializers = GemfireTestApplicationContextInitializer.class) +@ContextConfiguration(locations = "basic-cache.xml") public class CacheIntegrationTest { @Autowired ApplicationContext ctx; diff --git a/src/test/java/org/springframework/data/gemfire/ForkUtil.java b/src/test/java/org/springframework/data/gemfire/ForkUtil.java index 6fd944d3..82bdd352 100644 --- a/src/test/java/org/springframework/data/gemfire/ForkUtil.java +++ b/src/test/java/org/springframework/data/gemfire/ForkUtil.java @@ -81,7 +81,6 @@ public class ForkUtil { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { - System.out.println("Stopping fork..."); runCondition.set(false); processStandardInStream = null; @@ -91,8 +90,6 @@ public class ForkUtil { } catch (InterruptedException ignore) { } - - System.out.println("Fork stopped"); } }); diff --git a/src/test/java/org/springframework/data/gemfire/GemfireUtilsTest.java b/src/test/java/org/springframework/data/gemfire/GemfireUtilsTest.java index 8a775146..298b3ede 100644 --- a/src/test/java/org/springframework/data/gemfire/GemfireUtilsTest.java +++ b/src/test/java/org/springframework/data/gemfire/GemfireUtilsTest.java @@ -16,11 +16,24 @@ package org.springframework.data.gemfire; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import java.util.Properties; import org.junit.Test; +import com.gemstone.gemfire.cache.Cache; +import com.gemstone.gemfire.cache.client.ClientCache; +import com.gemstone.gemfire.distributed.DistributedSystem; import com.gemstone.gemfire.internal.GemFireVersion; /** @@ -34,16 +47,104 @@ import com.gemstone.gemfire.internal.GemFireVersion; */ public class GemfireUtilsTest { + @Test + public void isClientWithClientIsTrue() { + ClientCache mockClient = mock(ClientCache.class); + + assertThat(GemfireUtils.isClient(mockClient), is(true)); + + verifyZeroInteractions(mockClient); + } + + @Test + public void isClientWithNonClientIsFalse() { + Cache mockCache = mock(Cache.class); + + assertThat(GemfireUtils.isClient(mockCache), is(false)); + + verifyZeroInteractions(mockCache); + } + + @Test + public void isDurableWithDurableClientIsTrue() { + ClientCache mockClientCache = mock(ClientCache.class); + DistributedSystem mockDistributedSystem = mock(DistributedSystem.class); + + Properties gemfireProperties = new Properties(); + + gemfireProperties.setProperty(GemfireUtils.DURABLE_CLIENT_ID_PROPERTY_NAME, "123"); + + when(mockClientCache.getDistributedSystem()).thenReturn(mockDistributedSystem); + when(mockDistributedSystem.isConnected()).thenReturn(true); + when(mockDistributedSystem.getProperties()).thenReturn(gemfireProperties); + + assertThat(GemfireUtils.isDurable(mockClientCache), is(true)); + + verify(mockClientCache, times(1)).getDistributedSystem(); + verify(mockDistributedSystem, times(1)).isConnected(); + verify(mockDistributedSystem, times(1)).getProperties(); + } + + @Test + public void isDurableWhenNotDurableClientIsFalse() { + ClientCache mockClientCache = mock(ClientCache.class); + DistributedSystem mockDistributedSystem = mock(DistributedSystem.class); + + Properties gemfireProperties = new Properties(); + + gemfireProperties.setProperty(GemfireUtils.DURABLE_CLIENT_ID_PROPERTY_NAME, " "); + + when(mockClientCache.getDistributedSystem()).thenReturn(mockDistributedSystem); + when(mockDistributedSystem.isConnected()).thenReturn(true); + when(mockDistributedSystem.getProperties()).thenReturn(gemfireProperties); + + assertThat(GemfireUtils.isDurable(mockClientCache), is(false)); + + verify(mockClientCache, times(1)).getDistributedSystem(); + verify(mockDistributedSystem, times(1)).isConnected(); + verify(mockDistributedSystem, times(1)).getProperties(); + } + + @Test + public void isDurableWhenDistributedSystemIsNotConnectedIsFalse() { + ClientCache mockClientCache = mock(ClientCache.class); + DistributedSystem mockDistributedSystem = mock(DistributedSystem.class); + + when(mockClientCache.getDistributedSystem()).thenReturn(mockDistributedSystem); + when(mockDistributedSystem.isConnected()).thenReturn(false); + + assertThat(GemfireUtils.isDurable(mockClientCache), is(false)); + + verify(mockClientCache, times(1)).getDistributedSystem(); + verify(mockDistributedSystem, times(1)).isConnected(); + verify(mockDistributedSystem, never()).getProperties(); + } + + @Test + public void isPeerWithPeerIsTrue() { + Cache mockCache = mock(Cache.class); + + assertThat(GemfireUtils.isPeer(mockCache), is(true)); + + verifyZeroInteractions(mockCache); + } + + @Test + public void isPeerWithNonPeerIsFalse() { + ClientCache mockClientCache = mock(ClientCache.class); + + assertThat(GemfireUtils.isPeer(mockClientCache), is(false)); + + verifyZeroInteractions(mockClientCache); + } + // NOTE implementation is based on a GemFire internal class... com.gemstone.gemfire.internal.GemFireVersion. protected int getGemFireVersion() { try { String gemfireVersion = GemFireVersion.getGemFireVersion(); - StringBuilder buffer = new StringBuilder(); - buffer.append(GemFireVersion.getMajorVersion(gemfireVersion)); - buffer.append(GemFireVersion.getMinorVersion(gemfireVersion)); - - return Integer.decode(buffer.toString()); + return Integer.decode(String.valueOf(GemFireVersion.getMajorVersion(gemfireVersion)).concat( + String.valueOf(GemFireVersion.getMinorVersion(gemfireVersion)))); } catch (NumberFormatException ignore) { return -1; @@ -51,17 +152,24 @@ public class GemfireUtilsTest { } @Test - public void testIsGemfireVersion65OrAbove() { + public void gemfireVersionIs65OrAbove() { int gemfireVersion = getGemFireVersion(); assumeTrue(gemfireVersion > -1); assertEquals(getGemFireVersion() >= 65, GemfireUtils.isGemfireVersion65OrAbove()); } @Test - public void testIsGemfireVersion7OrAbove() { + public void gemfireVersionIs7OrAbove() { int gemfireVersion = getGemFireVersion(); assumeTrue(gemfireVersion > -1); assertEquals(getGemFireVersion() >= 70, GemfireUtils.isGemfireVersion7OrAbove()); } + @Test + public void gemfireVersionIs80rAbove() { + int gemfireVersion = getGemFireVersion(); + assumeTrue(gemfireVersion > -1); + assertEquals(getGemFireVersion() >= 80, GemfireUtils.isGemfireVersion8OrAbove()); + } + } diff --git a/src/test/java/org/springframework/data/gemfire/LazyWiringDeclarableSupportFunctionBasedIntegrationTest.java b/src/test/java/org/springframework/data/gemfire/LazyWiringDeclarableSupportFunctionBasedIntegrationTest.java index 6c0d4281..24cf388d 100644 --- a/src/test/java/org/springframework/data/gemfire/LazyWiringDeclarableSupportFunctionBasedIntegrationTest.java +++ b/src/test/java/org/springframework/data/gemfire/LazyWiringDeclarableSupportFunctionBasedIntegrationTest.java @@ -32,6 +32,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; import org.springframework.util.StringUtils; +import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.execute.Function; import com.gemstone.gemfire.cache.execute.FunctionContext; @@ -52,6 +53,9 @@ import com.gemstone.gemfire.cache.execute.FunctionContext; @SuppressWarnings("unused") public class LazyWiringDeclarableSupportFunctionBasedIntegrationTest { + @Autowired + private Cache gemfireCache; + @Autowired private HelloFunctionExecution helloFunctionExecution; diff --git a/src/test/java/org/springframework/data/gemfire/client/ClientCacheFactoryBeanTest.java b/src/test/java/org/springframework/data/gemfire/client/ClientCacheFactoryBeanTest.java index cd538c69..b3b6a18a 100644 --- a/src/test/java/org/springframework/data/gemfire/client/ClientCacheFactoryBeanTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/ClientCacheFactoryBeanTest.java @@ -16,19 +16,18 @@ package org.springframework.data.gemfire.client; +import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.sameInstance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; 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.Matchers.eq; import static org.mockito.Mockito.doThrow; @@ -36,16 +35,27 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.data.gemfire.TestUtils; +import org.springframework.data.gemfire.GemfireUtils; +import org.springframework.data.gemfire.config.GemfireConstants; +import org.springframework.data.gemfire.support.ConnectionEndpoint; import org.springframework.data.gemfire.util.DistributedSystemUtils; +import org.springframework.data.gemfire.util.SpringUtils; import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.GemFireCache; @@ -69,6 +79,9 @@ import com.gemstone.gemfire.pdx.PdxSerializer; */ public class ClientCacheFactoryBeanTest { + @Rule + public ExpectedException exception = ExpectedException.none(); + protected Properties createProperties(String key, String value) { return addProperty(null, key, value); } @@ -79,14 +92,19 @@ public class ClientCacheFactoryBeanTest { return properties; } + protected ConnectionEndpoint newConnectionEndpoint(String host, int port) { + return new ConnectionEndpoint(host, port); + } + @Test + @SuppressWarnings("unchecked") public void getObjectType() { - assertEquals(ClientCache.class, new ClientCacheFactoryBean().getObjectType()); + assertThat((Class) new ClientCacheFactoryBean().getObjectType(), is(equalTo(ClientCache.class))); } @Test public void isSingleton() { - assertTrue(new ClientCacheFactoryBean().isSingleton()); + assertThat(new ClientCacheFactoryBean().isSingleton(), is(true)); } @Test @@ -94,7 +112,7 @@ public class ClientCacheFactoryBeanTest { Properties gemfireProperties = createProperties("gf", "test"); Properties distributedSystemProperties = createProperties("ds", "mock"); - final DistributedSystem mockDistributedSystem = mock(DistributedSystem.class, "MockDistributedSystem"); + final DistributedSystem mockDistributedSystem = mock(DistributedSystem.class); when(mockDistributedSystem.isConnected()).thenReturn(true); when(mockDistributedSystem.getProperties()).thenReturn(distributedSystemProperties); @@ -124,13 +142,13 @@ public class ClientCacheFactoryBeanTest { @Test public void resolvePropertiesWhenDistributedSystemIsConnectedAndClientIsDurable() { - Properties gemfireProperties = DistributedSystemUtils.configureDurableClient(createProperties("gf", "test"), - "123", 600); + Properties gemfireProperties = DistributedSystemUtils.configureDurableClient( + createProperties("gf", "test"), "123", 600); Properties distributedSystemProperties = DistributedSystemUtils.configureDurableClient( createProperties("ds", "mock"), "987", 300); - final DistributedSystem mockDistributedSystem = mock(DistributedSystem.class, "MockDistributedSystem"); + final DistributedSystem mockDistributedSystem = mock(DistributedSystem.class); when(mockDistributedSystem.isConnected()).thenReturn(true); when(mockDistributedSystem.getProperties()).thenReturn(distributedSystemProperties); @@ -165,7 +183,7 @@ public class ClientCacheFactoryBeanTest { Properties gemfireProperties = createProperties("gf", "test"); Properties distributedSystemProperties = createProperties("ds", "mock"); - final DistributedSystem mockDistributedSystem = mock(DistributedSystem.class, "MockDistributedSystem"); + final DistributedSystem mockDistributedSystem = mock(DistributedSystem.class); when(mockDistributedSystem.isConnected()).thenReturn(false); when(mockDistributedSystem.getProperties()).thenReturn(distributedSystemProperties); @@ -180,7 +198,7 @@ public class ClientCacheFactoryBeanTest { Properties resolvedProperties = clientCacheFactoryBean.resolveProperties(); - assertSame(gemfireProperties, resolvedProperties); + assertThat(resolvedProperties, is(sameInstance(gemfireProperties))); verify(mockDistributedSystem, times(1)).isConnected(); verify(mockDistributedSystem, never()).getProperties(); @@ -190,104 +208,163 @@ public class ClientCacheFactoryBeanTest { public void resolvePropertiesWhenDistributedSystemIsNull() { Properties gemfireProperties = createProperties("gf", "test"); + assertThat(gemfireProperties.size(), is(equalTo(1))); + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { @Override T getDistributedSystem() { return null; } }; + clientCacheFactoryBean.setDurableClientId("123"); clientCacheFactoryBean.setProperties(gemfireProperties); Properties resolvedProperties = clientCacheFactoryBean.resolveProperties(); - assertSame(gemfireProperties, resolvedProperties); + assertThat(resolvedProperties, is(sameInstance(gemfireProperties))); + assertThat(resolvedProperties.size(), is(equalTo(2))); + assertThat(resolvedProperties.getProperty("gf"), is(equalTo("test"))); + assertThat(resolvedProperties.getProperty(DistributedSystemUtils.DURABLE_CLIENT_ID_PROPERTY_NAME), + is(equalTo("123"))); } @Test public void createClientCacheFactory() { Properties gemfireProperties = new Properties(); + Object clientCacheFactoryReference = new ClientCacheFactoryBean().createFactory(gemfireProperties); - assertTrue(gemfireProperties.isEmpty()); - assertTrue(clientCacheFactoryReference instanceof ClientCacheFactory); + assertThat(clientCacheFactoryReference, is(instanceOf(ClientCacheFactory.class))); + assertThat(gemfireProperties.isEmpty(), is(true)); ClientCacheFactory clientCacheFactory = (ClientCacheFactory) clientCacheFactoryReference; - clientCacheFactory.set("name", "TestCreateClientCacheFactory"); + clientCacheFactory.set("testCase", "TestCreateClientCacheFactory"); - assertTrue(gemfireProperties.containsKey("name")); - assertEquals("TestCreateClientCacheFactory", gemfireProperties.get("name")); + assertThat(gemfireProperties.containsKey("testCase"), is(true)); + assertThat(gemfireProperties.getProperty("testCase"), is(equalTo("TestCreateClientCacheFactory"))); } @Test - public void prepareClientCacheFactoryWithUnspecifiedPdxOptions() { - ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class, "MockGemFireClientCacheFactory"); + public void prepareClientCacheFactoryCallsInitializePdxAndInitializePool() { + final AtomicBoolean initializePdxCalled = new AtomicBoolean(false); + final AtomicBoolean initializePoolCalled = new AtomicBoolean(false); - assertSame(mockClientCacheFactory, new ClientCacheFactoryBean().prepareFactory(mockClientCacheFactory)); + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); - verify(mockClientCacheFactory, never()).setPdxSerializer(any(PdxSerializer.class)); - verify(mockClientCacheFactory, never()).setPdxDiskStore(any(String.class)); - verify(mockClientCacheFactory, never()).setPdxIgnoreUnreadFields(any(Boolean.class)); - verify(mockClientCacheFactory, never()).setPdxPersistent(any(Boolean.class)); - verify(mockClientCacheFactory, never()).setPdxReadSerialized(any(Boolean.class)); + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { + @Override ClientCacheFactory initializePdx(final ClientCacheFactory clientCacheFactory) { + initializePdxCalled.set(true); + return clientCacheFactory; + } + + @Override ClientCacheFactory initializePool(final ClientCacheFactory clientCacheFactory) { + initializePoolCalled.set(true); + return clientCacheFactory; + } + }; + + assertThat((ClientCacheFactory) clientCacheFactoryBean.prepareFactory(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + assertThat(initializePdxCalled.get(), is(true)); + assertThat(initializePoolCalled.get(), is(true)); } @Test - public void prepareClientCacheFactoryWithPartialPdxOptions() { + public void initializePdxWithAllPdxOptions() { ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); - clientCacheFactoryBean.setPdxSerializer(mock(PdxSerializer.class)); - clientCacheFactoryBean.setPdxReadSerialized(true); - clientCacheFactoryBean.setPdxIgnoreUnreadFields(false); + PdxSerializer mockPdxSerializer = mock(PdxSerializer.class); - ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class, "MockGemFireClientCacheFactory"); - - assertSame(mockClientCacheFactory, clientCacheFactoryBean.prepareFactory(mockClientCacheFactory)); - - verify(mockClientCacheFactory, times(1)).setPdxSerializer(any(PdxSerializer.class)); - verify(mockClientCacheFactory, never()).setPdxDiskStore(any(String.class)); - verify(mockClientCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false)); - verify(mockClientCacheFactory, never()).setPdxPersistent(any(Boolean.class)); - verify(mockClientCacheFactory, times(1)).setPdxReadSerialized(eq(true)); - } - - @Test - public void prepareClientCacheFactoryWithAllPdxOptions() { - ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); - - clientCacheFactoryBean.setPdxSerializer(mock(PdxSerializer.class)); - clientCacheFactoryBean.setPdxDiskStoreName("mockPdxDiskStoreName"); + clientCacheFactoryBean.setPdxDiskStoreName("MockPdxDiskStoreName"); clientCacheFactoryBean.setPdxIgnoreUnreadFields(false); clientCacheFactoryBean.setPdxPersistent(true); - clientCacheFactoryBean.setPdxReadSerialized(true); + clientCacheFactoryBean.setPdxReadSerialized(false); + clientCacheFactoryBean.setPdxSerializer(mockPdxSerializer); - ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class, "MockGemFireClientCacheFactory"); + assertThat(clientCacheFactoryBean.getPdxDiskStoreName(), is(equalTo("MockPdxDiskStoreName"))); + assertThat(clientCacheFactoryBean.getPdxIgnoreUnreadFields(), is(false)); + assertThat(clientCacheFactoryBean.getPdxPersistent(), is(true)); + assertThat(clientCacheFactoryBean.getPdxReadSerialized(), is(false)); + assertThat((PdxSerializer) clientCacheFactoryBean.getPdxSerializer(), is(sameInstance(mockPdxSerializer))); - assertSame(mockClientCacheFactory, clientCacheFactoryBean.prepareFactory(mockClientCacheFactory)); + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); - verify(mockClientCacheFactory, times(1)).setPdxSerializer(any(PdxSerializer.class)); - verify(mockClientCacheFactory, times(1)).setPdxDiskStore(eq("mockPdxDiskStoreName")); + assertThat(clientCacheFactoryBean.initializePdx(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verify(mockClientCacheFactory, times(1)).setPdxSerializer(eq(mockPdxSerializer)); + verify(mockClientCacheFactory, times(1)).setPdxDiskStore(eq("MockPdxDiskStoreName")); verify(mockClientCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false)); verify(mockClientCacheFactory, times(1)).setPdxPersistent(eq(true)); - verify(mockClientCacheFactory, times(1)).setPdxReadSerialized(eq(true)); + verify(mockClientCacheFactory, times(1)).setPdxReadSerialized(eq(false)); } - @Test(expected = IllegalArgumentException.class) - public void prepareClientCacheFactoryWithInvalidTypeForPdxSerializer() { - ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class, "MockGemFireClientCacheFactory"); + @Test + public void initializePdxWithPartialPdxOptions() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setPdxReadSerialized(true); + clientCacheFactoryBean.setPdxIgnoreUnreadFields(true); + + assertThat(clientCacheFactoryBean.getPdxDiskStoreName(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPdxIgnoreUnreadFields(), is(true)); + assertThat(clientCacheFactoryBean.getPdxPersistent(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPdxReadSerialized(), is(true)); + assertThat(clientCacheFactoryBean.getPdxSerializer(), is(nullValue())); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePdx(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verify(mockClientCacheFactory, never()).setPdxDiskStore(anyString()); + verify(mockClientCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(true)); + verify(mockClientCacheFactory, never()).setPdxPersistent(anyBoolean()); + verify(mockClientCacheFactory, times(1)).setPdxReadSerialized(eq(true)); + verify(mockClientCacheFactory, never()).setPdxSerializer(any(PdxSerializer.class)); + } + + @Test + public void initializePdxWithNoPdxOptions() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + assertThat(clientCacheFactoryBean.getPdxDiskStoreName(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPdxIgnoreUnreadFields(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPdxPersistent(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPdxReadSerialized(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPdxSerializer(), is(nullValue())); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePdx(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verifyZeroInteractions(mockClientCacheFactory); + } + + @Test + public void initializePdxUsingIllegalTypeForPdxSerializer() { + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); try { ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); - clientCacheFactoryBean.setPdxSerializer(new Object()); - clientCacheFactoryBean.setPdxReadSerialized(true); - clientCacheFactoryBean.setPdxIgnoreUnreadFields(true); - clientCacheFactoryBean.prepareFactory(mockClientCacheFactory); - } - catch (IllegalArgumentException expected) { - assertTrue(expected.getMessage().startsWith("Invalid pdx serializer used")); - assertNull(expected.getCause()); - throw expected; + Object pdxSerializer = new Object(); + + clientCacheFactoryBean.setPdxSerializer(pdxSerializer); + clientCacheFactoryBean.setPdxReadSerialized(false); + clientCacheFactoryBean.setPdxPersistent(true); + clientCacheFactoryBean.setPdxIgnoreUnreadFields(false); + clientCacheFactoryBean.setPdxDiskStoreName("test"); + + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage(containsString(String.format( + "[%1$s] of type [java.lang.Object] is not a PdxSerializer", pdxSerializer))); + + assertThat(clientCacheFactoryBean.initializePdx(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); } finally { verify(mockClientCacheFactory, never()).setPdxSerializer(any(PdxSerializer.class)); @@ -299,177 +376,620 @@ public class ClientCacheFactoryBeanTest { } @Test - public void createCache() { - BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockBeanFactory"); + public void initializePoolWithPool() { + Pool mockPool = mock(Pool.class); - ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class, "MockClientCacheFactory"); - - ClientCache mockClientCache = mock(ClientCache.class, "MockClientCache"); - - Pool mockPool = mock(Pool.class, "MockPool"); - - when(mockClientCacheFactory.create()).thenReturn(mockClientCache); - when(mockBeanFactory.isTypeMatch(eq("testCreateCache.Pool"), eq(Pool.class))).thenReturn(true); - when(mockBeanFactory.getBean(eq("testCreateCache.Pool"), eq(Pool.class))).thenReturn(mockPool); - when(mockPool.getFreeConnectionTimeout()).thenReturn(30000); - when(mockPool.getIdleTimeout()).thenReturn(60000l); - when(mockPool.getLoadConditioningInterval()).thenReturn(45000); + when(mockPool.getFreeConnectionTimeout()).thenReturn(10000); + when(mockPool.getIdleTimeout()).thenReturn(120000l); + when(mockPool.getLoadConditioningInterval()).thenReturn(30000); + when(mockPool.getLocators()).thenReturn(Collections.emptyList()); when(mockPool.getMaxConnections()).thenReturn(100); when(mockPool.getMinConnections()).thenReturn(10); when(mockPool.getMultiuserAuthentication()).thenReturn(true); + when(mockPool.getPRSingleHopEnabled()).thenReturn(true); when(mockPool.getPingInterval()).thenReturn(15000l); - when(mockPool.getPRSingleHopEnabled()).thenReturn(true); when(mockPool.getReadTimeout()).thenReturn(20000); - when(mockPool.getRetryAttempts()).thenReturn(10); - when(mockPool.getServerGroup()).thenReturn("TestServerGroup"); - when(mockPool.getSocketBufferSize()).thenReturn(32768); + when(mockPool.getRetryAttempts()).thenReturn(1); + when(mockPool.getServerGroup()).thenReturn("TestGroup"); + when(mockPool.getSocketBufferSize()).thenReturn(8192); when(mockPool.getStatisticInterval()).thenReturn(5000); - when(mockPool.getSubscriptionAckInterval()).thenReturn(15000); - when(mockPool.getSubscriptionEnabled()).thenReturn(true); - when(mockPool.getSubscriptionMessageTrackingTimeout()).thenReturn(30000); - when(mockPool.getSubscriptionRedundancy()).thenReturn(2); - when(mockPool.getThreadLocalConnections()).thenReturn(false); - - ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); - - clientCacheFactoryBean.setBeanFactory(mockBeanFactory); - clientCacheFactoryBean.setPoolName("testCreateCache.Pool"); - clientCacheFactoryBean.setReadyForEvents(false); - - GemFireCache actualCache = clientCacheFactoryBean.createCache(mockClientCacheFactory); - - assertSame(mockClientCache, actualCache); - - verify(mockClientCacheFactory, times(1)).create(); - verify(mockBeanFactory, times(1)).isTypeMatch(eq("testCreateCache.Pool"), eq(Pool.class)); - verify(mockBeanFactory, times(1)).getBean(eq("testCreateCache.Pool"), eq(Pool.class)); - verify(mockBeanFactory, never()).getBean(eq(Pool.class)); - verify(mockClientCacheFactory, never()).setPoolFreeConnectionTimeout(eq(30000)); - verify(mockClientCacheFactory, never()).setPoolIdleTimeout(eq(60000l)); - verify(mockClientCacheFactory, never()).setPoolLoadConditioningInterval(eq(45000)); - verify(mockClientCacheFactory, never()).setPoolMaxConnections(eq(100)); - verify(mockClientCacheFactory, never()).setPoolMinConnections(eq(10)); - verify(mockClientCacheFactory, never()).setPoolMultiuserAuthentication(eq(true)); - verify(mockClientCacheFactory, never()).setPoolPingInterval(eq(15000l)); - verify(mockClientCacheFactory, never()).setPoolPRSingleHopEnabled(eq(true)); - verify(mockClientCacheFactory, never()).setPoolReadTimeout(eq(20000)); - verify(mockClientCacheFactory, never()).setPoolRetryAttempts(eq(10)); - verify(mockClientCacheFactory, never()).setPoolServerGroup(eq("TestServerGroup")); - verify(mockClientCacheFactory, never()).setPoolSocketBufferSize(eq(32768)); - verify(mockClientCacheFactory, never()).setPoolStatisticInterval(eq(5000)); - verify(mockClientCacheFactory, never()).setPoolSubscriptionAckInterval(eq(15000)); - verify(mockClientCacheFactory, never()).setPoolSubscriptionEnabled(eq(true)); - verify(mockClientCacheFactory, never()).setPoolSubscriptionMessageTrackingTimeout(eq(30000)); - verify(mockClientCacheFactory, never()).setPoolSubscriptionRedundancy(eq(2)); - verify(mockClientCacheFactory, never()).setPoolThreadLocalConnections(eq(false)); - } - - @Test - public void resolvePoolWithUnresolvablePoolName() throws Exception { - BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockSpringBeanFactory"); - ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class, "MockGemFireClientCacheFactory"); - ClientCache mockClientCache = mock(ClientCache.class, "MockGemFireClientCache"); - Pool mockPool = mock(Pool.class, "MockGemFirePool"); - - when(mockBeanFactory.isTypeMatch(any(String.class), eq(Pool.class))).thenReturn(false); - when(mockBeanFactory.getBean(eq(Pool.class))).thenReturn(mockPool); - when(mockClientCacheFactory.create()).thenReturn(mockClientCache); - when(mockPool.getFreeConnectionTimeout()).thenReturn(120000); - when(mockPool.getIdleTimeout()).thenReturn(300000l); - when(mockPool.getLoadConditioningInterval()).thenReturn(15000); - when(mockPool.getMaxConnections()).thenReturn(50); - when(mockPool.getMinConnections()).thenReturn(5); - when(mockPool.getMultiuserAuthentication()).thenReturn(false); - when(mockPool.getName()).thenReturn("MockGemFirePool"); - when(mockPool.getPingInterval()).thenReturn(12000l); - when(mockPool.getPRSingleHopEnabled()).thenReturn(true); - when(mockPool.getReadTimeout()).thenReturn(60000); - when(mockPool.getRetryAttempts()).thenReturn(5); - when(mockPool.getServerGroup()).thenReturn("MockServerGroup"); - when(mockPool.getSocketBufferSize()).thenReturn(16384); - when(mockPool.getStatisticInterval()).thenReturn(1000); when(mockPool.getSubscriptionAckInterval()).thenReturn(500); when(mockPool.getSubscriptionEnabled()).thenReturn(true); - when(mockPool.getSubscriptionMessageTrackingTimeout()).thenReturn(15000); - when(mockPool.getSubscriptionRedundancy()).thenReturn(4); + when(mockPool.getSubscriptionMessageTrackingTimeout()).thenReturn(500); + when(mockPool.getSubscriptionRedundancy()).thenReturn(2); when(mockPool.getThreadLocalConnections()).thenReturn(false); + when(mockPool.getServers()).thenReturn(Arrays.asList( + new InetSocketAddress("localhost", 11235), new InetSocketAddress("localhost", 12480))); ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); - clientCacheFactoryBean.setBeanFactory(mockBeanFactory); - clientCacheFactoryBean.setPoolName("TestGemFirePool"); - clientCacheFactoryBean.setReadyForEvents(false); + clientCacheFactoryBean.setPool(mockPool); - assertEquals("TestGemFirePool", TestUtils.readField("poolName", clientCacheFactoryBean)); + assertThat(clientCacheFactoryBean.getFreeConnectionTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getIdleTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getLoadConditioningInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getLocators().isEmpty(), is(true)); + assertThat(clientCacheFactoryBean.getMaxConnections(), is(nullValue())); + assertThat(clientCacheFactoryBean.getMinConnections(), is(nullValue())); + assertThat(clientCacheFactoryBean.getMultiUserAuthentication(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPingInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPrSingleHopEnabled(), is(nullValue())); + assertThat(clientCacheFactoryBean.getReadTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getRetryAttempts(), is(nullValue())); + assertThat(clientCacheFactoryBean.getServerGroup(), is(nullValue())); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); + assertThat(clientCacheFactoryBean.getSocketBufferSize(), is(nullValue())); + assertThat(clientCacheFactoryBean.getStatisticsInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionAckInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionEnabled(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionMessageTrackingTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionRedundancy(), is(nullValue())); + assertThat(clientCacheFactoryBean.getThreadLocalConnections(), is(nullValue())); - GemFireCache actualClientCache = clientCacheFactoryBean.createCache(mockClientCacheFactory); + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); - assertSame(mockClientCache, actualClientCache); - assertEquals("MockGemFirePool", TestUtils.readField("poolName", clientCacheFactoryBean)); + assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); - verify(mockClientCacheFactory, times(1)).create(); - verify(mockBeanFactory, times(1)).isTypeMatch(eq("TestGemFirePool"), eq(Pool.class)); - verify(mockBeanFactory, never()).getBean(eq("TestGemFirePool"), eq(Pool.class)); - verify(mockBeanFactory, times(1)).getBean(eq(Pool.class)); - verify(mockPool, times(1)).getName(); - verify(mockClientCacheFactory, never()).setPoolFreeConnectionTimeout(eq(120000)); - verify(mockClientCacheFactory, never()).setPoolIdleTimeout(eq(300000l)); - verify(mockClientCacheFactory, never()).setPoolLoadConditioningInterval(eq(15000)); - verify(mockClientCacheFactory, never()).setPoolMaxConnections(eq(50)); - verify(mockClientCacheFactory, never()).setPoolMinConnections(eq(5)); - verify(mockClientCacheFactory, never()).setPoolMultiuserAuthentication(eq(false)); - verify(mockClientCacheFactory, never()).setPoolPingInterval(eq(12000l)); - verify(mockClientCacheFactory, never()).setPoolPRSingleHopEnabled(eq(true)); - verify(mockClientCacheFactory, never()).setPoolReadTimeout(eq(60000)); - verify(mockClientCacheFactory, never()).setPoolRetryAttempts(eq(5)); - verify(mockClientCacheFactory, never()).setPoolServerGroup(eq("MockServerGroup")); - verify(mockClientCacheFactory, never()).setPoolSocketBufferSize(eq(16384)); - verify(mockClientCacheFactory, never()).setPoolStatisticInterval(eq(1000)); - verify(mockClientCacheFactory, never()).setPoolSubscriptionAckInterval(eq(500)); - verify(mockClientCacheFactory, never()).setPoolSubscriptionEnabled(eq(true)); - verify(mockClientCacheFactory, never()).setPoolSubscriptionMessageTrackingTimeout(eq(15000)); - verify(mockClientCacheFactory, never()).setPoolSubscriptionRedundancy(eq(4)); - verify(mockClientCacheFactory, never()).setPoolThreadLocalConnections(eq(false)); + verify(mockPool, times(1)).getFreeConnectionTimeout(); + verify(mockPool, times(1)).getIdleTimeout(); + verify(mockPool, times(1)).getLoadConditioningInterval(); + verify(mockPool, never()).getLocators(); + verify(mockPool, times(1)).getMaxConnections(); + verify(mockPool, times(1)).getMinConnections(); + verify(mockPool, times(1)).getMultiuserAuthentication(); + verify(mockPool, times(1)).getPRSingleHopEnabled(); + verify(mockPool, times(1)).getPingInterval(); + verify(mockPool, times(1)).getReadTimeout(); + verify(mockPool, times(1)).getRetryAttempts(); + verify(mockPool, times(1)).getServerGroup(); + verify(mockPool, times(1)).getServers(); + verify(mockPool, times(1)).getSocketBufferSize(); + verify(mockPool, times(1)).getStatisticInterval(); + verify(mockPool, times(1)).getSubscriptionAckInterval(); + verify(mockPool, times(1)).getSubscriptionEnabled(); + verify(mockPool, times(1)).getSubscriptionMessageTrackingTimeout(); + verify(mockPool, times(1)).getSubscriptionRedundancy(); + verify(mockPool, times(1)).getThreadLocalConnections(); + verify(mockClientCacheFactory, times(1)).setPoolFreeConnectionTimeout(eq(10000)); + verify(mockClientCacheFactory, times(1)).setPoolIdleTimeout(eq(120000l)); + verify(mockClientCacheFactory, times(1)).setPoolLoadConditioningInterval(eq(30000)); + verify(mockClientCacheFactory, times(1)).setPoolMaxConnections(eq(100)); + verify(mockClientCacheFactory, times(1)).setPoolMinConnections(eq(10)); + verify(mockClientCacheFactory, times(1)).setPoolMultiuserAuthentication(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolPRSingleHopEnabled(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolPingInterval(eq(15000l)); + verify(mockClientCacheFactory, times(1)).setPoolReadTimeout(eq(20000)); + verify(mockClientCacheFactory, times(1)).setPoolRetryAttempts(eq(1)); + verify(mockClientCacheFactory, times(1)).setPoolServerGroup(eq("TestGroup")); + verify(mockClientCacheFactory, times(1)).setPoolSocketBufferSize(eq(8192)); + verify(mockClientCacheFactory, times(1)).setPoolStatisticInterval(eq(5000)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionAckInterval(eq(500)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionEnabled(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionMessageTrackingTimeout(eq(500)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionRedundancy(eq(2)); + verify(mockClientCacheFactory, times(1)).setPoolThreadLocalConnections(eq(false)); + verify(mockClientCacheFactory, times(1)).addPoolServer(eq("localhost"), eq(11235)); + verify(mockClientCacheFactory, times(1)).addPoolServer(eq("localhost"), eq(12480)); + verify(mockClientCacheFactory, never()).addPoolLocator(anyString(), anyInt()); } @Test - public void resolveUnresolvablePool() { - BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockSpringBeanFactory"); - ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class, "MockGemFireClientCacheFactory"); + public void initializePoolWithFactory() { + Pool mockPool = mock(Pool.class); - when(mockBeanFactory.getBean(eq(Pool.class))).thenThrow(new NoSuchBeanDefinitionException("TEST")); + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setFreeConnectionTimeout(5000); + clientCacheFactoryBean.setIdleTimeout(300000l); + clientCacheFactoryBean.setLoadConditioningInterval(120000); + clientCacheFactoryBean.setMaxConnections(99); + clientCacheFactoryBean.setMinConnections(9); + clientCacheFactoryBean.setMultiUserAuthentication(true); + clientCacheFactoryBean.setPingInterval(15000l); + clientCacheFactoryBean.setPool(mockPool); + clientCacheFactoryBean.setPrSingleHopEnabled(true); + clientCacheFactoryBean.setReadTimeout(20000); + clientCacheFactoryBean.setRetryAttempts(2); + clientCacheFactoryBean.setServerGroup("TestGroup"); + clientCacheFactoryBean.setSocketBufferSize(16384); + clientCacheFactoryBean.setStatisticsInterval(1000); + clientCacheFactoryBean.setSubscriptionAckInterval(100); + clientCacheFactoryBean.setSubscriptionEnabled(true); + clientCacheFactoryBean.setSubscriptionMessageTrackingTimeout(500); + clientCacheFactoryBean.setSubscriptionRedundancy(2); + clientCacheFactoryBean.setThreadLocalConnections(false); + clientCacheFactoryBean.addLocators(newConnectionEndpoint("localhost", 11235), + newConnectionEndpoint("skullbox", 10334)); + + assertThat(clientCacheFactoryBean.getFreeConnectionTimeout(), is(equalTo(5000))); + assertThat(clientCacheFactoryBean.getIdleTimeout(), is(equalTo(300000l))); + assertThat(clientCacheFactoryBean.getLoadConditioningInterval(), is(equalTo(120000))); + assertThat(clientCacheFactoryBean.getLocators().size(), is(equalTo(2))); + assertThat(clientCacheFactoryBean.getMaxConnections(), is(equalTo(99))); + assertThat(clientCacheFactoryBean.getMinConnections(), is(equalTo(9))); + assertThat(clientCacheFactoryBean.getMultiUserAuthentication(), is(equalTo(true))); + assertThat(clientCacheFactoryBean.getPingInterval(), is(equalTo(15000l))); + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPrSingleHopEnabled(), is(equalTo(true))); + assertThat(clientCacheFactoryBean.getReadTimeout(), is(equalTo(20000))); + assertThat(clientCacheFactoryBean.getRetryAttempts(), is(equalTo(2))); + assertThat(clientCacheFactoryBean.getServerGroup(), is(equalTo("TestGroup"))); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); + assertThat(clientCacheFactoryBean.getSocketBufferSize(), is(equalTo(16384))); + assertThat(clientCacheFactoryBean.getStatisticsInterval(), is(equalTo(1000))); + assertThat(clientCacheFactoryBean.getSubscriptionAckInterval(), is(equalTo(100))); + assertThat(clientCacheFactoryBean.getSubscriptionEnabled(), is(equalTo(true))); + assertThat(clientCacheFactoryBean.getSubscriptionMessageTrackingTimeout(), is(equalTo(500))); + assertThat(clientCacheFactoryBean.getSubscriptionRedundancy(), is(equalTo(2))); + assertThat(clientCacheFactoryBean.getThreadLocalConnections(), is(equalTo(false))); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verifyZeroInteractions(mockPool); + verify(mockClientCacheFactory, times(1)).setPoolFreeConnectionTimeout(eq(5000)); + verify(mockClientCacheFactory, times(1)).setPoolIdleTimeout(eq(300000l)); + verify(mockClientCacheFactory, times(1)).setPoolLoadConditioningInterval(eq(120000)); + verify(mockClientCacheFactory, times(1)).setPoolMaxConnections(eq(99)); + verify(mockClientCacheFactory, times(1)).setPoolMinConnections(eq(9)); + verify(mockClientCacheFactory, times(1)).setPoolMultiuserAuthentication(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolPingInterval(eq(15000l)); + verify(mockClientCacheFactory, times(1)).setPoolPRSingleHopEnabled(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolReadTimeout(eq(20000)); + verify(mockClientCacheFactory, times(1)).setPoolRetryAttempts(eq(2)); + verify(mockClientCacheFactory, times(1)).setPoolServerGroup(eq("TestGroup")); + verify(mockClientCacheFactory, times(1)).setPoolSocketBufferSize(eq(16384)); + verify(mockClientCacheFactory, times(1)).setPoolStatisticInterval(eq(1000)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionAckInterval(eq(100)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionEnabled(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionMessageTrackingTimeout(eq(500)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionRedundancy(eq(2)); + verify(mockClientCacheFactory, times(1)).setPoolThreadLocalConnections(eq(false)); + verify(mockClientCacheFactory, times(1)).addPoolLocator(eq("localhost"), eq(11235)); + verify(mockClientCacheFactory, times(1)).addPoolLocator(eq("skullbox"), eq(10334)); + verify(mockClientCacheFactory, never()).addPoolServer(anyString(), anyInt()); + } + + @Test + public void initializePoolWithFactoryAndPoolButFactoryOverridesPool() { + Pool mockPool = mock(Pool.class); + + when(mockPool.getFreeConnectionTimeout()).thenReturn(5000); + when(mockPool.getIdleTimeout()).thenReturn(120000l); + when(mockPool.getLoadConditioningInterval()).thenReturn(300000); + when(mockPool.getLocators()).thenReturn(Collections.emptyList()); + when(mockPool.getMaxConnections()).thenReturn(200); + when(mockPool.getMinConnections()).thenReturn(10); + when(mockPool.getMultiuserAuthentication()).thenReturn(false); + when(mockPool.getPingInterval()).thenReturn(15000l); + when(mockPool.getPRSingleHopEnabled()).thenReturn(false); + when(mockPool.getReadTimeout()).thenReturn(30000); + when(mockPool.getRetryAttempts()).thenReturn(1); + when(mockPool.getServerGroup()).thenReturn("TestServerGroup"); + when(mockPool.getServers()).thenReturn(Collections.singletonList(new InetSocketAddress("localhost", 12480))); + when(mockPool.getSocketBufferSize()).thenReturn(8192); + when(mockPool.getStatisticInterval()).thenReturn(5000); + when(mockPool.getSubscriptionAckInterval()).thenReturn(1000); + when(mockPool.getSubscriptionEnabled()).thenReturn(false); + when(mockPool.getSubscriptionMessageTrackingTimeout()).thenReturn(20000); + when(mockPool.getSubscriptionRedundancy()).thenReturn(1); + when(mockPool.getThreadLocalConnections()).thenReturn(true); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setIdleTimeout(180000l); + clientCacheFactoryBean.setMaxConnections(500); + clientCacheFactoryBean.setMinConnections(50); + clientCacheFactoryBean.setMultiUserAuthentication(true); + clientCacheFactoryBean.setPool(mockPool); + clientCacheFactoryBean.setPrSingleHopEnabled(true); + clientCacheFactoryBean.setServerGroup("TestGroup"); + clientCacheFactoryBean.setSocketBufferSize(16384); + clientCacheFactoryBean.setStatisticsInterval(500); + clientCacheFactoryBean.setSubscriptionAckInterval(100); + clientCacheFactoryBean.setSubscriptionEnabled(true); + clientCacheFactoryBean.setSubscriptionRedundancy(2); + clientCacheFactoryBean.setThreadLocalConnections(false); + clientCacheFactoryBean.addLocators(newConnectionEndpoint("localhost", 11235)); + + assertThat(clientCacheFactoryBean.getFreeConnectionTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getIdleTimeout(), is(equalTo(180000l))); + assertThat(clientCacheFactoryBean.getLoadConditioningInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getLocators().size(), is(equalTo(1))); + assertThat(clientCacheFactoryBean.getMaxConnections(), is(equalTo(500))); + assertThat(clientCacheFactoryBean.getMinConnections(), is(equalTo(50))); + assertThat(clientCacheFactoryBean.getMultiUserAuthentication(), is(true)); + assertThat(clientCacheFactoryBean.getPingInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPrSingleHopEnabled(), is(true)); + assertThat(clientCacheFactoryBean.getReadTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getRetryAttempts(), is(nullValue())); + assertThat(clientCacheFactoryBean.getServerGroup(), is(equalTo("TestGroup"))); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); + assertThat(clientCacheFactoryBean.getSocketBufferSize(), is(equalTo(16384))); + assertThat(clientCacheFactoryBean.getStatisticsInterval(), is(equalTo(500))); + assertThat(clientCacheFactoryBean.getSubscriptionAckInterval(), is(equalTo(100))); + assertThat(clientCacheFactoryBean.getSubscriptionEnabled(), is(true)); + assertThat(clientCacheFactoryBean.getSubscriptionMessageTrackingTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionRedundancy(), is(equalTo(2))); + assertThat(clientCacheFactoryBean.getThreadLocalConnections(), is(false)); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verify(mockPool, times(1)).getFreeConnectionTimeout(); + verify(mockPool, never()).getIdleTimeout(); + verify(mockPool, times(1)).getLoadConditioningInterval(); + verify(mockPool, never()).getLocators(); + verify(mockPool, never()).getMaxConnections(); + verify(mockPool, never()).getMinConnections(); + verify(mockPool, never()).getMultiuserAuthentication(); + verify(mockPool, times(1)).getPingInterval(); + verify(mockPool, never()).getPRSingleHopEnabled(); + verify(mockPool, times(1)).getReadTimeout(); + verify(mockPool, times(1)).getRetryAttempts(); + verify(mockPool, never()).getServerGroup(); + verify(mockPool, never()).getServers(); + verify(mockPool, never()).getSocketBufferSize(); + verify(mockPool, never()).getStatisticInterval(); + verify(mockPool, never()).getSubscriptionAckInterval(); + verify(mockPool, never()).getSubscriptionEnabled(); + verify(mockPool, times(1)).getSubscriptionMessageTrackingTimeout(); + verify(mockPool, never()).getSubscriptionRedundancy(); + verify(mockPool, never()).getThreadLocalConnections(); + verify(mockClientCacheFactory, times(1)).setPoolFreeConnectionTimeout(eq(5000)); + verify(mockClientCacheFactory, times(1)).setPoolIdleTimeout(eq(180000l)); + verify(mockClientCacheFactory, times(1)).setPoolLoadConditioningInterval(eq(300000)); + verify(mockClientCacheFactory, times(1)).setPoolMaxConnections(eq(500)); + verify(mockClientCacheFactory, times(1)).setPoolMinConnections(eq(50)); + verify(mockClientCacheFactory, times(1)).setPoolMultiuserAuthentication(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolPingInterval(eq(15000l)); + verify(mockClientCacheFactory, times(1)).setPoolPRSingleHopEnabled(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolReadTimeout(eq(30000)); + verify(mockClientCacheFactory, times(1)).setPoolRetryAttempts(eq(1)); + verify(mockClientCacheFactory, times(1)).setPoolServerGroup(eq("TestGroup")); + verify(mockClientCacheFactory, times(1)).setPoolSocketBufferSize(eq(16384)); + verify(mockClientCacheFactory, times(1)).setPoolStatisticInterval(eq(500)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionAckInterval(eq(100)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionEnabled(eq(true)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionMessageTrackingTimeout(eq(20000)); + verify(mockClientCacheFactory, times(1)).setPoolSubscriptionRedundancy(eq(2)); + verify(mockClientCacheFactory, times(1)).addPoolLocator(eq("localhost"), eq(11235)); + verify(mockClientCacheFactory, never()).addPoolServer(anyString(), anyInt()); + } + + @Test + public void initializePoolWithFactoryServer() { + Pool mockPool = mock(Pool.class); + + when(mockPool.getLocators()).thenReturn(Collections.singletonList(new InetSocketAddress("localhost", 21668))); + when(mockPool.getServers()).thenReturn(Collections.singletonList(new InetSocketAddress("localhost", 41414))); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setPool(mockPool); + clientCacheFactoryBean.addServers(newConnectionEndpoint("skullbox", 12480)); + + assertThat(clientCacheFactoryBean.getLocators().isEmpty(), is(true)); + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + assertThat(clientCacheFactoryBean.getServers().size(), is(equalTo(1))); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verify(mockPool, never()).getLocators(); + verify(mockPool, never()).getServers(); + verify(mockClientCacheFactory, never()).addPoolLocator(anyString(), anyInt()); + verify(mockClientCacheFactory, times(1)).addPoolServer(eq("skullbox"), eq(12480)); + } + + @Test + public void initializePoolWithFactoryLocator() { + Pool mockPool = mock(Pool.class); + + when(mockPool.getLocators()).thenReturn(Collections.singletonList(new InetSocketAddress("localhost", 21668))); + when(mockPool.getServers()).thenReturn(Collections.singletonList(new InetSocketAddress("localhost", 41414))); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setPool(mockPool); + clientCacheFactoryBean.addLocators(newConnectionEndpoint("boombox", 11235)); + + assertThat(clientCacheFactoryBean.getLocators().size(), is(equalTo(1))); + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verify(mockPool, never()).getLocators(); + verify(mockPool, never()).getServers(); + verify(mockClientCacheFactory, times(1)).addPoolLocator(eq("boombox"), eq(11235)); + verify(mockClientCacheFactory, never()).addPoolServer(anyString(), anyInt()); + } + + @Test + public void initializePoolWithPoolServer() { + Pool mockPool = mock(Pool.class); + + when(mockPool.getLocators()).thenReturn(Collections.emptyList()); + when(mockPool.getServers()).thenReturn(Collections.singletonList(new InetSocketAddress("boombox", 41414))); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setPool(mockPool); + + assertThat(clientCacheFactoryBean.getLocators().isEmpty(), is(true)); + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verify(mockPool, never()).getLocators(); + verify(mockPool, times(1)).getServers(); + verify(mockClientCacheFactory, never()).addPoolLocator(anyString(), anyInt()); + verify(mockClientCacheFactory, times(1)).addPoolServer(eq("boombox"), eq(41414)); + } + + @Test + public void initializePoolWithPoolLocator() { + Pool mockPool = mock(Pool.class); + + when(mockPool.getLocators()).thenReturn(Collections.singletonList(new InetSocketAddress("skullbox", 21668))); + when(mockPool.getServers()).thenReturn(Collections.emptyList()); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setPool(mockPool); + + assertThat(clientCacheFactoryBean.getLocators().isEmpty(), is(true)); + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verify(mockPool, times(1)).getLocators(); + verify(mockPool, times(1)).getServers(); + verify(mockClientCacheFactory, times(1)).addPoolLocator(eq("skullbox"), eq(21668)); + verify(mockClientCacheFactory, never()).addPoolServer(anyString(), anyInt()); + } + + @Test + public void initializePoolWithDefaultServer() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { + @Override Pool resolvePool() { + return null; + } + }; + + assertThat(clientCacheFactoryBean.getLocators().isEmpty(), is(true)); + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); + + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + assertThat(clientCacheFactoryBean.initializePool(mockClientCacheFactory), + is(sameInstance(mockClientCacheFactory))); + + verify(mockClientCacheFactory, never()).addPoolLocator(anyString(), anyInt()); + verify(mockClientCacheFactory, times(1)).addPoolServer(eq("localhost"), + eq(GemfireUtils.DEFAULT_CACHE_SERVER_PORT)); + } + + @Test + public void createCache() { + ClientCache mockClientCache = mock(ClientCache.class); + ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); + + when(mockClientCacheFactory.create()).thenReturn(mockClientCache); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + assertThat((ClientCache) clientCacheFactoryBean.createCache(mockClientCacheFactory), + is(sameInstance(mockClientCache))); + + verify(mockClientCacheFactory, times(1)).create(); + verifyZeroInteractions(mockClientCache); + } + + @Test + public void resolvePoolByReturningProvidedPool() { + Pool mockPool = mock(Pool.class); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setPool(mockPool); + + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool))); + + verifyZeroInteractions(mockPool); + } + + @Test + public void resolvesPoolByName() { + final Pool mockPool = mock(Pool.class); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { + @Override Pool findPool(String name) { + assertThat(name, is(equalTo("TestPool"))); + return mockPool; + } + }; + + clientCacheFactoryBean.setPoolName("TestPool"); + + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool"))); + assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool))); + + verifyZeroInteractions(mockPool); + } + + @Test + public void resolvesPoolByDefaultName() { + final Pool mockPool = mock(Pool.class); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { + @Override Pool findPool(String name) { + assertThat(name, is(equalTo(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME))); + return mockPool; + } + }; + + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool))); + + verifyZeroInteractions(mockPool); + } + + @Test + public void resolvesNamedPoolFromBeanFactory() { + ListableBeanFactory mockBeanFactory = mock(ListableBeanFactory.class); + Pool mockPool = mock(Pool.class); + PoolFactoryBean mockPoolFactoryBean = mock(PoolFactoryBean.class); + + Map beans = Collections.singletonMap("&TestPool", mockPoolFactoryBean); + + when(mockBeanFactory.getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false))).thenReturn(beans); + when(mockPoolFactoryBean.getPool()).thenReturn(mockPool); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setBeanFactory(mockBeanFactory); + clientCacheFactoryBean.setPoolName("TestPool"); + + assertThat((ListableBeanFactory) clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory))); + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool"))); + assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool))); + + verify(mockBeanFactory, times(1)).getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false)); + verify(mockPoolFactoryBean, times(1)).getPool(); + verifyZeroInteractions(mockPool); + } + + @Test + public void resolvesUnnamedPoolFromBeanFactory() { + ListableBeanFactory mockBeanFactory = mock(ListableBeanFactory.class); + Pool mockPool = mock(Pool.class); + PoolFactoryBean mockPoolFactoryBean = mock(PoolFactoryBean.class); + + Map beans = Collections.singletonMap("&gemfirePool", mockPoolFactoryBean); + + when(mockBeanFactory.getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false))).thenReturn(beans); + when(mockPoolFactoryBean.getPool()).thenReturn(mockPool); ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); clientCacheFactoryBean.setBeanFactory(mockBeanFactory); + assertThat((ListableBeanFactory) clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory))); + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + assertThat(clientCacheFactoryBean.resolvePool(), is(equalTo(mockPool))); - clientCacheFactoryBean.createCache(mockClientCacheFactory); + verify(mockBeanFactory, times(1)).getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false)); + verify(mockPoolFactoryBean, times(1)).getPool(); + verifyZeroInteractions(mockPool); + } + @Test + public void resolvePoolReturnsNullWhenNoBeansOfTypePoolFactoryBeanExists() { + ListableBeanFactory mockBeanFactory = mock(ListableBeanFactory.class); + + Map beans = Collections.emptyMap(); + + when(mockBeanFactory.getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false))).thenReturn(beans); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setBeanFactory(mockBeanFactory); + + assertThat((ListableBeanFactory) clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory))); + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + assertThat(clientCacheFactoryBean.resolvePool(), is(nullValue())); - verify(mockBeanFactory, never()).isTypeMatch(anyString(), eq(Pool.class)); - verify(mockBeanFactory, never()).getBean(anyString(), eq(Pool.class)); - verify(mockBeanFactory, times(1)).getBean(eq(Pool.class)); - verify(mockClientCacheFactory, times(1)).create(); + verify(mockBeanFactory, times(1)).getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false)); + } + + @Test + public void resolvePoolReturnsNullWhenNoBeansOfTypePoolFactoryBeanExistsWithPoolName() { + ListableBeanFactory mockBeanFactory = mock(ListableBeanFactory.class); + Pool mockPool = mock(Pool.class); + PoolFactoryBean mockPoolFactoryBean = mock(PoolFactoryBean.class); + + Map beans = Collections.singletonMap("&swimPool", mockPoolFactoryBean); + + when(mockBeanFactory.getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false))).thenReturn(beans); + when(mockPoolFactoryBean.getPool()).thenReturn(mockPool); + + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setBeanFactory(mockBeanFactory); + clientCacheFactoryBean.setPoolName("TestPool"); + + assertThat((ListableBeanFactory) clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory))); + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool"))); + assertThat(clientCacheFactoryBean.resolvePool(), is(nullValue())); + + verify(mockBeanFactory, times(1)).getBeansOfType(eq(PoolFactoryBean.class), eq(false), eq(false)); + verify(mockPoolFactoryBean, never()).getPool(); + verifyZeroInteractions(mockPool); + } + + @Test + public void resolvePoolReturnsNullWhenBeanFactoryIsNotAListableBeanFactory() { + BeanFactory mockBeanFactory = mock(BeanFactory.class); + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + clientCacheFactoryBean.setBeanFactory(mockBeanFactory); + + assertThat(clientCacheFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory))); + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + assertThat(clientCacheFactoryBean.resolvePool(), is(nullValue())); + + verifyZeroInteractions(mockBeanFactory); } @Test @SuppressWarnings("unchecked") public void onApplicationEventCallsClientCacheReadyForEvents() { - final ClientCache mockClientCache = mock(ClientCache.class, "MockClientCache"); + final ClientCache mockClientCache = mock(ClientCache.class); ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { - @Override public boolean isReadyForEvents() { - return true; - } - @Override protected T fetchCache() { return (T) mockClientCache; } }; + clientCacheFactoryBean.setReadyForEvents(true); + + assertThat(clientCacheFactoryBean.isReadyForEvents(), is(true)); + clientCacheFactoryBean.onApplicationEvent(mock(ContextRefreshedEvent.class, "MockContextRefreshedEvent")); verify(mockClientCache, times(1)).readyForEvents(); @@ -478,20 +998,20 @@ public class ClientCacheFactoryBeanTest { @Test @SuppressWarnings("unchecked") public void onApplicationEventDoesNotCallClientCacheReadyForEventsWhenClientCacheFactoryBeanReadyForEventsIsFalse() { - final ClientCache mockClientCache = mock(ClientCache.class, "MockClientCache"); + final ClientCache mockClientCache = mock(ClientCache.class); doThrow(new RuntimeException("test")).when(mockClientCache).readyForEvents(); ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { - @Override public boolean isReadyForEvents() { - return false; - } - @Override protected T fetchCache() { return (T) mockClientCache; } }; + clientCacheFactoryBean.setReadyForEvents(false); + + assertThat(clientCacheFactoryBean.isReadyForEvents(), is(false)); + clientCacheFactoryBean.onApplicationEvent(mock(ContextRefreshedEvent.class, "MockContextRefreshedEvent")); verify(mockClientCache, never()).readyForEvents(); @@ -500,21 +1020,21 @@ public class ClientCacheFactoryBeanTest { @Test @SuppressWarnings("unchecked") public void onApplicationEventHandlesIllegalStateException() { - final ClientCache mockClientCache = mock(ClientCache.class, "MockClientCache"); + final ClientCache mockClientCache = mock(ClientCache.class); - doThrow(new IllegalStateException("non-durable client")).when(mockClientCache).readyForEvents(); + doThrow(new IllegalStateException("test")).when(mockClientCache).readyForEvents(); ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { - @Override public boolean isReadyForEvents() { - return true; - } - @Override protected T fetchCache() { return (T) mockClientCache; } }; - clientCacheFactoryBean.onApplicationEvent(mock(ContextRefreshedEvent.class, "MockContextRefreshedEvent")); + clientCacheFactoryBean.setReadyForEvents(true); + + assertThat(clientCacheFactoryBean.isReadyForEvents(), is(true)); + + clientCacheFactoryBean.onApplicationEvent(mock(ContextRefreshedEvent.class)); verify(mockClientCache, times(1)).readyForEvents(); } @@ -522,21 +1042,21 @@ public class ClientCacheFactoryBeanTest { @Test public void onApplicationEventHandlesCacheClosedException() { ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean() { - @Override public boolean isReadyForEvents() { - return true; - } - @Override protected T fetchCache() { throw new CacheClosedException("test"); } }; - clientCacheFactoryBean.onApplicationEvent(mock(ContextRefreshedEvent.class, "MockContextRefreshedEvent")); + clientCacheFactoryBean.setReadyForEvents(true); + + assertThat(clientCacheFactoryBean.isReadyForEvents(), is(true)); + + clientCacheFactoryBean.onApplicationEvent(mock(ContextRefreshedEvent.class)); } @Test public void closeClientCacheWithKeepAlive() { - ClientCache mockClientCache = mock(ClientCache.class, "MockClientCache"); + ClientCache mockClientCache = mock(ClientCache.class); ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); @@ -551,7 +1071,7 @@ public class ClientCacheFactoryBeanTest { @Test public void closeClientCacheWithoutKeepAlive() { - ClientCache mockClientCache = mock(ClientCache.class, "MockClientCache"); + ClientCache mockClientCache = mock(ClientCache.class); ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); @@ -566,7 +1086,7 @@ public class ClientCacheFactoryBeanTest { @Test public void autoReconnectDisabled() { - assertFalse(new ClientCacheFactoryBean().getEnableAutoReconnect()); + assertThat(new ClientCacheFactoryBean().getEnableAutoReconnect(), is(false)); } @Test(expected = UnsupportedOperationException.class) @@ -574,26 +1094,125 @@ public class ClientCacheFactoryBeanTest { new ClientCacheFactoryBean().setEnableAutoReconnect(true); } - @Test(expected = IllegalArgumentException.class) - public void setPoolToNull() { - try { - new ClientCacheFactoryBean().setPool(null); - } - catch (IllegalArgumentException expected) { - assertEquals("GemFire Pool must not be null", expected.getMessage()); - throw expected; - } + @Test + public void clusterConfigurationNotUsed() { + assertThat(new ClientCacheFactoryBean().getUseClusterConfiguration(), is(false)); } - @Test(expected = IllegalArgumentException.class) - public void setPoolNameWithAnIllegalArgument() { - try { - new ClientCacheFactoryBean().setPoolName(" "); - } - catch (IllegalArgumentException expected) { - assertEquals("Pool 'name' is required", expected.getMessage()); - throw expected; - } + @Test(expected = UnsupportedOperationException.class) + public void useClusterConfiguration() { + new ClientCacheFactoryBean().setUseClusterConfiguration(true); + } + + @Test + public void setAndGetKeepAlive() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + assertThat(clientCacheFactoryBean.getKeepAlive(), is(false)); + assertThat(clientCacheFactoryBean.isKeepAlive(), is(false)); + + clientCacheFactoryBean.setKeepAlive(true); + + assertThat(clientCacheFactoryBean.getKeepAlive(), is(true)); + assertThat(clientCacheFactoryBean.isKeepAlive(), is(true)); + + clientCacheFactoryBean.setKeepAlive(null); + + assertThat(clientCacheFactoryBean.getKeepAlive(), is(nullValue())); + assertThat(clientCacheFactoryBean.isKeepAlive(), is(false)); + } + + @Test + public void setAndGetPool() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + Pool mockPool = mock(Pool.class); + + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); + + clientCacheFactoryBean.setPool(mockPool); + + assertThat(clientCacheFactoryBean.getPool(), is(sameInstance(mockPool))); + + clientCacheFactoryBean.setPool(null); + + assertThat(clientCacheFactoryBean.getPool(), is(nullValue())); + } + + @Test + public void setAndGetPoolName() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + + clientCacheFactoryBean.setPoolName("TestPool"); + + assertThat(clientCacheFactoryBean.getPoolName(), is(equalTo("TestPool"))); + + clientCacheFactoryBean.setPoolName(null); + + assertThat(clientCacheFactoryBean.getPoolName(), is(nullValue())); + } + + @Test + public void setAndGetPoolSettings() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + assertThat(clientCacheFactoryBean.getFreeConnectionTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getIdleTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getLoadConditioningInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getMaxConnections(), is(nullValue())); + assertThat(clientCacheFactoryBean.getMinConnections(), is(nullValue())); + assertThat(clientCacheFactoryBean.getMultiUserAuthentication(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPingInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getPrSingleHopEnabled(), is(nullValue())); + assertThat(clientCacheFactoryBean.getReadTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getRetryAttempts(), is(nullValue())); + assertThat(clientCacheFactoryBean.getServerGroup(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSocketBufferSize(), is(nullValue())); + assertThat(clientCacheFactoryBean.getStatisticsInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionAckInterval(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionEnabled(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionMessageTrackingTimeout(), is(nullValue())); + assertThat(clientCacheFactoryBean.getSubscriptionRedundancy(), is(nullValue())); + assertThat(clientCacheFactoryBean.getThreadLocalConnections(), is(nullValue())); + + clientCacheFactoryBean.setFreeConnectionTimeout(5000); + clientCacheFactoryBean.setIdleTimeout(120000l); + clientCacheFactoryBean.setLoadConditioningInterval(300000); + clientCacheFactoryBean.setMaxConnections(500); + clientCacheFactoryBean.setMinConnections(50); + clientCacheFactoryBean.setMultiUserAuthentication(true); + clientCacheFactoryBean.setPingInterval(15000l); + clientCacheFactoryBean.setPrSingleHopEnabled(true); + clientCacheFactoryBean.setReadTimeout(30000); + clientCacheFactoryBean.setRetryAttempts(1); + clientCacheFactoryBean.setServerGroup("test"); + clientCacheFactoryBean.setSocketBufferSize(16384); + clientCacheFactoryBean.setStatisticsInterval(500); + clientCacheFactoryBean.setSubscriptionAckInterval(200); + clientCacheFactoryBean.setSubscriptionEnabled(true); + clientCacheFactoryBean.setSubscriptionMessageTrackingTimeout(20000); + clientCacheFactoryBean.setSubscriptionRedundancy(2); + clientCacheFactoryBean.setThreadLocalConnections(false); + + assertThat(clientCacheFactoryBean.getFreeConnectionTimeout(), is(equalTo(5000))); + assertThat(clientCacheFactoryBean.getIdleTimeout(), is(equalTo(120000l))); + assertThat(clientCacheFactoryBean.getLoadConditioningInterval(), is(equalTo(300000))); + assertThat(clientCacheFactoryBean.getMaxConnections(), is(equalTo(500))); + assertThat(clientCacheFactoryBean.getMinConnections(), is(equalTo(50))); + assertThat(clientCacheFactoryBean.getMultiUserAuthentication(), is(equalTo(true))); + assertThat(clientCacheFactoryBean.getPingInterval(), is(equalTo(15000l))); + assertThat(clientCacheFactoryBean.getPrSingleHopEnabled(), is(equalTo(true))); + assertThat(clientCacheFactoryBean.getReadTimeout(), is(equalTo(30000))); + assertThat(clientCacheFactoryBean.getRetryAttempts(), is(equalTo(1))); + assertThat(clientCacheFactoryBean.getServerGroup(), is(equalTo("test"))); + assertThat(clientCacheFactoryBean.getSocketBufferSize(), is(16384)); + assertThat(clientCacheFactoryBean.getStatisticsInterval(), is(equalTo(500))); + assertThat(clientCacheFactoryBean.getSubscriptionAckInterval(), is(equalTo(200))); + assertThat(clientCacheFactoryBean.getSubscriptionEnabled(), is(equalTo(true))); + assertThat(clientCacheFactoryBean.getSubscriptionMessageTrackingTimeout(), is(equalTo(20000))); + assertThat(clientCacheFactoryBean.getSubscriptionRedundancy(), is(equalTo(2))); + assertThat(clientCacheFactoryBean.getThreadLocalConnections(), is(equalTo(false))); } @Test @@ -616,9 +1235,9 @@ public class ClientCacheFactoryBeanTest { } protected ClientCache mockClientCache(String durableClientId) { - ClientCache mockClientCache = mock(ClientCache.class, "MockClientCache"); + ClientCache mockClientCache = mock(ClientCache.class); - DistributedSystem mockDistributedSystem = mock(DistributedSystem.class, "MockDistributedSystem"); + DistributedSystem mockDistributedSystem = mock(DistributedSystem.class); Properties gemfireProperties = new Properties(); @@ -648,7 +1267,7 @@ public class ClientCacheFactoryBeanTest { assertThat(clientCacheFactoryBean.getReadyForEvents(), is(true)); assertThat(clientCacheFactoryBean.isReadyForEvents(), is(true)); - verify(mockClientCache, never()).getDistributedSystem(); + verifyZeroInteractions(mockClientCache); } @Test @@ -667,7 +1286,7 @@ public class ClientCacheFactoryBeanTest { assertThat(clientCacheFactoryBean.getReadyForEvents(), is(false)); assertThat(clientCacheFactoryBean.isReadyForEvents(), is(false)); - verify(mockClientCache, never()).getDistributedSystem(); + verifyZeroInteractions(mockClientCache); } @Test @@ -717,13 +1336,73 @@ public class ClientCacheFactoryBeanTest { } @Test - public void clusterConfigurationNotUsed() { - assertFalse(new ClientCacheFactoryBean().getUseClusterConfiguration()); + public void addSetAndGetLocators() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + assertThat(clientCacheFactoryBean.getLocators(), is(notNullValue())); + assertThat(clientCacheFactoryBean.getLocators().isEmpty(), is(true)); + + ConnectionEndpoint localhost = newConnectionEndpoint("localhost", 21668); + + clientCacheFactoryBean.addLocators(localhost); + + assertThat(clientCacheFactoryBean.getLocators().size(), is(equalTo(1))); + assertThat(clientCacheFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost))); + + ConnectionEndpoint skullbox = newConnectionEndpoint("skullbox", 10334); + ConnectionEndpoint boombox = newConnectionEndpoint("boombox", 10334); + + clientCacheFactoryBean.addLocators(skullbox, boombox); + + assertThat(clientCacheFactoryBean.getLocators().size(), is(equalTo(3))); + assertThat(clientCacheFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost))); + assertThat(clientCacheFactoryBean.getLocators().findOne("skullbox"), is(equalTo(skullbox))); + assertThat(clientCacheFactoryBean.getLocators().findOne("boombox"), is(equalTo(boombox))); + + clientCacheFactoryBean.setLocators(SpringUtils.toArray(localhost)); + + assertThat(clientCacheFactoryBean.getLocators().size(), is(equalTo(1))); + assertThat(clientCacheFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost))); + + clientCacheFactoryBean.setLocators(Collections.emptyList()); + + assertThat(clientCacheFactoryBean.getLocators(), is(notNullValue())); + assertThat(clientCacheFactoryBean.getLocators().isEmpty(), is(true)); } - @Test(expected = UnsupportedOperationException.class) - public void useClusterConfiguration() { - new ClientCacheFactoryBean().setUseClusterConfiguration(true); + @Test + public void addSetAndGetServers() { + ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); + + assertThat(clientCacheFactoryBean.getServers(), is(notNullValue())); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); + + ConnectionEndpoint localhost = newConnectionEndpoint("localhost", 21668); + + clientCacheFactoryBean.addServers(localhost); + + assertThat(clientCacheFactoryBean.getServers().size(), is(equalTo(1))); + assertThat(clientCacheFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost))); + + ConnectionEndpoint skullbox = newConnectionEndpoint("skullbox", 10334); + ConnectionEndpoint boombox = newConnectionEndpoint("boombox", 10334); + + clientCacheFactoryBean.addServers(skullbox, boombox); + + assertThat(clientCacheFactoryBean.getServers().size(), is(equalTo(3))); + assertThat(clientCacheFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost))); + assertThat(clientCacheFactoryBean.getServers().findOne("skullbox"), is(equalTo(skullbox))); + assertThat(clientCacheFactoryBean.getServers().findOne("boombox"), is(equalTo(boombox))); + + clientCacheFactoryBean.setServers(SpringUtils.toArray(localhost)); + + assertThat(clientCacheFactoryBean.getServers().size(), is(equalTo(1))); + assertThat(clientCacheFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost))); + + clientCacheFactoryBean.setServers(Collections.emptyList()); + + assertThat(clientCacheFactoryBean.getServers(), is(notNullValue())); + assertThat(clientCacheFactoryBean.getServers().isEmpty(), is(true)); } } diff --git a/src/test/java/org/springframework/data/gemfire/client/ClientCacheTest.java b/src/test/java/org/springframework/data/gemfire/client/ClientCacheTest.java index 3dfe0b53..8f4d8431 100644 --- a/src/test/java/org/springframework/data/gemfire/client/ClientCacheTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/ClientCacheTest.java @@ -15,24 +15,22 @@ */ package org.springframework.data.gemfire.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.data.gemfire.config.GemfireConstants; import org.springframework.data.gemfire.test.GemfireTestApplicationContextInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.client.ClientCache; /** * @author David Turanski @@ -40,26 +38,27 @@ import com.gemstone.gemfire.cache.client.ClientCache; */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "client-cache.xml", initializers = GemfireTestApplicationContextInitializer.class) -@SuppressWarnings("unused") public class ClientCacheTest { - @Autowired - private ClientCache cache; - - @Resource(name = "challengeQuestionsRegion") + @Resource(name = "ChallengeQuestions") + @SuppressWarnings("all") private Region region; @Test - public void testPoolName() { - assertEquals(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME, region.getAttributes().getPoolName()); + public void clientCacheIsNotClosed() { + ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( + "/org/springframework/data/gemfire/client/client-cache-no-close.xml"); + + Cache cache = context.getBean(Cache.class); + + context.close(); + + assertThat(cache.isClosed(), is(false)); } @Test - public void testNoClose() { - ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("/org/springframework/data/gemfire/client/client-cache-no-close.xml"); - Cache cache = ctx.getBean(Cache.class); - ctx.close(); - assertFalse(cache.isClosed()); + public void poolNameEqualsDefault() { + assertThat(region.getAttributes().getPoolName(), is(nullValue())); } } diff --git a/src/test/java/org/springframework/data/gemfire/client/ClientReadyForEventsTest.java b/src/test/java/org/springframework/data/gemfire/client/ClientReadyForEventsTest.java deleted file mode 100644 index b5fa7c66..00000000 --- a/src/test/java/org/springframework/data/gemfire/client/ClientReadyForEventsTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2010-2013 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.client; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.data.gemfire.TestUtils; -import org.springframework.data.gemfire.test.GemfireTestApplicationContextInitializer; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Lyndon Adams - * - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "client-cache-ready-for-events.xml", - initializers = GemfireTestApplicationContextInitializer.class) -@SuppressWarnings("unused") -public class ClientReadyForEventsTest { - - @Autowired - private ApplicationContext context; - - @Test - public void testReadyForEvents() throws Exception { - ClientCacheFactoryBean clientCacheFactoryBean = context.getBean("&gemfireCache", ClientCacheFactoryBean.class); - Boolean readyForEvents = TestUtils.readField("readyForEvents", clientCacheFactoryBean); - assertTrue(readyForEvents); - } - -} diff --git a/src/test/java/org/springframework/data/gemfire/client/ClientRegionFactoryBeanTest.java b/src/test/java/org/springframework/data/gemfire/client/ClientRegionFactoryBeanTest.java index 39b61990..7ded23a1 100644 --- a/src/test/java/org/springframework/data/gemfire/client/ClientRegionFactoryBeanTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/ClientRegionFactoryBeanTest.java @@ -32,6 +32,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import java.io.InputStream; @@ -42,6 +43,7 @@ import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.core.io.Resource; import org.springframework.data.gemfire.TestUtils; +import org.springframework.data.gemfire.config.GemfireConstants; import com.gemstone.gemfire.cache.DataPolicy; import com.gemstone.gemfire.cache.EvictionAttributes; @@ -189,71 +191,84 @@ public class ClientRegionFactoryBeanTest { @Test @SuppressWarnings("unchecked") public void testLookupFallbackWithSpecifiedShortcut() throws Exception { + BeanFactory mockBeanFactory = mock(BeanFactory.class); ClientCache mockClientCache = mock(ClientCache.class); ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class); Region mockRegion = mock(Region.class); - when(mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.CACHING_PROXY))).thenReturn( - mockClientRegionFactory); + when(mockBeanFactory.containsBean(anyString())).thenReturn(true); + when(mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.CACHING_PROXY))) + .thenReturn(mockClientRegionFactory); when(mockClientRegionFactory.create(eq("TestRegion"))).thenReturn(mockRegion); factoryBean.setAttributes(null); - factoryBean.setBeanFactory(null); + factoryBean.setBeanFactory(mockBeanFactory); factoryBean.setShortcut(ClientRegionShortcut.CACHING_PROXY); Region actualRegion = factoryBean.lookupFallback(mockClientCache, "TestRegion"); assertSame(mockRegion, actualRegion); + verify(mockBeanFactory, times(1)).containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME)); verify(mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.CACHING_PROXY)); verify(mockClientRegionFactory, times(1)).create(eq("TestRegion")); + verifyZeroInteractions(mockRegion); } @Test @SuppressWarnings("unchecked") public void testLookupFallbackWithSubRegionCreation() throws Exception { + BeanFactory mockBeanFactory = mock(BeanFactory.class); ClientCache mockClientCache = mock(ClientCache.class); ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class); - Region mockParentRegion = mock(Region.class, "Parent"); + Region mockRegion = mock(Region.class, "RootRegion"); Region mockSubRegion = mock(Region.class, "SubRegion"); + when(mockBeanFactory.containsBean(anyString())).thenReturn(true); when(mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.PROXY))).thenReturn(mockClientRegionFactory); - when(mockClientRegionFactory.createSubregion(eq(mockParentRegion), eq("TestSubRegion"))).thenReturn(mockSubRegion); + when(mockClientRegionFactory.createSubregion(eq(mockRegion), eq("TestSubRegion"))).thenReturn(mockSubRegion); factoryBean.setAttributes(null); - factoryBean.setBeanFactory(null); - factoryBean.setParent(mockParentRegion); + factoryBean.setBeanFactory(mockBeanFactory); + factoryBean.setParent(mockRegion); factoryBean.setShortcut(ClientRegionShortcut.PROXY); Region actualRegion = factoryBean.lookupFallback(mockClientCache, "TestSubRegion"); assertSame(mockSubRegion, actualRegion); + verify(mockBeanFactory, times(1)).containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME)); verify(mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.PROXY)); - verify(mockClientRegionFactory, times(1)).createSubregion(eq(mockParentRegion), eq("TestSubRegion")); + verify(mockClientRegionFactory, times(1)).createSubregion(eq(mockRegion), eq("TestSubRegion")); + verifyZeroInteractions(mockRegion); + verifyZeroInteractions(mockSubRegion); } @Test @SuppressWarnings("unchecked") public void testLookupFallbackWithUnspecifiedPool() throws Exception { + BeanFactory mockBeanFactory = mock(BeanFactory.class); ClientCache mockClientCache = mock(ClientCache.class); ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class); Region mockRegion = mock(Region.class); + when(mockBeanFactory.containsBean(anyString())).thenReturn(false); when(mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.LOCAL_HEAP_LRU))).thenReturn(mockClientRegionFactory); when(mockClientRegionFactory.create(eq("TestRegion"))).thenReturn(mockRegion); factoryBean.setAttributes(null); - factoryBean.setBeanFactory(null); + factoryBean.setBeanFactory(mockBeanFactory); factoryBean.setShortcut(ClientRegionShortcut.LOCAL_HEAP_LRU); Region actualRegion = factoryBean.lookupFallback(mockClientCache, "TestRegion"); assertSame(mockRegion, actualRegion); + verify(mockBeanFactory, times(1)).containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME)); verify(mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.LOCAL_HEAP_LRU)); verify(mockClientRegionFactory, times(1)).create(eq("TestRegion")); verify(mockClientRegionFactory, never()).setPoolName(any(String.class)); + verifyZeroInteractions(mockRegion); } @Test diff --git a/src/test/java/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest.java b/src/test/java/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest.java index ae6417a5..6816d41d 100644 --- a/src/test/java/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest.java @@ -51,7 +51,7 @@ import com.gemstone.gemfire.cache.client.ClientCache; /** * The GemFireDataSourceIntegrationTest class is a test suite of test cases testing the contract and functionality * of the <gfe-data:datasource> element in the context of a GemFire cluster running both native, - * non-Spring configured GemFire Servers in a addition to Spring configured and bootstrapped GemFire Server. + * non-Spring configured GemFire Server(s) in addition to Spring configured and bootstrapped GemFire Server(s). * * @author John Blum * @see org.junit.Test @@ -77,17 +77,19 @@ public class GemFireDataSourceIntegrationTest { @Autowired private ClientCache gemfireClientCache; - @Resource(name = "LocalRegion") - private Region localRegion; + @Resource(name = "ClientOnlyRegion") + private Region clientOnlyRegion; - @Resource(name = "ServerRegion") - private Region serverRegion; + @Resource(name = "ClientServerRegion") + private Region clientServerRegion; - @Resource(name = "ExclusiveServerRegion") - private Region exclusiveServerRegion; + @Resource(name = "ServerOnlyRegion") + private Region serverOnlyRegion; @BeforeClass public static void setupBeforeClass() throws IOException { + System.setProperty("gemfire.log-level", "warning"); + String serverName = "GemFireDataSourceSpringBasedServer"; File serverWorkingDirectory = new File(FileSystemUtils.WORKING_DIRECTORY, serverName.toLowerCase()); @@ -97,7 +99,7 @@ public class GemFireDataSourceIntegrationTest { List arguments = new ArrayList(); arguments.add(String.format("-Dgemfire.name=%1$s", serverName)); - arguments.add("/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-server-context.xml"); + arguments.add(GemFireDataSourceIntegrationTest.class.getName().replace(".", "/").concat("-server-context.xml")); serverProcess = ProcessExecutor.launch(serverWorkingDirectory, ServerProcess.class, arguments.toArray(new String[arguments.size()])); @@ -139,9 +141,9 @@ public class GemFireDataSourceIntegrationTest { @Test @SuppressWarnings("unchecked") public void clientProxyRegionBeansExist() { - assertRegion(localRegion, "LocalRegion"); - assertRegion(serverRegion, "ServerRegion"); - assertRegion(exclusiveServerRegion, "ExclusiveServerRegion"); + assertRegion(clientOnlyRegion, "ClientOnlyRegion"); + assertRegion(clientServerRegion, "ClientServerRegion"); + assertRegion(serverOnlyRegion, "ServerOnlyRegion"); } } diff --git a/src/test/java/org/springframework/data/gemfire/client/GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTest.java b/src/test/java/org/springframework/data/gemfire/client/GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTest.java index 19c4a545..157aefa3 100644 --- a/src/test/java/org/springframework/data/gemfire/client/GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTest.java @@ -88,6 +88,8 @@ public class GemFireDataSourceUsingNonSpringConfiguredGemFireServerIntegrationTe @BeforeClass public static void setupBeforeClass() throws IOException { + System.setProperty("gemfire.log-level", "warning"); + String serverName = "GemFireDataSourceGemFireBasedServer"; File serverWorkingDirectory = new File(FileSystemUtils.WORKING_DIRECTORY, serverName.toLowerCase()); diff --git a/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java b/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java index 3566b7ce..32301de0 100644 --- a/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/PoolFactoryBeanTest.java @@ -16,16 +16,17 @@ package org.springframework.data.gemfire.client; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -33,22 +34,23 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Collections; -import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.data.gemfire.TestUtils; -import org.springframework.data.gemfire.test.support.CollectionUtils; +import org.springframework.data.gemfire.support.ConnectionEndpoint; +import org.springframework.data.gemfire.util.SpringUtils; import org.springframework.data.util.ReflectionUtils; +import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.Pool; import com.gemstone.gemfire.cache.client.PoolFactory; +import com.gemstone.gemfire.cache.query.QueryService; /** * The PoolFactoryBeanTest class is a test suite of test cases testing the contract and functionality @@ -60,6 +62,8 @@ import com.gemstone.gemfire.cache.client.PoolFactory; * @see org.junit.rules.ExpectedException * @see org.mockito.Mockito * @see org.springframework.data.gemfire.client.PoolFactoryBean + * @see org.springframework.data.gemfire.support.ConnectionEndpoint + * @see com.gemstone.gemfire.cache.GemFireCache * @see com.gemstone.gemfire.cache.client.Pool * @see com.gemstone.gemfire.cache.client.PoolFactory * @since 1.7.0 @@ -67,35 +71,33 @@ import com.gemstone.gemfire.cache.client.PoolFactory; public class PoolFactoryBeanTest { @Rule - public ExpectedException expectedException = ExpectedException.none(); + public ExpectedException exception = ExpectedException.none(); + + protected ConnectionEndpoint newConnectionEndpoint(String host, int port) { + return new ConnectionEndpoint(host, port); + } + + protected InetSocketAddress newSocketAddress(String host, int port) { + return new InetSocketAddress(host, port); + } @Test @SuppressWarnings("deprecation") public void afterPropertiesSet() throws Exception { - BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockBeanFactory"); + BeanFactory mockBeanFactory = mock(BeanFactory.class); - final PoolFactory mockPoolFactory = mock(PoolFactory.class, "MockPoolFactory"); + Pool mockPool = mock(Pool.class); - Pool mockPool = mock(Pool.class, "MockPool"); + final PoolFactory mockPoolFactory = mock(PoolFactory.class); - final Properties gemfireProperties = new Properties(); - - gemfireProperties.setProperty("name", "testAfterPropertiesSet"); - - ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); - - clientCacheFactoryBean.setProperties(gemfireProperties); - - when(mockBeanFactory.getBean(eq(ClientCacheFactoryBean.class))).thenReturn(clientCacheFactoryBean); when(mockPoolFactory.create(eq("GemFirePool"))).thenReturn(mockPool); PoolFactoryBean poolFactoryBean = new PoolFactoryBean() { @Override protected PoolFactory createPoolFactory() { return mockPoolFactory; } - - @Override void doDistributedSystemConnect(Properties properties) { - assertThat(properties, is(equalTo(gemfireProperties))); + @Override boolean isDistributedSystemPresent() { + return false; } }; @@ -106,25 +108,29 @@ public class PoolFactoryBeanTest { poolFactoryBean.setIdleTimeout(120000l); poolFactoryBean.setKeepAlive(false); poolFactoryBean.setLoadConditioningInterval(15000); - poolFactoryBean.setLocators(Collections.singletonList(new InetSocketAddress(InetAddress.getLocalHost(), 54321))); + poolFactoryBean.setLocators(Collections.singletonList(newConnectionEndpoint("localhost", 54321))); poolFactoryBean.setMaxConnections(50); poolFactoryBean.setMinConnections(5); poolFactoryBean.setMultiUserAuthentication(false); poolFactoryBean.setPingInterval(5000l); poolFactoryBean.setPrSingleHopEnabled(true); + poolFactoryBean.setReadTimeout(30000); poolFactoryBean.setRetryAttempts(10); poolFactoryBean.setServerGroup("TestServerGroup"); - poolFactoryBean.setServers(Collections.singletonList(new InetSocketAddress(InetAddress.getLocalHost(), 12345))); + poolFactoryBean.setServers(Collections.singletonList(newConnectionEndpoint("localhost", 12345))); poolFactoryBean.setSocketBufferSize(32768); poolFactoryBean.setStatisticInterval(1000); poolFactoryBean.setSubscriptionAckInterval(500); + poolFactoryBean.setSubscriptionEnabled(true); poolFactoryBean.setSubscriptionMessageTrackingTimeout(20000); poolFactoryBean.setSubscriptionRedundancy(2); poolFactoryBean.setThreadLocalConnections(false); poolFactoryBean.afterPropertiesSet(); - assertSame(mockPool, poolFactoryBean.getObject()); + assertThat(poolFactoryBean.getBeanFactory(), is(equalTo(mockBeanFactory))); + assertThat(poolFactoryBean.getObject(), is(sameInstance(mockPool))); + verify(mockBeanFactory, times(1)).getBean(eq(ClientCache.class)); verify(mockPoolFactory, times(1)).setFreeConnectionTimeout(eq(60000)); verify(mockPoolFactory, times(1)).setIdleTimeout(eq(120000l)); verify(mockPoolFactory, times(1)).setLoadConditioningInterval(eq(15000)); @@ -133,16 +139,18 @@ public class PoolFactoryBeanTest { verify(mockPoolFactory, times(1)).setMultiuserAuthentication(eq(false)); verify(mockPoolFactory, times(1)).setPingInterval(eq(5000l)); verify(mockPoolFactory, times(1)).setPRSingleHopEnabled(eq(true)); + verify(mockPoolFactory, times(1)).setReadTimeout(eq(30000)); verify(mockPoolFactory, times(1)).setRetryAttempts(eq(10)); verify(mockPoolFactory, times(1)).setServerGroup(eq("TestServerGroup")); verify(mockPoolFactory, times(1)).setSocketBufferSize(eq(32768)); verify(mockPoolFactory, times(1)).setStatisticInterval(eq(1000)); verify(mockPoolFactory, times(1)).setSubscriptionAckInterval(eq(500)); + verify(mockPoolFactory, times(1)).setSubscriptionEnabled(eq(true)); verify(mockPoolFactory, times(1)).setSubscriptionMessageTrackingTimeout(eq(20000)); verify(mockPoolFactory, times(1)).setSubscriptionRedundancy(eq(2)); verify(mockPoolFactory, times(1)).setThreadLocalConnections(eq(false)); - verify(mockPoolFactory, times(1)).addLocator(InetAddress.getLocalHost().getHostName(), 54321); - verify(mockPoolFactory, times(1)).addServer(InetAddress.getLocalHost().getHostName(), 12345); + verify(mockPoolFactory, times(1)).addLocator(eq("localhost"), eq(54321)); + verify(mockPoolFactory, times(1)).addServer(eq("localhost"), eq(12345)); verify(mockPoolFactory, times(1)).create(eq("GemFirePool")); } @@ -153,105 +161,50 @@ public class PoolFactoryBeanTest { poolFactoryBean.setBeanName(null); poolFactoryBean.setName(null); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage("Pool 'name' is required"); + assertThat(poolFactoryBean.getName(), is(nullValue())); + + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("Pool 'name' is required"); poolFactoryBean.afterPropertiesSet(); } @Test @SuppressWarnings("deprecation") - public void afterPropertiesSetWithNoLocatorsOrServersSpecified() throws Exception { + public void afterPropertiesSetUsesName() throws Exception { PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); - poolFactoryBean.setBeanName("GemFirePool"); - poolFactoryBean.setLocators(null); - poolFactoryBean.setServers(Collections.emptyList()); + poolFactoryBean.setBeanName("gemfirePool"); + poolFactoryBean.setName("TestPool"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage("at least one GemFire Locator or Server is required"); + assertThat(poolFactoryBean.getLocators().isEmpty(), is(true)); + assertThat(poolFactoryBean.getServers().isEmpty(), is(true)); poolFactoryBean.afterPropertiesSet(); + + assertThat(poolFactoryBean.getName(), is(equalTo("TestPool"))); } @Test - public void resolveGemfireProperties() { - BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockBeanFactory"); - - ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); - - when(mockBeanFactory.getBean(eq(ClientCacheFactoryBean.class))).thenReturn(clientCacheFactoryBean); - - Properties expectedGemfireProperties = new Properties(); - - expectedGemfireProperties.setProperty("name", "resolveGemfirePropertiesTest"); - - clientCacheFactoryBean.setProperties(expectedGemfireProperties); - + @SuppressWarnings("deprecation") + public void afterPropertiesSetDefaultsToBeanName() throws Exception { PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); - poolFactoryBean.setBeanFactory(mockBeanFactory); + poolFactoryBean.setBeanName("swimPool"); - Properties resolvedGemfireProperties = poolFactoryBean.resolveGemfireProperties(); + assertThat(poolFactoryBean.getName(), is(nullValue())); + assertThat(poolFactoryBean.getLocators().isEmpty(), is(true)); + assertThat(poolFactoryBean.getServers().isEmpty(), is(true)); - assertThat(resolvedGemfireProperties, is(equalTo(expectedGemfireProperties))); - } + poolFactoryBean.afterPropertiesSet(); - @Test - public void resolveMergedGemfireProperties() { - BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockBeanFactory"); - - ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); - - when(mockBeanFactory.getBean(eq(ClientCacheFactoryBean.class))).thenReturn(clientCacheFactoryBean); - - Properties poolGemfireProperties = new Properties(); - Properties expectedGemfireProperties = new Properties(); - - poolGemfireProperties.setProperty("name", "resolveMergedGemfirePropertiesTest"); - poolGemfireProperties.setProperty("log-level", "warning"); - - CollectionUtils.mergePropertiesIntoMap(poolGemfireProperties, expectedGemfireProperties); - - expectedGemfireProperties.setProperty("log-level", "config"); - expectedGemfireProperties.setProperty("durableClientId", "123"); - expectedGemfireProperties.setProperty("durableClientTimeout", "60"); - - clientCacheFactoryBean.setProperties(expectedGemfireProperties); - - PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); - - poolFactoryBean.setBeanFactory(mockBeanFactory); - poolFactoryBean.setProperties(poolGemfireProperties); - - Properties resolvedGemfireProperties = poolFactoryBean.resolveGemfireProperties(); - - assertThat(resolvedGemfireProperties.getProperty("log-level"), is(equalTo("config"))); - assertThat(resolvedGemfireProperties, is(equalTo(expectedGemfireProperties))); - } - - @Test - public void resolveUnresolvableGemfireProperties() { - BeanFactory mockBeanFactory = mock(BeanFactory.class, "MockBeanFactory"); - - when(mockBeanFactory.getBean(eq(ClientCacheFactoryBean.class))).thenThrow( - new NoSuchBeanDefinitionException("TEST")); - - PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); - - poolFactoryBean.setBeanFactory(mockBeanFactory); - - Properties gemfireProperties = poolFactoryBean.resolveGemfireProperties(); - - assertThat(gemfireProperties, is(notNullValue())); - assertThat(gemfireProperties.isEmpty(), is(true)); + assertThat(poolFactoryBean.getName(), is(equalTo("swimPool"))); } @Test public void destroy() throws Exception { - Pool mockPool = mock(Pool.class, "MockPool"); + Pool mockPool = mock(Pool.class); when(mockPool.isDestroyed()).thenReturn(false); @@ -260,7 +213,7 @@ public class PoolFactoryBeanTest { poolFactoryBean.setPool(mockPool); poolFactoryBean.destroy(); - assertNull(TestUtils.readField("pool", poolFactoryBean)); + assertThat(TestUtils.readField("pool", poolFactoryBean), is(nullValue())); verify(mockPool, times(1)).releaseThreadLocalConnection(); verify(mockPool, times(1)).destroy(eq(false)); @@ -268,7 +221,7 @@ public class PoolFactoryBeanTest { @Test public void destroyWithNonSpringBasedPool() throws Exception { - Pool mockPool = mock(Pool.class, "MockGemFirePool"); + Pool mockPool = mock(Pool.class); PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); @@ -278,7 +231,7 @@ public class PoolFactoryBeanTest { verify(mockPool, never()).isDestroyed(); verify(mockPool, never()).releaseThreadLocalConnection(); - verify(mockPool, never()).destroy(any(Boolean.class)); + verify(mockPool, never()).destroy(anyBoolean()); } @Test @@ -299,4 +252,292 @@ public class PoolFactoryBeanTest { assertTrue(new PoolFactoryBean().isSingleton()); } + @Test + public void addGetAndSetLocators() { + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + + assertThat(poolFactoryBean.getLocators(), is(notNullValue())); + assertThat(poolFactoryBean.getLocators().isEmpty(), is(true)); + + ConnectionEndpoint localhost = newConnectionEndpoint("localhost", 21668); + + poolFactoryBean.addLocators(localhost); + + assertThat(poolFactoryBean.getLocators().size(), is(equalTo(1))); + assertThat(poolFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost))); + + ConnectionEndpoint skullbox = newConnectionEndpoint("skullbox", 10334); + ConnectionEndpoint boombox = newConnectionEndpoint("boombox", 10334); + + poolFactoryBean.addLocators(skullbox, boombox); + + assertThat(poolFactoryBean.getLocators().size(), is(equalTo(3))); + assertThat(poolFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost))); + assertThat(poolFactoryBean.getLocators().findOne("skullbox"), is(equalTo(skullbox))); + assertThat(poolFactoryBean.getLocators().findOne("boombox"), is(equalTo(boombox))); + + poolFactoryBean.setLocators(SpringUtils.toArray(localhost)); + + assertThat(poolFactoryBean.getLocators().size(), is(equalTo(1))); + assertThat(poolFactoryBean.getLocators().findOne("localhost"), is(equalTo(localhost))); + + poolFactoryBean.setLocators(Collections.emptyList()); + + assertThat(poolFactoryBean.getLocators(), is(notNullValue())); + assertThat(poolFactoryBean.getLocators().isEmpty(), is(true)); + } + + @Test + public void addGetAndSetServers() { + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + + assertThat(poolFactoryBean.getServers(), is(notNullValue())); + assertThat(poolFactoryBean.getServers().isEmpty(), is(true)); + + ConnectionEndpoint localhost = newConnectionEndpoint("localhost", 21668); + + poolFactoryBean.addServers(localhost); + + assertThat(poolFactoryBean.getServers().size(), is(equalTo(1))); + assertThat(poolFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost))); + + ConnectionEndpoint skullbox = newConnectionEndpoint("skullbox", 10334); + ConnectionEndpoint boombox = newConnectionEndpoint("boombox", 10334); + + poolFactoryBean.addServers(skullbox, boombox); + + assertThat(poolFactoryBean.getServers().size(), is(equalTo(3))); + assertThat(poolFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost))); + assertThat(poolFactoryBean.getServers().findOne("skullbox"), is(equalTo(skullbox))); + assertThat(poolFactoryBean.getServers().findOne("boombox"), is(equalTo(boombox))); + + poolFactoryBean.setServers(SpringUtils.toArray(localhost)); + + assertThat(poolFactoryBean.getServers().size(), is(equalTo(1))); + assertThat(poolFactoryBean.getServers().findOne("localhost"), is(equalTo(localhost))); + + poolFactoryBean.setServers(Collections.emptyList()); + + assertThat(poolFactoryBean.getServers(), is(notNullValue())); + assertThat(poolFactoryBean.getServers().isEmpty(), is(true)); + } + + @Test + public void getPoolWhenPoolIsSetIsThePool() { + Pool mockPool = mock(Pool.class); + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + + poolFactoryBean.setPool(mockPool); + + assertThat(poolFactoryBean.getPool(), is(sameInstance(mockPool))); + } + + @Test + public void getPoolWhenPoolIsUnsetIsThePoolFactoryBean() { + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + + poolFactoryBean.setFreeConnectionTimeout(5000); + poolFactoryBean.setIdleTimeout(120000l); + poolFactoryBean.setLoadConditioningInterval(300000); + poolFactoryBean.setLocators(SpringUtils.toArray(newConnectionEndpoint("skullbox", 11235))); + poolFactoryBean.setMaxConnections(500); + poolFactoryBean.setMinConnections(50); + poolFactoryBean.setMultiUserAuthentication(true); + poolFactoryBean.setPingInterval(15000l); + poolFactoryBean.setPrSingleHopEnabled(true); + poolFactoryBean.setReadTimeout(30000); + poolFactoryBean.setRetryAttempts(1); + poolFactoryBean.setServerGroup("TestGroup"); + poolFactoryBean.setServers(SpringUtils.toArray(newConnectionEndpoint("boombox", 12480))); + poolFactoryBean.setSocketBufferSize(16384); + poolFactoryBean.setStatisticInterval(500); + poolFactoryBean.setSubscriptionAckInterval(200); + poolFactoryBean.setSubscriptionEnabled(true); + poolFactoryBean.setSubscriptionMessageTrackingTimeout(20000); + poolFactoryBean.setSubscriptionRedundancy(2); + poolFactoryBean.setThreadLocalConnections(false); + + Pool pool = poolFactoryBean.getPool(); + + assertThat(pool, is(instanceOf(PoolAdapter.class))); + assertThat(pool.isDestroyed(), is(false)); + assertThat(pool.getFreeConnectionTimeout(), is(equalTo(5000))); + assertThat(pool.getIdleTimeout(), is(equalTo(120000l))); + assertThat(pool.getLoadConditioningInterval(), is(equalTo(300000))); + assertThat(pool.getLocators(), is(equalTo(Collections.singletonList(newSocketAddress("skullbox", 11235))))); + assertThat(pool.getMaxConnections(), is(equalTo(500))); + assertThat(pool.getMinConnections(), is(equalTo(50))); + assertThat(pool.getMultiuserAuthentication(), is(equalTo(true))); + assertThat(pool.getName(), is(nullValue())); + assertThat(pool.getPingInterval(), is(equalTo(15000l))); + assertThat(pool.getPRSingleHopEnabled(), is(equalTo(true))); + assertThat(pool.getReadTimeout(), is(equalTo(30000))); + assertThat(pool.getRetryAttempts(), is(equalTo(1))); + assertThat(pool.getServerGroup(), is(equalTo("TestGroup"))); + assertThat(pool.getServers(), is(equalTo(Collections.singletonList(newSocketAddress("boombox", 12480))))); + assertThat(pool.getSocketBufferSize(), is(equalTo(16384))); + assertThat(pool.getStatisticInterval(), is(equalTo(500))); + assertThat(pool.getSubscriptionAckInterval(), is(equalTo(200))); + assertThat(pool.getSubscriptionEnabled(), is(equalTo(true))); + assertThat(pool.getSubscriptionMessageTrackingTimeout(), is(equalTo(20000))); + assertThat(pool.getSubscriptionRedundancy(), is(equalTo(2))); + assertThat(pool.getThreadLocalConnections(), is(equalTo(false))); + } + + @Test + public void getPoolNameWhenBeanNameSet() { + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + + poolFactoryBean.setBeanName("PoolBean"); + poolFactoryBean.setName(null); + + assertThat(poolFactoryBean.getPool().getName(), is(equalTo("PoolBean"))); + } + + @Test + public void getPoolNameWhenBeanNameAndNameSet() { + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + + poolFactoryBean.setBeanName("PoolBean"); + poolFactoryBean.setName("TestPool"); + + assertThat(poolFactoryBean.getPool().getName(), is(equalTo("TestPool"))); + } + + @Test + public void getPoolPendingEventCountWithPool() { + Pool mockPool = mock(Pool.class); + + when(mockPool.getPendingEventCount()).thenReturn(2); + + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + Pool pool = poolFactoryBean.getPool(); + + assertThat(pool, is(not(sameInstance(mockPool)))); + assertThat(pool, is(instanceOf(PoolAdapter.class))); + + poolFactoryBean.setPool(mockPool); + + assertThat(pool.getPendingEventCount(), is(equalTo(2))); + + verify(mockPool, times(1)).getPendingEventCount(); + } + + @Test + public void getPoolPendingEventCountWithoutPoolThrowsIllegalStateException() { + exception.expect(IllegalStateException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("The Pool is not initialized"); + + new PoolFactoryBean().getPool().getPendingEventCount(); + } + + @Test + public void getPoolQueryServiceWithPool() { + Pool mockPool = mock(Pool.class); + QueryService mockQueryService = mock(QueryService.class); + + when(mockPool.getQueryService()).thenReturn(mockQueryService); + + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + Pool pool = poolFactoryBean.getPool(); + + assertThat(pool, is(not(sameInstance(mockPool)))); + assertThat(pool, is(instanceOf(PoolAdapter.class))); + + poolFactoryBean.setPool(mockPool); + + assertThat(pool.getQueryService(), is(equalTo(mockQueryService))); + + verify(mockPool, times(1)).getQueryService(); + } + + @Test + public void getPoolQueryServiceWithoutPoolThrowsIllegalStateException() { + exception.expect(IllegalStateException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("The Pool is not initialized"); + + new PoolFactoryBean().getPool().getQueryService(); + } + + @Test + public void getPoolAndDestroyWithPool() { + Pool mockPool = mock(Pool.class); + + PoolFactoryBean poolFactoryBean = new PoolFactoryBean() { + @Override public void destroy() throws Exception { + throw new IllegalStateException("test"); + } + }; + + Pool pool = poolFactoryBean.getPool(); + + assertThat(pool, is(not(sameInstance(mockPool)))); + assertThat(pool, is(instanceOf(PoolAdapter.class))); + + poolFactoryBean.setPool(mockPool); + pool.destroy(); + pool.destroy(true); + + verify(mockPool, times(1)).destroy(eq(false)); + verify(mockPool, times(1)).destroy(eq(true)); + } + + @Test + public void getPoolAndDestroyWithoutPool() { + final AtomicBoolean destroyCalled = new AtomicBoolean(false); + + PoolFactoryBean poolFactoryBean = new PoolFactoryBean() { + @Override public void destroy() throws Exception { + destroyCalled.set(true); + throw new IllegalStateException("test"); + } + }; + + Pool pool = poolFactoryBean.getPool(); + + assertThat(pool, is(instanceOf(PoolAdapter.class))); + + pool.destroy(); + + assertThat(destroyCalled.get(), is(true)); + + destroyCalled.set(false); + pool.destroy(true); + + assertThat(destroyCalled.get(), is(true)); + } + + @Test + public void getPoolAndReleaseThreadLocalConnectionWithPool() { + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + + Pool pool = poolFactoryBean.getPool(); + Pool mockPool = mock(Pool.class); + + assertThat(pool, is(not(sameInstance(mockPool)))); + assertThat(pool, is(instanceOf(PoolAdapter.class))); + + poolFactoryBean.setPool(mockPool); + pool.releaseThreadLocalConnection(); + + verify(mockPool, times(1)).releaseThreadLocalConnection(); + } + + @Test + public void getPoolAndReleaseThreadLocalConnectionWithoutPool() { + PoolFactoryBean poolFactoryBean = new PoolFactoryBean(); + + Pool pool = poolFactoryBean.getPool(); + + assertThat(pool, is(instanceOf(PoolAdapter.class))); + + exception.expect(IllegalStateException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("The Pool is not initialized"); + + pool.releaseThreadLocalConnection(); + } + } diff --git a/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java b/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java index 4ebdf71c..7fc0a7d1 100644 --- a/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java +++ b/src/test/java/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest.java @@ -18,109 +18,102 @@ package org.springframework.data.gemfire.client; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; 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.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.data.gemfire.support.ConnectionEndpoint; import org.springframework.data.gemfire.support.ConnectionEndpointList; +import org.springframework.data.gemfire.util.SpringUtils; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import com.gemstone.gemfire.cache.client.Pool; import com.gemstone.gemfire.cache.client.PoolFactory; /** - * The PoolUsingLocatorsAndServersPropertyPlaceholdersTest class... + * The PoolUsingLocatorsAndServersPropertyPlaceholdersTest class is a test suite of test cases testing the use of + * property placeholder values in the nested <gfe:locator> and <gfe:server> sub-elements + * of the <gfe:pool> element as well as the locators and servers attributes. * * @author John Blum - * @since 1.0.0 + * @see org.junit.Test + * @see org.junit.runner.RunWith + * @see org.springframework.test.context.ContextConfiguration + * @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner + * @see org.springframework.data.gemfire.client.PoolFactoryBean + * @see org.springframework.data.gemfire.config.PoolParser + * @see SGF-433 + * @since 1.6.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest { - private static ConnectionEndpointList locatorConnectionEndpoints = new ConnectionEndpointList(); - private static ConnectionEndpointList serverConnectionEndpoints = new ConnectionEndpointList(); + private static ConnectionEndpointList anotherServers = new ConnectionEndpointList(); + private static ConnectionEndpointList locators = new ConnectionEndpointList(); + private static ConnectionEndpointList servers = new ConnectionEndpointList(); - private static PoolFactory mockPoolFactory; + @Autowired + @Qualifier("locatorPool") + @SuppressWarnings("unused") + private Pool locatorPool; + + @Autowired + @Qualifier("serverPool") + @SuppressWarnings("unused") + private Pool serverPool; + + @Autowired + @Qualifier("anotherServerPool") + @SuppressWarnings("unused") + private Pool anotherServerPool; protected static ConnectionEndpoint newConnectionEndpoint(String host, int port) { return new ConnectionEndpoint(host, port); } - @BeforeClass - public static void setup() { - mockPoolFactory = mock(PoolFactory.class, "MockPoolFactory"); - - when(mockPoolFactory.addLocator(anyString(), anyInt())).thenAnswer(new Answer() { - @Override - public PoolFactory answer(final InvocationOnMock invocation) throws Throwable { - String host = invocation.getArgumentAt(0, String.class); - int port = invocation.getArgumentAt(1, Integer.class); - locatorConnectionEndpoints.add(newConnectionEndpoint(host, port)); - return mockPoolFactory; - } - }); - - when(mockPoolFactory.addServer(anyString(), anyInt())).thenAnswer(new Answer() { - @Override - public PoolFactory answer(final InvocationOnMock invocation) throws Throwable { - String host = invocation.getArgumentAt(0, String.class); - int port = invocation.getArgumentAt(1, Integer.class); - serverConnectionEndpoints.add(newConnectionEndpoint(host, port)); - return mockPoolFactory; - } - }); - } - - protected ConnectionEndpointList sort(ConnectionEndpointList list) { - List connectionEndpoints = new ArrayList(list.size()); - - for (ConnectionEndpoint connectionEndpoint : list) { - connectionEndpoints.add(connectionEndpoint); - } - - Collections.sort(connectionEndpoints); - - return new ConnectionEndpointList(connectionEndpoints); - } - - protected void assertConnectionEndpoints(ConnectionEndpointList connectionEndpoints, String... expected) { - assertThat(connectionEndpoints.isEmpty(), is(false)); - assertThat(connectionEndpoints.size(), is(equalTo(expected.length))); + protected void assertConnectionEndpoints(Iterable connectionEndpoints, String... expected) { + assertThat(connectionEndpoints, is(notNullValue())); int index = 0; for (ConnectionEndpoint connectionEndpoint : connectionEndpoints) { assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++]))); } + + assertThat(index, is(equalTo(expected.length))); + } + + @Test + public void anotherServerPoolFactoryConfiguration() { + String[] expected = { "boombox[1234]", "jambox[40404]", "toolbox[8181]" }; + + assertThat(anotherServers.size(), is(equalTo(expected.length))); + + assertConnectionEndpoints(SpringUtils.sort(anotherServers), expected); } @Test public void locatorPoolFactoryConfiguration() { String[] expected = { "backspace[10334]", "jambox[11235]", "mars[30303]", "pluto[20668]", "skullbox[12480]" }; -// System.out.printf("locatorPool is... %1$s%n", locatorConnectionEndpoints); + assertThat(locators.size(), is(equalTo(expected.length))); - assertThat(locatorConnectionEndpoints.isEmpty(), is(false)); - assertThat(locatorConnectionEndpoints.size(), is(equalTo(expected.length))); - - assertConnectionEndpoints(sort(locatorConnectionEndpoints), expected); + assertConnectionEndpoints(SpringUtils.sort(locators), expected); } @Test @@ -128,34 +121,81 @@ public class PoolUsingLocatorsAndServersPropertyPlaceholdersTest { String[] expected = { "earth[4554]", "jupiter[40404]", "mercury[1234]", "neptune[42424]", "saturn[41414]", "uranis[0]", "venus[9876]" }; -// System.out.printf("serverPool is... %1$s%n", serverConnectionEndpoints); + assertThat(servers.size(), is(equalTo(expected.length))); - assertThat(serverConnectionEndpoints.isEmpty(), is(false)); - assertThat(serverConnectionEndpoints.size(), is(equalTo(expected.length))); - - assertConnectionEndpoints(sort(serverConnectionEndpoints), expected); + assertConnectionEndpoints(SpringUtils.sort(servers), expected); } public static class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor { - @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - BeanDefinition locatorsPoolBeanDefinition = beanFactory.getBeanDefinition("locatorPool"); - locatorsPoolBeanDefinition.setBeanClassName(TestPoolFactoryBean.class.getName()); - BeanDefinition serversPoolBeanDefinition = beanFactory.getBeanDefinition("serverPool"); - serversPoolBeanDefinition.setBeanClassName(TestPoolFactoryBean.class.getName()); + BeanDefinition anotherServerPoolBeanDefinition = beanFactory.getBeanDefinition("anotherServerPool"); + anotherServerPoolBeanDefinition.setBeanClassName(AnotherServerPoolFactoryBean.class.getName()); + BeanDefinition locatorPoolBeanDefinition = beanFactory.getBeanDefinition("locatorPool"); + locatorPoolBeanDefinition.setBeanClassName(LocatorPoolFactoryBean.class.getName()); + BeanDefinition serverPoolBeanDefinition = beanFactory.getBeanDefinition("serverPool"); + serverPoolBeanDefinition.setBeanClassName(ServerPoolFactoryBean.class.getName()); + } + } + + public static class AnotherServerPoolFactoryBean extends TestPoolFactoryBean { + @Override ConnectionEndpointList getServerList() { + return anotherServers; + } + } + + public static class LocatorPoolFactoryBean extends TestPoolFactoryBean { + @Override ConnectionEndpointList getLocatorList() { + return locators; + } + } + + public static class ServerPoolFactoryBean extends TestPoolFactoryBean { + @Override ConnectionEndpointList getServerList() { + return servers; } } public static class TestPoolFactoryBean extends PoolFactoryBean { + ConnectionEndpointList getLocatorList() { + throw new UnsupportedOperationException("Not Implemented"); + } + + ConnectionEndpointList getServerList() { + throw new UnsupportedOperationException("Not Implemented"); + } + @Override protected PoolFactory createPoolFactory() { + final PoolFactory mockPoolFactory = mock(PoolFactory.class); + + when(mockPoolFactory.addLocator(anyString(), anyInt())).thenAnswer(new Answer() { + @Override + public PoolFactory answer(InvocationOnMock invocation) throws Throwable { + String host = invocation.getArgumentAt(0, String.class); + int port = invocation.getArgumentAt(1, Integer.class); + getLocatorList().add(newConnectionEndpoint(host, port)); + return mockPoolFactory; + } + }); + + when(mockPoolFactory.addServer(anyString(), anyInt())).thenAnswer(new Answer() { + @Override + public PoolFactory answer(InvocationOnMock invocation) throws Throwable { + String host = invocation.getArgumentAt(0, String.class); + int port = invocation.getArgumentAt(1, Integer.class); + getServerList().add(newConnectionEndpoint(host, port)); + return mockPoolFactory; + } + }); + return mockPoolFactory; } @Override - protected void resolveDistributedSystem() { + boolean isDistributedSystemPresent() { + return true; } } diff --git a/src/test/java/org/springframework/data/gemfire/client/support/DelegatingPoolAdapterTest.java b/src/test/java/org/springframework/data/gemfire/client/support/DelegatingPoolAdapterTest.java new file mode 100644 index 00000000..9baa0e95 --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/client/support/DelegatingPoolAdapterTest.java @@ -0,0 +1,266 @@ +/* + * Copyright 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.client.support; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import java.net.InetSocketAddress; +import java.util.Collections; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.data.gemfire.GemfireUtils; + +import com.gemstone.gemfire.cache.client.Pool; +import com.gemstone.gemfire.cache.client.PoolFactory; +import com.gemstone.gemfire.cache.query.QueryService; + +/** + * The DelegatingPoolAdapterTest class is a test suite of test cases testing the contract and functionality + * of the {@link DelegatingPoolAdapter} class. + * + * @author John Blum + * @see org.junit.Rule + * @see org.junit.Test + * @see org.junit.rules.ExpectedException + * @see org.junit.runner.RunWith + * @see org.mockito.Mock + * @see org.mockito.Mockito + * @see org.mockito.runners.MockitoJUnitRunner + * @see DelegatingPoolAdapter + * @see com.gemstone.gemfire.cache.client.Pool + * @see com.gemstone.gemfire.cache.client.PoolFactory + * @since 1.8.0 + */ +@RunWith(MockitoJUnitRunner.class) +public class DelegatingPoolAdapterTest { + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Mock + private Pool mockPool; + + @Mock + private QueryService mockQueryService; + + protected InetSocketAddress newSocketAddress(String host, int port) { + return new InetSocketAddress(host, port); + } + + @Before + public void setup() { + when(mockPool.isDestroyed()).thenReturn(false); + when(mockPool.getFreeConnectionTimeout()).thenReturn(10000); + when(mockPool.getIdleTimeout()).thenReturn(120000l); + when(mockPool.getLoadConditioningInterval()).thenReturn(300000); + when(mockPool.getLocators()).thenReturn(Collections.singletonList(newSocketAddress("skullbox", 11235))); + when(mockPool.getMaxConnections()).thenReturn(500); + when(mockPool.getMinConnections()).thenReturn(50); + when(mockPool.getMultiuserAuthentication()).thenReturn(true); + when(mockPool.getName()).thenReturn("MockPool"); + when(mockPool.getPendingEventCount()).thenReturn(2); + when(mockPool.getPingInterval()).thenReturn(15000l); + when(mockPool.getPRSingleHopEnabled()).thenReturn(true); + when(mockPool.getQueryService()).thenReturn(mockQueryService); + when(mockPool.getReadTimeout()).thenReturn(30000); + when(mockPool.getRetryAttempts()).thenReturn(1); + when(mockPool.getServerGroup()).thenReturn("TestGroup"); + when(mockPool.getServers()).thenReturn(Collections.singletonList(newSocketAddress("xghost", 12480))); + when(mockPool.getSocketBufferSize()).thenReturn(16384); + when(mockPool.getStatisticInterval()).thenReturn(1000); + when(mockPool.getSubscriptionAckInterval()).thenReturn(200); + when(mockPool.getSubscriptionEnabled()).thenReturn(true); + when(mockPool.getSubscriptionMessageTrackingTimeout()).thenReturn(60000); + when(mockPool.getSubscriptionRedundancy()).thenReturn(2); + when(mockPool.getThreadLocalConnections()).thenReturn(false); + } + + @Test + public void delegateEqualsMockPool() { + assertThat(DelegatingPoolAdapter.from(mockPool).getDelegate(), is(equalTo(mockPool))); + } + + @Test + public void mockPoolDelegateUsesMockPool() { + Pool pool = DelegatingPoolAdapter.from(mockPool); + + assertThat(pool.isDestroyed(), is(equalTo(false))); + assertThat(pool.getFreeConnectionTimeout(), is(equalTo(10000))); + assertThat(pool.getIdleTimeout(), is(equalTo(120000l))); + assertThat(pool.getLoadConditioningInterval(), is(equalTo(300000))); + assertThat(pool.getMaxConnections(), is(equalTo(500))); + assertThat(pool.getMinConnections(), is(equalTo(50))); + assertThat(pool.getMultiuserAuthentication(), is(equalTo(true))); + assertThat(pool.getLocators(), is(equalTo(Collections.singletonList(newSocketAddress("skullbox", 11235))))); + assertThat(pool.getName(), is(equalTo("MockPool"))); + assertThat(pool.getPendingEventCount(), is(equalTo(2))); + assertThat(pool.getPingInterval(), is(equalTo(15000l))); + assertThat(pool.getPRSingleHopEnabled(), is(equalTo(true))); + assertThat(pool.getQueryService(), is(equalTo(mockQueryService))); + assertThat(pool.getReadTimeout(), is(equalTo(30000))); + assertThat(pool.getRetryAttempts(), is(equalTo(1))); + assertThat(pool.getServerGroup(), is(equalTo("TestGroup"))); + assertThat(pool.getServers(), is(equalTo(Collections.singletonList(newSocketAddress("xghost", 12480))))); + assertThat(pool.getSocketBufferSize(), is(equalTo(16384))); + assertThat(pool.getStatisticInterval(), is(equalTo(1000))); + assertThat(pool.getSubscriptionAckInterval(), is(equalTo(200))); + assertThat(pool.getSubscriptionEnabled(), is(equalTo(true))); + assertThat(pool.getSubscriptionMessageTrackingTimeout(), is(equalTo(60000))); + assertThat(pool.getSubscriptionRedundancy(), is(equalTo(2))); + assertThat(pool.getThreadLocalConnections(), is(equalTo(false))); + + verify(mockPool, times(1)).isDestroyed(); + verify(mockPool, times(1)).getFreeConnectionTimeout(); + verify(mockPool, times(1)).getIdleTimeout(); + verify(mockPool, times(1)).getLoadConditioningInterval(); + verify(mockPool, times(1)).getLocators(); + verify(mockPool, times(1)).getMaxConnections(); + verify(mockPool, times(1)).getMinConnections(); + verify(mockPool, times(1)).getMultiuserAuthentication(); + verify(mockPool, times(1)).getName(); + verify(mockPool, times(1)).getPendingEventCount(); + verify(mockPool, times(1)).getPingInterval(); + verify(mockPool, times(1)).getPRSingleHopEnabled(); + verify(mockPool, times(1)).getQueryService(); + verify(mockPool, times(1)).getReadTimeout(); + verify(mockPool, times(1)).getRetryAttempts(); + verify(mockPool, times(1)).getServerGroup(); + verify(mockPool, times(1)).getServers(); + verify(mockPool, times(1)).getSocketBufferSize(); + verify(mockPool, times(1)).getStatisticInterval(); + verify(mockPool, times(1)).getSubscriptionAckInterval(); + verify(mockPool, times(1)).getSubscriptionEnabled(); + verify(mockPool, times(1)).getSubscriptionMessageTrackingTimeout(); + verify(mockPool, times(1)).getSubscriptionRedundancy(); + verify(mockPool, times(1)).getThreadLocalConnections(); + } + + @Test + public void destroyWithDelegateCallsDestroy() { + DelegatingPoolAdapter.from(mockPool).destroy(); + verify(mockPool, times(1)).destroy(); + } + + @Test + public void destroyWithKeepAliveUsingDelegateCallsDestroy() { + DelegatingPoolAdapter.from(mockPool).destroy(true); + verify(mockPool, times(1)).destroy(eq(true)); + } + + @Test + public void releaseThreadLocalConnectionWithDelegateCallsReleaseThreadLocalConnection() { + DelegatingPoolAdapter.from(mockPool).releaseThreadLocalConnection(); + verify(mockPool, times(1)).releaseThreadLocalConnection(); + } + + @Test + public void nullDelegateUsesDefaultFactorySettings() { + Pool pool = DelegatingPoolAdapter.from(null); + + assertThat(pool.getFreeConnectionTimeout(), is(equalTo(PoolFactory.DEFAULT_FREE_CONNECTION_TIMEOUT))); + assertThat(pool.getIdleTimeout(), is(equalTo(PoolFactory.DEFAULT_IDLE_TIMEOUT))); + assertThat(pool.getLoadConditioningInterval(), is(equalTo(PoolFactory.DEFAULT_LOAD_CONDITIONING_INTERVAL))); + assertThat(pool.getMaxConnections(), is(equalTo(PoolFactory.DEFAULT_MAX_CONNECTIONS))); + assertThat(pool.getMinConnections(), is(equalTo(PoolFactory.DEFAULT_MIN_CONNECTIONS))); + assertThat(pool.getMultiuserAuthentication(), is(equalTo(PoolFactory.DEFAULT_MULTIUSER_AUTHENTICATION))); + assertThat(pool.getPingInterval(), is(equalTo(PoolFactory.DEFAULT_PING_INTERVAL))); + assertThat(pool.getPRSingleHopEnabled(), is(equalTo(PoolFactory.DEFAULT_PR_SINGLE_HOP_ENABLED))); + assertThat(pool.getReadTimeout(), is(equalTo(PoolFactory.DEFAULT_READ_TIMEOUT))); + assertThat(pool.getRetryAttempts(), is(equalTo(PoolFactory.DEFAULT_RETRY_ATTEMPTS))); + assertThat(pool.getServerGroup(), is(equalTo(PoolFactory.DEFAULT_SERVER_GROUP))); + assertThat(pool.getSocketBufferSize(), is(equalTo(PoolFactory.DEFAULT_SOCKET_BUFFER_SIZE))); + assertThat(pool.getStatisticInterval(), is(equalTo(PoolFactory.DEFAULT_STATISTIC_INTERVAL))); + assertThat(pool.getSubscriptionAckInterval(), is(equalTo(PoolFactory.DEFAULT_SUBSCRIPTION_ACK_INTERVAL))); + assertThat(pool.getSubscriptionEnabled(), is(equalTo(PoolFactory.DEFAULT_SUBSCRIPTION_ENABLED))); + assertThat(pool.getSubscriptionMessageTrackingTimeout(), is(equalTo(PoolFactory.DEFAULT_SUBSCRIPTION_MESSAGE_TRACKING_TIMEOUT))); + assertThat(pool.getSubscriptionRedundancy(), is(equalTo(PoolFactory.DEFAULT_SUBSCRIPTION_REDUNDANCY))); + assertThat(pool.getThreadLocalConnections(), is(equalTo(PoolFactory.DEFAULT_THREAD_LOCAL_CONNECTIONS))); + + verifyZeroInteractions(mockPool); + } + + @Test + public void destroyedWithNullIsUnsupported() { + exception.expect(UnsupportedOperationException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage(is(equalTo(DelegatingPoolAdapter.NOT_IMPLEMENTED))); + + DelegatingPoolAdapter.from(null).isDestroyed(); + } + + @Test + public void locatorsWithNullIsEqualToEmptyList() { + assertThat(DelegatingPoolAdapter.from(null).getLocators(), is(equalTo(Collections.emptyList()))); + } + + @Test + public void nameWithNullIsEqualToDefault() { + assertThat(DelegatingPoolAdapter.from(null).getName(), is(equalTo(DelegatingPoolAdapter.DEFAULT_POOL_NAME))); + } + + @Test + public void pendingEventCountWithNullIsEqualToZero() { + assertThat(DelegatingPoolAdapter.from(null).getPendingEventCount(), is(equalTo(0))); + } + + @Test + public void queryServiceWithNullIsNull() { + assertThat(DelegatingPoolAdapter.from(null).getQueryService(), is(nullValue())); + } + + @Test + public void serversWithNullIsEqualToLocalhostListeningOnDefaultCacheServerPort() { + assertThat(DelegatingPoolAdapter.from(null).getServers(), is(equalTo(Collections.singletonList( + newSocketAddress("localhost", GemfireUtils.DEFAULT_CACHE_SERVER_PORT))))); + } + + @Test + public void destroyWithNullIsNoOp() { + DelegatingPoolAdapter.from(null).destroy(); + verify(mockPool, never()).destroy(); + } + + @Test + public void destroyWithKeepAliveUsingNullIsNoOp() { + DelegatingPoolAdapter.from(null).destroy(false); + verify(mockPool, never()).destroy(anyBoolean()); + } + + @Test + public void releaseThreadLocalConnectionWithNullIsNoOp() { + DelegatingPoolAdapter.from(null).releaseThreadLocalConnection(); + verify(mockPool, never()).releaseThreadLocalConnection(); + } + +} diff --git a/src/test/java/org/springframework/data/gemfire/client/support/FactoryDefaultsPoolAdapterTest.java b/src/test/java/org/springframework/data/gemfire/client/support/FactoryDefaultsPoolAdapterTest.java new file mode 100644 index 00000000..0bd18702 --- /dev/null +++ b/src/test/java/org/springframework/data/gemfire/client/support/FactoryDefaultsPoolAdapterTest.java @@ -0,0 +1,145 @@ +/* + * Copyright 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.client.support; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.net.InetSocketAddress; +import java.util.Collections; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.springframework.data.gemfire.GemfireUtils; + +import com.gemstone.gemfire.cache.client.PoolFactory; + +/** + * The FactoryDefaultsPoolAdapterTest class is a test suite of test cases testing the contract and functionality + * of the {@link FactoryDefaultsPoolAdapter} class. + * + * @author John Blum + * @see org.junit.Rule + * @see org.junit.Test + * @see org.junit.rules.ExpectedException + * @see FactoryDefaultsPoolAdapter + * @see com.gemstone.gemfire.cache.client.Pool + * @see com.gemstone.gemfire.cache.client.PoolFactory + * @since 1.8.0 + */ +public class FactoryDefaultsPoolAdapterTest { + + protected static final int DEFAULT_CACHE_SERVER_PORT = GemfireUtils.DEFAULT_CACHE_SERVER_PORT; + + private FactoryDefaultsPoolAdapter poolAdapter = new FactoryDefaultsPoolAdapter() { }; + + @Rule + public ExpectedException exception = ExpectedException.none(); + + protected InetSocketAddress newSocketAddress(String host, int port) { + return new InetSocketAddress(host, port); + } + + @Test + public void defaultPoolAdapterConfigurationPropertiesReturnDefaultFactorySettings() { + assertThat(poolAdapter.getFreeConnectionTimeout(), is(equalTo(PoolFactory.DEFAULT_FREE_CONNECTION_TIMEOUT))); + assertThat(poolAdapter.getIdleTimeout(), is(equalTo(PoolFactory.DEFAULT_IDLE_TIMEOUT))); + assertThat(poolAdapter.getLoadConditioningInterval(), is(equalTo(PoolFactory.DEFAULT_LOAD_CONDITIONING_INTERVAL))); + assertThat(poolAdapter.getMaxConnections(), is(equalTo(PoolFactory.DEFAULT_MAX_CONNECTIONS))); + assertThat(poolAdapter.getMinConnections(), is(equalTo(PoolFactory.DEFAULT_MIN_CONNECTIONS))); + assertThat(poolAdapter.getMultiuserAuthentication(), is(equalTo(PoolFactory.DEFAULT_MULTIUSER_AUTHENTICATION))); + assertThat(poolAdapter.getPRSingleHopEnabled(), is(equalTo(PoolFactory.DEFAULT_PR_SINGLE_HOP_ENABLED))); + assertThat(poolAdapter.getPingInterval(), is(equalTo(PoolFactory.DEFAULT_PING_INTERVAL))); + assertThat(poolAdapter.getReadTimeout(), is(equalTo(PoolFactory.DEFAULT_READ_TIMEOUT))); + assertThat(poolAdapter.getRetryAttempts(), is(equalTo(PoolFactory.DEFAULT_RETRY_ATTEMPTS))); + assertThat(poolAdapter.getServerGroup(), is(equalTo(PoolFactory.DEFAULT_SERVER_GROUP))); + assertThat(poolAdapter.getSocketBufferSize(), is(equalTo(PoolFactory.DEFAULT_SOCKET_BUFFER_SIZE))); + assertThat(poolAdapter.getStatisticInterval(), is(equalTo(PoolFactory.DEFAULT_STATISTIC_INTERVAL))); + assertThat(poolAdapter.getSubscriptionAckInterval(), is(equalTo(PoolFactory.DEFAULT_SUBSCRIPTION_ACK_INTERVAL))); + assertThat(poolAdapter.getSubscriptionEnabled(), is(equalTo(PoolFactory.DEFAULT_SUBSCRIPTION_ENABLED))); + assertThat(poolAdapter.getSubscriptionMessageTrackingTimeout(), + is(equalTo(PoolFactory.DEFAULT_SUBSCRIPTION_MESSAGE_TRACKING_TIMEOUT))); + assertThat(poolAdapter.getSubscriptionRedundancy(), is(equalTo(PoolFactory.DEFAULT_SUBSCRIPTION_REDUNDANCY))); + assertThat(poolAdapter.getThreadLocalConnections(), is(equalTo(PoolFactory.DEFAULT_THREAD_LOCAL_CONNECTIONS))); + } + + @Test + public void locatorsEqualsEmptyList() { + assertThat(poolAdapter.getLocators(), is(equalTo(Collections.emptyList()))); + } + + @Test + public void nameEqualsDefault() { + assertThat(poolAdapter.getName(), is(equalTo(FactoryDefaultsPoolAdapter.DEFAULT_POOL_NAME))); + } + + @Test + public void queryServiceIsNull() { + assertThat(poolAdapter.getQueryService(), is(nullValue())); + } + + @Test + public void serversEqualsLocalhostListeningOnDefaultCacheServerPort() { + assertThat(poolAdapter.getServers(), is(equalTo(Collections.singletonList( + newSocketAddress("localhost", DEFAULT_CACHE_SERVER_PORT))))); + } + + @Test + public void isDestroyedIsUnsupported() { + exception.expect(UnsupportedOperationException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage(FactoryDefaultsPoolAdapter.NOT_IMPLEMENTED); + poolAdapter.isDestroyed(); + } + + @Test + public void getPendingEventCountIsUnsupported() { + exception.expect(UnsupportedOperationException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage(FactoryDefaultsPoolAdapter.NOT_IMPLEMENTED); + poolAdapter.getPendingEventCount(); + } + + @Test + public void destroyedIsUnsupported() { + exception.expect(UnsupportedOperationException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage(FactoryDefaultsPoolAdapter.NOT_IMPLEMENTED); + poolAdapter.destroy(); + } + + @Test + public void destroyedWithKeepAliveIsUnsupported() { + exception.expect(UnsupportedOperationException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage(FactoryDefaultsPoolAdapter.NOT_IMPLEMENTED); + poolAdapter.destroy(false); + } + + @Test + public void releaseThreadLocalConnectionsIsUnsupported() { + exception.expect(UnsupportedOperationException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage(FactoryDefaultsPoolAdapter.NOT_IMPLEMENTED); + poolAdapter.releaseThreadLocalConnection(); + } + +} diff --git a/src/test/java/org/springframework/data/gemfire/config/CacheNamespaceTest.java b/src/test/java/org/springframework/data/gemfire/config/CacheNamespaceTest.java index 1b11d6e3..4f8ced34 100644 --- a/src/test/java/org/springframework/data/gemfire/config/CacheNamespaceTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/CacheNamespaceTest.java @@ -127,7 +127,7 @@ public class CacheNamespaceTest{ } @Test - public void testCacheWithAutoReconnectDisabled() { + public void testCacheWithAutoReconnectDisabled() throws Exception { assertTrue(context.containsBean("cache-with-auto-reconnect-disabled")); Cache gemfireCache = context.getBean("cache-with-auto-reconnect-disabled", Cache.class); @@ -141,16 +141,13 @@ public class CacheNamespaceTest{ } @Test - public void testCacheWithAutoReconnectEnabled() { + public void testCacheWithAutoReconnectEnabled() throws Exception { assertTrue(context.containsBean("cache-with-auto-reconnect-enabled")); Cache gemfireCache = context.getBean("cache-with-auto-reconnect-enabled", Cache.class); - boolean expected = Boolean.getBoolean("org.springframework.data.gemfire.test.GemfireTestRunner.nomock"); - boolean actual = Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties() - .getProperty("disable-auto-reconnect")); - - assertEquals(String.format("Expected 'disable-auto-reconnect' to be %1$s!", expected), expected, actual); + assertFalse(Boolean.parseBoolean(gemfireCache.getDistributedSystem().getProperties() + .getProperty("disable-auto-reconnect"))); CacheFactoryBean cacheFactoryBean = context.getBean("&cache-with-auto-reconnect-enabled", CacheFactoryBean.class); diff --git a/src/test/java/org/springframework/data/gemfire/config/ClientCacheNamespaceTest.java b/src/test/java/org/springframework/data/gemfire/config/ClientCacheNamespaceTest.java index 96b425c3..3980f741 100644 --- a/src/test/java/org/springframework/data/gemfire/config/ClientCacheNamespaceTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/ClientCacheNamespaceTest.java @@ -68,11 +68,11 @@ public class ClientCacheNamespaceTest { assertThat(clientCacheFactoryBean.getDurableClientId(), is(equalTo("TestDurableClientId"))); assertThat(clientCacheFactoryBean.getDurableClientTimeout(), is(equalTo(600))); assertThat(clientCacheFactoryBean.getEvictionHeapPercentage(), is(equalTo(0.65f))); - assertThat((PdxSerializer) clientCacheFactoryBean.getPdxSerializer(), is(equalTo(reflectionPdxSerializer))); + assertThat(clientCacheFactoryBean.isKeepAlive(), is(true)); assertThat(clientCacheFactoryBean.getPdxIgnoreUnreadFields(), is(true)); assertThat(clientCacheFactoryBean.getPdxPersistent(), is(false)); assertThat(clientCacheFactoryBean.getPdxReadSerialized(), is(true)); - assertThat(clientCacheFactoryBean.isKeepAlive(), is(true)); + assertThat((PdxSerializer) clientCacheFactoryBean.getPdxSerializer(), is(equalTo(reflectionPdxSerializer))); assertThat(TestUtils.readField("poolName", clientCacheFactoryBean), is(equalTo("serverPool"))); assertThat(clientCacheFactoryBean.getReadyForEvents(), is(false)); } diff --git a/src/test/java/org/springframework/data/gemfire/config/ClientCacheParserTest.java b/src/test/java/org/springframework/data/gemfire/config/ClientCacheParserTest.java index eb21989a..86c21060 100644 --- a/src/test/java/org/springframework/data/gemfire/config/ClientCacheParserTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/ClientCacheParserTest.java @@ -22,25 +22,17 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isNotNull; -import static org.mockito.Matchers.same; -import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.util.concurrent.atomic.AtomicReference; - import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; @@ -76,7 +68,7 @@ public class ClientCacheParserTest { } @Test - public void doParseSetsPropertiesAndRegistersClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor() { + public void doParseSetsProperties() { NodeList mockNodeList = mock(NodeList.class); when(mockNodeList.getLength()).thenReturn(0); @@ -87,24 +79,8 @@ public class ClientCacheParserTest { when(mockElement.getAttribute(eq("ready-for-events"))).thenReturn(null); when(mockElement.getChildNodes()).thenReturn(mockNodeList); - final AtomicReference beanDefinitionReference = new AtomicReference(null); - final BeanDefinitionRegistry mockRegistry = mock(BeanDefinitionRegistry.class); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - BeanDefinition beanFactoryPostProcessorBeanDefinition = - invocation.getArgumentAt(1, BeanDefinition.class); - - if (ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessor.class.getName().equals( - beanFactoryPostProcessorBeanDefinition.getBeanClassName())) { - beanDefinitionReference.compareAndSet(null, beanFactoryPostProcessorBeanDefinition); - } - - return null; - } - }).when(mockRegistry).registerBeanDefinition(isNotNull(String.class), any(BeanDefinition.class)); - when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false); BeanDefinitionBuilder clientCacheBuilder = BeanDefinitionBuilder.genericBeanDefinition(); @@ -129,15 +105,12 @@ public class ClientCacheParserTest { assertThat((String) propertyValues.getPropertyValue("keepAlive").getValue(), is(equalTo("false"))); assertThat((String) propertyValues.getPropertyValue("poolName").getValue(), is(equalTo("testPool"))); assertThat(propertyValues.getPropertyValue("readyForEvents"), is(nullValue())); - assertThat(beanDefinitionReference.get(), is(notNullValue())); verify(mockElement, times(1)).getAttribute(eq("durable-client-id")); verify(mockElement, times(1)).getAttribute(eq("durable-client-timeout")); verify(mockElement, times(1)).getAttribute(eq("keep-alive")); verify(mockElement, times(1)).getAttribute(eq("pool-name")); verify(mockElement, times(1)).getAttribute(eq("ready-for-events")); - verify(mockRegistry, times(1)).registerBeanDefinition(isNotNull(String.class), - same(beanDefinitionReference.get())); } @Test diff --git a/src/test/java/org/springframework/data/gemfire/config/ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessorTest.java b/src/test/java/org/springframework/data/gemfire/config/ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessorTest.java index 6efa365b..5bc53096 100644 --- a/src/test/java/org/springframework/data/gemfire/config/ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessorTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessorTest.java @@ -51,6 +51,7 @@ import org.springframework.data.gemfire.client.PoolFactoryBean; * @since 1.0.0 */ @RunWith(MockitoJUnitRunner.class) +@SuppressWarnings("deprecation") public class ClientCachePoolGemfirePropertiesSyncingBeanFactoryPostProcessorTest { protected static final String PROPERTIES_PROPERTY_NAME_SHORTCUT = diff --git a/src/test/java/org/springframework/data/gemfire/config/ClientRegionNamespaceTest.java b/src/test/java/org/springframework/data/gemfire/config/ClientRegionNamespaceTest.java index fb797e5a..f1b7ed64 100644 --- a/src/test/java/org/springframework/data/gemfire/config/ClientRegionNamespaceTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/ClientRegionNamespaceTest.java @@ -45,7 +45,6 @@ import org.springframework.data.gemfire.SimpleObjectSizer; import org.springframework.data.gemfire.TestUtils; import org.springframework.data.gemfire.client.ClientRegionFactoryBean; import org.springframework.data.gemfire.client.Interest; -import org.springframework.data.gemfire.test.GemfireTestApplicationContextInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.ObjectUtils; @@ -78,7 +77,7 @@ import com.gemstone.gemfire.compression.Compressor; * @see org.springframework.data.gemfire.config.ClientRegionParser */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations="client-ns.xml", initializers=GemfireTestApplicationContextInitializer.class) +@ContextConfiguration(locations="client-ns.xml") @SuppressWarnings("unused") public class ClientRegionNamespaceTest { diff --git a/src/test/java/org/springframework/data/gemfire/config/CustomEditorRegistrationBeanFactoryPostProcessorTest.java b/src/test/java/org/springframework/data/gemfire/config/CustomEditorRegistrationBeanFactoryPostProcessorTest.java index a6d6bc7d..5a650c00 100644 --- a/src/test/java/org/springframework/data/gemfire/config/CustomEditorRegistrationBeanFactoryPostProcessorTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/CustomEditorRegistrationBeanFactoryPostProcessorTest.java @@ -16,6 +16,10 @@ package org.springframework.data.gemfire.config; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -36,6 +40,7 @@ import org.springframework.data.gemfire.ScopeConverter; import org.springframework.data.gemfire.client.InterestResultPolicyConverter; import org.springframework.data.gemfire.server.SubscriptionEvictionPolicy; import org.springframework.data.gemfire.server.SubscriptionEvictionPolicyConverter; +import org.springframework.data.gemfire.support.ConnectionEndpoint; import org.springframework.data.gemfire.wan.OrderPolicyConverter; import org.springframework.data.gemfire.wan.StartupPolicyConverter; import org.springframework.data.gemfire.wan.StartupPolicyType; @@ -59,12 +64,13 @@ import com.gemstone.gemfire.cache.util.Gateway; public class CustomEditorRegistrationBeanFactoryPostProcessorTest { @Test - public void testCustomEditorRegistration() { - ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class, - "testCustomEditorRegistration.MockBeanFactory"); + public void customEditorRegistration() { + ConfigurableListableBeanFactory mockBeanFactory = mock(ConfigurableListableBeanFactory.class); new CustomEditorRegistrationBeanFactoryPostProcessor().postProcessBeanFactory(mockBeanFactory); + verify(mockBeanFactory, times(1)).registerCustomEditor(eq(ConnectionEndpoint[].class), eq( + CustomEditorRegistrationBeanFactoryPostProcessor.ConnectionEndpointArrayToIterableConverter.class)); verify(mockBeanFactory, times(1)).registerCustomEditor(eq(EvictionAction.class), eq(EvictionActionConverter.class)); verify(mockBeanFactory, times(1)).registerCustomEditor(eq(EvictionPolicyType.class), @@ -73,12 +79,14 @@ public class CustomEditorRegistrationBeanFactoryPostProcessorTest { eq(ExpirationActionConverter.class)); verify(mockBeanFactory, times(1)).registerCustomEditor(eq(IndexMaintenancePolicyType.class), eq(IndexMaintenancePolicyConverter.class)); - verify(mockBeanFactory, times(1)).registerCustomEditor(eq(IndexType.class), eq(IndexTypeConverter.class)); + verify(mockBeanFactory, times(1)).registerCustomEditor(eq(IndexType.class), + eq(IndexTypeConverter.class)); verify(mockBeanFactory, times(1)).registerCustomEditor(eq(InterestPolicy.class), eq(InterestPolicyConverter.class)); verify(mockBeanFactory, times(1)).registerCustomEditor(eq(InterestResultPolicy.class), eq(InterestResultPolicyConverter.class)); - verify(mockBeanFactory, times(1)).registerCustomEditor(eq(Scope.class), eq(ScopeConverter.class)); + verify(mockBeanFactory, times(1)).registerCustomEditor(eq(Scope.class), + eq(ScopeConverter.class)); verify(mockBeanFactory, times(1)).registerCustomEditor(eq(Gateway.OrderPolicy.class), eq(OrderPolicyConverter.class)); verify(mockBeanFactory, times(1)).registerCustomEditor(eq(StartupPolicyType.class), @@ -87,4 +95,30 @@ public class CustomEditorRegistrationBeanFactoryPostProcessorTest { eq(SubscriptionEvictionPolicyConverter.class)); } + protected ConnectionEndpoint newConnectionEndpoint(String host, int port) { + return new ConnectionEndpoint(host, port); + } + + @Test + @SuppressWarnings("unchecked") + public void connectionEndpointArrayToIterableConversion() { + ConnectionEndpoint[] array = { + newConnectionEndpoint("localhost", 10334), + newConnectionEndpoint("localhost", 40404) + }; + + Iterable iterable = new CustomEditorRegistrationBeanFactoryPostProcessor + .ConnectionEndpointArrayToIterableConverter().convert(array); + + assertThat(iterable, is(notNullValue())); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : iterable) { + assertThat(connectionEndpoint, is(equalTo(array[index++]))); + } + + assertThat(index, is(equalTo(2))); + } + } diff --git a/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java b/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java index c52c6f82..d4f9bb0c 100644 --- a/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/PoolNamespaceTest.java @@ -39,8 +39,6 @@ import org.springframework.data.gemfire.test.GemfireTestApplicationContextInitia import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.gemstone.gemfire.cache.client.PoolManager; - /** * @author Costin Leau * @author John Blum @@ -61,10 +59,8 @@ public class PoolNamespaceTest { @Test public void testBasicClient() throws Exception { - assertThat(context.containsBean("DEFAULT"), is(true)); assertThat(context.containsBean("gemfirePool"), is(true)); assertThat(context.containsBean("gemfire-pool"), is(true)); - assertThat(PoolManager.find("DEFAULT"), is(equalTo(context.getBean("gemfirePool")))); PoolFactoryBean poolFactoryBean = context.getBean("&gemfirePool", PoolFactoryBean.class); @@ -82,17 +78,17 @@ public class PoolNamespaceTest { PoolFactoryBean poolFactoryBean = context.getBean("&simple", PoolFactoryBean.class); - ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); - - assertThat(locators, is(notNullValue())); - assertThat(locators.size(), is(equalTo(1))); - - assertConnectionEndpoint(locators.iterator().next(), PoolParser.DEFAULT_HOST, PoolParser.DEFAULT_LOCATOR_PORT); - ConnectionEndpointList servers = TestUtils.readField("servers", poolFactoryBean); assertThat(servers, is(notNullValue())); - assertThat(servers.isEmpty(), is(true)); + assertThat(servers.size(), is(equalTo(1))); + + assertConnectionEndpoint(servers.iterator().next(), PoolParser.DEFAULT_HOST, PoolParser.DEFAULT_SERVER_PORT); + + ConnectionEndpointList locators = TestUtils.readField("locators", poolFactoryBean); + + assertThat(locators, is(notNullValue())); + assertThat(locators.isEmpty(), is(true)); } @Test diff --git a/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java b/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java index a901d4ab..b53d9eb2 100644 --- a/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java +++ b/src/test/java/org/springframework/data/gemfire/config/PoolParserTest.java @@ -17,15 +17,20 @@ package org.springframework.data.gemfire.config; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isA; +import static org.mockito.Matchers.notNull; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -34,14 +39,27 @@ import static org.mockito.Mockito.when; import java.util.List; +import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.beans.factory.config.MethodInvokingBean; +import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.ManagedList; +import org.springframework.beans.factory.xml.ParserContext; import org.springframework.data.gemfire.client.PoolFactoryBean; import org.springframework.data.gemfire.support.ConnectionEndpoint; import org.springframework.data.gemfire.support.ConnectionEndpointList; +import org.springframework.util.StringUtils; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -51,13 +69,30 @@ import org.w3c.dom.NodeList; * * @author John Blum * @see org.junit.Test + * @see org.junit.runner.RunWith + * @see org.mockito.Mock * @see org.mockito.Mockito + * @see org.mockito.runners.MockitoJUnitRunner + * @see org.springframework.data.gemfire.client.PoolFactoryBean * @see org.springframework.data.gemfire.config.PoolParser * @since 1.7.0 */ +@RunWith(MockitoJUnitRunner.class) public class PoolParserTest { - private PoolParser parser = new PoolParser(); + @Mock + private BeanDefinitionRegistry mockRegistry; + + private PoolParser parser; + + @Before + public void setup() { + parser = new PoolParser() { + @Override BeanDefinitionRegistry getRegistry(final ParserContext parserContext) { + return mockRegistry; + } + }; + } protected void assertBeanDefinition(BeanDefinition beanDefinition, String expectedHost, String expectedPort) { assertThat(beanDefinition, is(notNullValue())); @@ -69,6 +104,18 @@ public class PoolParserTest { is(equalTo(expectedPort))); } + protected void assertPropertyValue(PropertyValues propertyValues, String propertyName, Object propertyValue) { + assertThat(propertyValues.getPropertyValue(propertyName).getValue(), is(equalTo(propertyValue))); + } + + protected String generatedBeanName(Class type) { + return generatedBeanName(type.getName()); + } + + protected String generatedBeanName(String beanClassName) { + return String.format("%1$s%2$s%3$d", beanClassName, BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR, 0); + } + @Test @SuppressWarnings("unchecked") public void getBeanClass() { @@ -79,27 +126,46 @@ public class PoolParserTest { @SuppressWarnings("unchecked") public void doParse() { Element mockPoolElement = mock(Element.class, "testDoParse.MockPoolElement"); - Element mockLocatorOneElement = mock(Element.class, "testDoParse.MockLocatorOneElement"); - Element mockLocatorTwoElement = mock(Element.class, "testDoParse.MockLocatorTwoElement"); + Element mockLocatorElementOne = mock(Element.class, "testDoParse.MockLocatorElementOne"); + Element mockLocatorElementTwo = mock(Element.class, "testDoParse.MockLocatorElementTwo"); Element mockServerElement = mock(Element.class, "testDoParse.MockServerElement"); - NodeList mockNodeList = mock(NodeList.class, "testDoParse.MockNodeList"); + NodeList mockNodeList = mock(NodeList.class); + when(mockPoolElement.getAttribute(eq("free-connection-timeout"))).thenReturn("5000"); + when(mockPoolElement.getAttribute(eq("idle-timeout"))).thenReturn("120000"); + when(mockPoolElement.getAttribute(eq("keep-alive"))).thenReturn("true"); + when(mockPoolElement.getAttribute(eq("load-conditioning-interval"))).thenReturn("300000"); + when(mockPoolElement.getAttribute(eq("max-connections"))).thenReturn("500"); + when(mockPoolElement.getAttribute(eq("min-connections"))).thenReturn("50"); + when(mockPoolElement.getAttribute(eq("multi-user-authentication"))).thenReturn("true"); + when(mockPoolElement.getAttribute(eq("ping-interval"))).thenReturn("15000"); + when(mockPoolElement.getAttribute(eq("pr-single-hop-enabled"))).thenReturn("true"); + when(mockPoolElement.getAttribute(eq("read-timeout"))).thenReturn("20000"); + when(mockPoolElement.getAttribute(eq("retry-attempts"))).thenReturn("1"); + when(mockPoolElement.getAttribute(eq("server-group"))).thenReturn("TestGroup"); + when(mockPoolElement.getAttribute(eq("socket-buffer-size"))).thenReturn("16384"); + when(mockPoolElement.getAttribute(eq("statistic-interval"))).thenReturn("500"); + when(mockPoolElement.getAttribute(eq("subscription-ack-interval"))).thenReturn("200"); + when(mockPoolElement.getAttribute(eq("subscription-enabled"))).thenReturn("true"); + when(mockPoolElement.getAttribute(eq("subscription-message-tracking-timeout"))).thenReturn("30000"); + when(mockPoolElement.getAttribute(eq("subscription-redundancy"))).thenReturn("2"); + when(mockPoolElement.getAttribute(eq("thread-local-connections"))).thenReturn("false"); when(mockPoolElement.hasAttribute(PoolParser.LOCATORS_ATTRIBUTE_NAME)).thenReturn(true); when(mockPoolElement.getAttribute(PoolParser.LOCATORS_ATTRIBUTE_NAME)).thenReturn("nebula[1234]"); when(mockPoolElement.hasAttribute(PoolParser.SERVERS_ATTRIBUTE_NAME)).thenReturn(true); when(mockPoolElement.getAttribute(PoolParser.SERVERS_ATTRIBUTE_NAME)).thenReturn("skullbox[9876], backspace"); when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); when(mockNodeList.getLength()).thenReturn(3); - when(mockNodeList.item(eq(0))).thenReturn(mockLocatorOneElement); + when(mockNodeList.item(eq(0))).thenReturn(mockLocatorElementOne); when(mockNodeList.item(eq(1))).thenReturn(mockServerElement); - when(mockNodeList.item(eq(2))).thenReturn(mockLocatorTwoElement); - when(mockLocatorOneElement.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); - when(mockLocatorOneElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("comet"); - when(mockLocatorOneElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("1025"); - when(mockLocatorTwoElement.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); - when(mockLocatorTwoElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("quasar"); - when(mockLocatorTwoElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(" "); + when(mockNodeList.item(eq(2))).thenReturn(mockLocatorElementTwo); + when(mockLocatorElementOne.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); + when(mockLocatorElementOne.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("comet"); + when(mockLocatorElementOne.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("1025"); + when(mockLocatorElementTwo.getLocalName()).thenReturn(PoolParser.LOCATOR_ELEMENT_NAME); + when(mockLocatorElementTwo.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("quasar"); + when(mockLocatorElementTwo.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(" "); when(mockServerElement.getLocalName()).thenReturn(PoolParser.SERVER_ELEMENT_NAME); when(mockServerElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn("rightshift"); when(mockServerElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn("4556"); @@ -107,20 +173,38 @@ public class PoolParserTest { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( parser.getBeanClass(mockPoolElement)); - parser.doParse(mockPoolElement, builder); + parser.doParse(mockPoolElement, null, builder); BeanDefinition poolDefinition = builder.getBeanDefinition(); + assertThat(poolDefinition, is(notNullValue())); + PropertyValues poolPropertyValues = poolDefinition.getPropertyValues(); - assertThat(poolDefinition, is(notNullValue())); - assertThat(poolPropertyValues.contains("locatorEndpoints"), is(true)); - assertThat(poolPropertyValues.contains("locatorEndpointList"), is(false)); - assertThat(poolPropertyValues.contains("serverEndpoints"), is(true)); - assertThat(poolPropertyValues.contains("serverEndpointList"), is(false)); + assertPropertyValue(poolPropertyValues, "freeConnectionTimeout", "5000"); + assertPropertyValue(poolPropertyValues, "idleTimeout", "120000"); + assertPropertyValue(poolPropertyValues, "keepAlive", "true"); + assertPropertyValue(poolPropertyValues, "loadConditioningInterval", "300000"); + assertPropertyValue(poolPropertyValues, "maxConnections", "500"); + assertPropertyValue(poolPropertyValues, "minConnections", "50"); + assertPropertyValue(poolPropertyValues, "multiUserAuthentication", "true"); + assertPropertyValue(poolPropertyValues, "pingInterval", "15000"); + assertPropertyValue(poolPropertyValues, "prSingleHopEnabled", "true"); + assertPropertyValue(poolPropertyValues, "readTimeout", "20000"); + assertPropertyValue(poolPropertyValues, "retryAttempts", "1"); + assertPropertyValue(poolPropertyValues, "serverGroup", "TestGroup"); + assertPropertyValue(poolPropertyValues, "socketBufferSize", "16384"); + assertPropertyValue(poolPropertyValues, "statisticInterval", "500"); + assertPropertyValue(poolPropertyValues, "subscriptionAckInterval", "200"); + assertPropertyValue(poolPropertyValues, "subscriptionEnabled", "true"); + assertPropertyValue(poolPropertyValues, "subscriptionMessageTrackingTimeout", "30000"); + assertPropertyValue(poolPropertyValues, "subscriptionRedundancy", "2"); + assertPropertyValue(poolPropertyValues, "threadLocalConnections", "false"); + assertThat(poolPropertyValues.contains("locators"), is(true)); + assertThat(poolPropertyValues.contains("servers"), is(true)); ManagedList locators = (ManagedList) - poolPropertyValues.getPropertyValue("locatorEndpoints").getValue(); + poolPropertyValues.getPropertyValue("locators").getValue(); assertThat(locators, is(notNullValue())); assertThat(locators.size(), is(equalTo(3))); @@ -129,7 +213,7 @@ public class PoolParserTest { assertBeanDefinition(locators.get(2), "nebula", "1234"); ManagedList servers = (ManagedList) poolDefinition.getPropertyValues() - .getPropertyValue("serverEndpoints").getValue(); + .getPropertyValue("servers").getValue(); assertThat(servers, is(notNullValue())); assertThat(servers.size(), is(equalTo(3))); @@ -137,6 +221,25 @@ public class PoolParserTest { assertBeanDefinition(servers.get(1), "skullbox", "9876"); assertBeanDefinition(servers.get(2), "backspace", String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); + verify(mockPoolElement, times(1)).getAttribute(eq("free-connection-timeout")); + verify(mockPoolElement, times(1)).getAttribute(eq("idle-timeout")); + verify(mockPoolElement, times(1)).getAttribute(eq("keep-alive")); + verify(mockPoolElement, times(1)).getAttribute(eq("load-conditioning-interval")); + verify(mockPoolElement, times(1)).getAttribute(eq("max-connections")); + verify(mockPoolElement, times(1)).getAttribute(eq("min-connections")); + verify(mockPoolElement, times(1)).getAttribute(eq("multi-user-authentication")); + verify(mockPoolElement, times(1)).getAttribute(eq("ping-interval")); + verify(mockPoolElement, times(1)).getAttribute(eq("pr-single-hop-enabled")); + verify(mockPoolElement, times(1)).getAttribute(eq("read-timeout")); + verify(mockPoolElement, times(1)).getAttribute(eq("retry-attempts")); + verify(mockPoolElement, times(1)).getAttribute(eq("server-group")); + verify(mockPoolElement, times(1)).getAttribute(eq("socket-buffer-size")); + verify(mockPoolElement, times(1)).getAttribute(eq("statistic-interval")); + verify(mockPoolElement, times(1)).getAttribute(eq("subscription-ack-interval")); + verify(mockPoolElement, times(1)).getAttribute(eq("subscription-enabled")); + verify(mockPoolElement, times(1)).getAttribute(eq("subscription-message-tracking-timeout")); + verify(mockPoolElement, times(1)).getAttribute(eq("subscription-redundancy")); + verify(mockPoolElement, times(1)).getAttribute(eq("thread-local-connections")); verify(mockPoolElement, times(1)).getChildNodes(); verify(mockNodeList, times(4)).getLength(); verify(mockNodeList, times(1)).item(eq(0)); @@ -146,12 +249,12 @@ public class PoolParserTest { verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); verify(mockPoolElement, never()).hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); - verify(mockLocatorOneElement, times(1)).getLocalName(); - verify(mockLocatorOneElement, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); - verify(mockLocatorOneElement, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); - verify(mockLocatorTwoElement, times(1)).getLocalName(); - verify(mockLocatorTwoElement, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); - verify(mockLocatorTwoElement, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); + verify(mockLocatorElementOne, times(1)).getLocalName(); + verify(mockLocatorElementOne, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); + verify(mockLocatorElementOne, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); + verify(mockLocatorElementTwo, times(1)).getLocalName(); + verify(mockLocatorElementTwo, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); + verify(mockLocatorElementTwo, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); verify(mockServerElement, times(1)).getLocalName(); verify(mockServerElement, times(1)).getAttribute(PoolParser.HOST_ATTRIBUTE_NAME); verify(mockServerElement, times(1)).getAttribute(PoolParser.PORT_ATTRIBUTE_NAME); @@ -160,38 +263,36 @@ public class PoolParserTest { @Test @SuppressWarnings("unchecked") public void doParseWithNoLocatorsOrServersSpecified() { - Element mockPoolElement = mock(Element.class, "testDoParseWithNoLocatorsOrServersSpecified.MockPoolElement"); + Element mockPoolElement = mock(Element.class); + NodeList mockNodeList = mock(NodeList.class); - NodeList mockNodeList = mock(NodeList.class, "testDoParseWithNoLocatorsOrServersSpecified.MockNodeList"); - - when(mockNodeList.getLength()).thenReturn(0); - when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); when(mockPoolElement.hasAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(false); when(mockPoolElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(""); when(mockPoolElement.hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(false); when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(""); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockNodeList.getLength()).thenReturn(0); BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition( parser.getBeanClass(mockPoolElement)); - parser.doParse(mockPoolElement, poolBuilder); + parser.doParse(mockPoolElement, null, poolBuilder); BeanDefinition poolDefinition = poolBuilder.getBeanDefinition(); + assertThat(poolDefinition, is(notNullValue())); + PropertyValues poolPropertyValues = poolDefinition.getPropertyValues(); - assertThat(poolDefinition, is(notNullValue())); - assertThat(poolPropertyValues.contains("locatorEndpoints"), is(true)); - assertThat(poolPropertyValues.contains("locatorEndpointList"), is(false)); - assertThat(poolPropertyValues.contains("serverEndpoints"), is(false)); - assertThat(poolPropertyValues.contains("serverEndpointList"), is(false)); + assertThat(poolPropertyValues.contains("locators"), is(false)); + assertThat(poolPropertyValues.contains("servers"), is(true)); - ManagedList locators = (ManagedList) - poolPropertyValues.getPropertyValue("locatorEndpoints").getValue(); + ManagedList servers = (ManagedList) + poolPropertyValues.getPropertyValue("servers").getValue(); - assertThat(locators, is(notNullValue())); - assertThat(locators.size(), is(equalTo(1))); - assertBeanDefinition(locators.get(0), PoolParser.DEFAULT_HOST, String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)); + assertThat(servers, is(notNullValue())); + assertThat(servers.size(), is(equalTo(1))); + assertBeanDefinition(servers.get(0), PoolParser.DEFAULT_HOST, String.valueOf(PoolParser.DEFAULT_SERVER_PORT)); verify(mockPoolElement, times(1)).getChildNodes(); verify(mockNodeList, times(1)).getLength(); @@ -204,54 +305,88 @@ public class PoolParserTest { @Test public void doParseWithServersAttributeValueSpecifiedAsAPropertyPlaceholder() { - Element mockPoolElement = mock(Element.class, "testDoParseWithServersAttributeValueSpecifiedAsAPropertyPlaceholder.MockPoolElement"); + Element mockPoolElement = mock(Element.class); + NodeList mockNodeList = mock(NodeList.class); - NodeList mockNodeList = mock(NodeList.class, "testDoParseWithServersAttributeValueSpecifiedAsAPropertyPlaceholder.MockNodeList"); - - when(mockNodeList.getLength()).thenReturn(0); - when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockPoolElement.getAttribute(PoolParser.ID_ATTRIBUTE)).thenReturn("TestPool"); when(mockPoolElement.hasAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(false); - when(mockPoolElement.hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(true); when(mockPoolElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn(""); - when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn("${gemfire.server.hosts-and-ports}"); + when(mockPoolElement.hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(true); + when(mockPoolElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn( + "${gemfire.server.hosts-and-ports}"); + when(mockPoolElement.getChildNodes()).thenReturn(mockNodeList); + when(mockNodeList.getLength()).thenReturn(0); BeanDefinitionBuilder poolBuilder = BeanDefinitionBuilder.genericBeanDefinition( parser.getBeanClass(mockPoolElement)); - parser.doParse(mockPoolElement, poolBuilder); + parser.doParse(mockPoolElement, null, poolBuilder); BeanDefinition poolDefinition = poolBuilder.getBeanDefinition(); + assertThat(poolDefinition, is(notNullValue())); + PropertyValues poolPropertyValues = poolDefinition.getPropertyValues(); - assertThat(poolDefinition, is(notNullValue())); - assertThat(poolPropertyValues.contains("locatorEndpoints"), is(false)); - assertThat(poolPropertyValues.contains("locatorEndpointList"), is(false)); - assertThat(poolPropertyValues.contains("serverEndpoints"), is(false)); - assertThat(poolPropertyValues.contains("serverEndpointList"), is(true)); + assertThat(poolPropertyValues.contains("locators"), is(false)); + assertThat(poolPropertyValues.contains("servers"), is(false)); - BeanDefinition servers = (BeanDefinition) poolPropertyValues.getPropertyValue("serverEndpointList").getValue(); + when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false); - assertThat(servers, is(notNullValue())); - assertThat(servers.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); - assertThat(servers.getFactoryMethodName(), is(equalTo("parse"))); - assertThat(servers.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue().toString(), - is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)))); - assertThat(servers.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), - is(equalTo("${gemfire.server.hosts-and-ports}"))); + doAnswer(new Answer() { + @Override public Void answer(final InvocationOnMock invocation) throws Throwable { + String generatedName = invocation.getArgumentAt(0, String.class); + BeanDefinition addServersDefinition = invocation.getArgumentAt(1, BeanDefinition.class); - verify(mockPoolElement, times(1)).getChildNodes(); - verify(mockNodeList, times(1)).getLength(); - verify(mockNodeList, never()).item(anyInt()); + assertThat(StringUtils.hasText(generatedName), is(true)); + assertThat(generatedName, is(equalTo(generatedBeanName(addServersDefinition.getBeanClassName())))); + assertThat(addServersDefinition, is(notNull())); + assertThat(addServersDefinition.getBeanClassName(), is(equalTo(MethodInvokingBean.class.getName()))); + + PropertyValues addServersPropertyValues = addServersDefinition.getPropertyValues(); + + assertThat(addServersPropertyValues, is(notNullValue())); + assertPropertyValue(addServersPropertyValues, "targetObject", new RuntimeBeanReference("&TestPool")); + assertPropertyValue(addServersPropertyValues, "targetMethod", "addServers"); + + Object arguments = addServersPropertyValues.getPropertyValue("arguments").getValue(); + + assertThat(arguments, is(instanceOf(BeanDefinition.class))); + + BeanDefinition argumentsDefinition = (BeanDefinition) arguments; + + assertThat(argumentsDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); + + ConstructorArgumentValues constructorArguments = argumentsDefinition.getConstructorArgumentValues(); + + assertThat(constructorArguments, is(notNullValue())); + assertThat(constructorArguments.getArgumentCount(), is(equalTo(2))); + assertThat((Integer) constructorArguments.getArgumentValue(0, Integer.class).getValue(), + is(equalTo(PoolParser.DEFAULT_SERVER_PORT))); + assertThat(String.valueOf(constructorArguments.getArgumentValue(1, String.class).getValue()), + is(equalTo("${gemfire.server.hosts-and-ports}"))); + + return null; + } + }).when(mockRegistry).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)), + any(BeanDefinition.class)); + + verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE)); verify(mockPoolElement, times(1)).hasAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); verify(mockPoolElement, times(1)).hasAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); verify(mockPoolElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockPoolElement, times(1)).getChildNodes(); + verify(mockNodeList, times(1)).getLength(); + verify(mockNodeList, never()).item(anyInt()); + verify(mockRegistry, times(1)).containsBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class))); + verify(mockRegistry, times(1)).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)), + isA(BeanDefinition.class)); } @Test public void hasAttributesReturnsTrueAndShortcircuts() { - Element mockElement = mock(Element.class, "testHasAttributesIsTrue.MockElement"); + Element mockElement = mock(Element.class); when(mockElement.hasAttribute("attributeOne")).thenReturn(true); when(mockElement.hasAttribute("attributeTwo")).thenReturn(true); @@ -265,7 +400,7 @@ public class PoolParserTest { @Test public void hasAttributesReturnsFalse() { - Element mockElement = mock(Element.class, "testHasAttributesIsTrue.MockElement"); + Element mockElement = mock(Element.class); when(mockElement.hasAttribute(anyString())).thenReturn(false); @@ -283,11 +418,13 @@ public class PoolParserTest { assertThat(beanDefinition, is(notNullValue())); assertThat(beanDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); - assertThat( - beanDefinition.getConstructorArgumentValues().getArgumentValue(0, Integer.class).getValue().toString(), + + ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); + + assertThat(constructorArguments, is(notNullValue())); + assertThat(constructorArguments.getArgumentValue(0, Integer.class).getValue().toString(), is(equalTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)))); - assertThat( - beanDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), + assertThat(constructorArguments.getArgumentValue(1, String.class).getValue().toString(), is(equalTo("${test}"))); } @@ -297,9 +434,13 @@ public class PoolParserTest { assertThat(beanDefinition, is(notNullValue())); assertThat(beanDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); - assertThat(beanDefinition.getConstructorArgumentValues().getArgumentValue(0, Integer.class).getValue().toString(), + + ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues(); + + assertThat(constructorArguments, is(notNullValue())); + assertThat(constructorArguments.getArgumentValue(0, Integer.class).getValue().toString(), is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)))); - assertThat(beanDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), + assertThat(constructorArguments.getArgumentValue(1, String.class).getValue().toString(), is(equalTo("${test}"))); } @@ -406,7 +547,7 @@ public class PoolParserTest { @Test public void parseLocator() { - Element mockElement = mock(Element.class, "testParseLocator.Element"); + Element mockElement = mock(Element.class); when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn("skullbox"); when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn("1234"); @@ -419,7 +560,7 @@ public class PoolParserTest { @Test public void parseLocatorWithNoHostPort() { - Element mockElement = mock(Element.class, "testParseLocatorWithNoHostPort.Element"); + Element mockElement = mock(Element.class); when(mockElement.getAttribute(PoolParser.HOST_ATTRIBUTE_NAME)).thenReturn(""); when(mockElement.getAttribute(PoolParser.PORT_ATTRIBUTE_NAME)).thenReturn(null); @@ -432,12 +573,12 @@ public class PoolParserTest { @Test public void parseLocators() { - Element mockElement = mock(Element.class, "testParseLocators.Element"); + Element mockElement = mock(Element.class); when(mockElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn( "jupiter, saturn[1234], [9876] "); - List locators = parser.parseLocators(mockElement, null); + List locators = parser.parseLocators(mockElement, mockRegistry); assertThat(locators, is(notNullValue())); assertThat(locators.size(), is(equalTo(3))); @@ -450,36 +591,66 @@ public class PoolParserTest { @Test public void parseLocatorsWithPropertyPlaceholder() { - Element mockElement = mock(Element.class, "testParseLocatorsWithPropertyPlaceholder.Element"); + Element mockElement = mock(Element.class); + when(mockElement.getAttribute(eq(PoolParser.ID_ATTRIBUTE))).thenReturn(null); when(mockElement.getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME))).thenReturn( "${gemfire.locators.hosts-and-ports}"); + when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false); - BeanDefinitionBuilder locatorsBuilder = BeanDefinitionBuilder.genericBeanDefinition( - parser.getBeanClass(mockElement)); + doAnswer(new Answer() { + @Override public Void answer(final InvocationOnMock invocation) throws Throwable { + String generatedName = invocation.getArgumentAt(0, String.class); + BeanDefinition addServersDefinition = invocation.getArgumentAt(1, BeanDefinition.class); - List locators = parser.parseLocators(mockElement, locatorsBuilder); + assertThat(StringUtils.hasText(generatedName), is(true)); + assertThat(generatedName, is(equalTo(generatedBeanName(addServersDefinition.getBeanClassName())))); + assertThat(addServersDefinition, is(notNullValue())); + assertThat(addServersDefinition.getBeanClassName(), is(equalTo(MethodInvokingBean.class.getName()))); + + PropertyValues addServersPropertyValues = addServersDefinition.getPropertyValues(); + + assertThat(addServersPropertyValues, is(notNullValue())); + assertPropertyValue(addServersPropertyValues, "targetObject", new RuntimeBeanReference("&gemfirePool")); + assertPropertyValue(addServersPropertyValues, "targetMethod", "addLocators"); + + Object arguments = addServersPropertyValues.getPropertyValue("arguments").getValue(); + + assertThat(arguments, is(instanceOf(BeanDefinition.class))); + + BeanDefinition argumentsDefinition = (BeanDefinition) arguments; + + assertThat(argumentsDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); + + ConstructorArgumentValues constructorArguments = argumentsDefinition.getConstructorArgumentValues(); + + assertThat(constructorArguments, is(notNullValue())); + assertThat(constructorArguments.getArgumentCount(), is(equalTo(2))); + assertThat(String.valueOf(constructorArguments.getArgumentValue(0, Integer.class).getValue()), + is(equalTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)))); + assertThat(String.valueOf(constructorArguments.getArgumentValue(1, String.class).getValue()), + is(equalTo("${gemfire.locators.hosts-and-ports}"))); + + return null; + } + }).when(mockRegistry).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)), + any(BeanDefinition.class)); + + List locators = parser.parseLocators(mockElement, mockRegistry); assertThat(locators, is(notNullValue())); assertThat(locators.isEmpty(), is(true)); - BeanDefinition locatorDefinition = (BeanDefinition) locatorsBuilder.getBeanDefinition() - .getPropertyValues().getPropertyValue("locatorEndpointList").getValue(); - - assertThat(locatorDefinition, is(notNullValue())); - assertThat(locatorDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); - assertThat(locatorDefinition.getFactoryMethodName(), is(equalTo("parse"))); - assertThat(locatorDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue().toString(), - is(equalTo(String.valueOf(PoolParser.DEFAULT_LOCATOR_PORT)))); - assertThat(locatorDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), - is(equalTo("${gemfire.locators.hosts-and-ports}"))); - + verify(mockElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE)); verify(mockElement, times(1)).getAttribute(eq(PoolParser.LOCATORS_ATTRIBUTE_NAME)); + verify(mockRegistry, times(1)).containsBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class))); + verify(mockRegistry, times(1)).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)), + isA(BeanDefinition.class)); } @Test public void parseServer() { - Element mockElement = mock(Element.class, "testParseServer.Element"); + Element mockElement = mock(Element.class); when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn("plato"); when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn("9876"); @@ -492,7 +663,7 @@ public class PoolParserTest { @Test public void parseServerWithNoHostPort() { - Element mockElement = mock(Element.class, "testParseServerWithNoHostPort.Element"); + Element mockElement = mock(Element.class); when(mockElement.getAttribute(eq(PoolParser.HOST_ATTRIBUTE_NAME))).thenReturn(" "); when(mockElement.getAttribute(eq(PoolParser.PORT_ATTRIBUTE_NAME))).thenReturn(""); @@ -505,11 +676,11 @@ public class PoolParserTest { @Test public void parseServers() { - Element mockElement = mock(Element.class, "testParseServers.Element"); + Element mockElement = mock(Element.class); when(mockElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn(" neptune[], venus[9876]"); - List servers = parser.parseServers(mockElement, null); + List servers = parser.parseServers(mockElement, mockRegistry); assertNotNull(servers); assertFalse(servers.isEmpty()); @@ -520,31 +691,61 @@ public class PoolParserTest { @Test public void parseServersWithPropertyPlaceholder() { - Element mockElement = mock(Element.class, "testParseServersWithPropertyPlaceholder.Element"); + Element mockElement = mock(Element.class); + when(mockElement.getAttribute(eq(PoolParser.ID_ATTRIBUTE))).thenReturn(null); when(mockElement.getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME))).thenReturn( "${gemfire.servers.hosts-and-ports}"); + when(mockRegistry.containsBeanDefinition(anyString())).thenReturn(false); - BeanDefinitionBuilder serversBuilder = BeanDefinitionBuilder.genericBeanDefinition( - parser.getBeanClass(mockElement)); + doAnswer(new Answer() { + @Override public Void answer(final InvocationOnMock invocation) throws Throwable { + String generatedName = invocation.getArgumentAt(0, String.class); + BeanDefinition addServersDefinition = invocation.getArgumentAt(1, BeanDefinition.class); - List servers = parser.parseServers(mockElement, serversBuilder); + assertThat(StringUtils.hasText(generatedName), is(true)); + assertThat(generatedName, is(equalTo(generatedBeanName(addServersDefinition.getBeanClassName())))); + assertThat(addServersDefinition, is(notNullValue())); + assertThat(addServersDefinition.getBeanClassName(), is(equalTo(MethodInvokingBean.class.getName()))); + + PropertyValues addServersPropertyValues = addServersDefinition.getPropertyValues(); + + assertThat(addServersPropertyValues, is(notNullValue())); + assertPropertyValue(addServersPropertyValues, "targetObject", new RuntimeBeanReference("&gemfirePool")); + assertPropertyValue(addServersPropertyValues, "targetMethod", "addServers"); + + Object arguments = addServersPropertyValues.getPropertyValue("arguments").getValue(); + + assertThat(arguments, is(instanceOf(BeanDefinition.class))); + + BeanDefinition argumentsDefinition = (BeanDefinition) arguments; + + assertThat(argumentsDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); + + ConstructorArgumentValues constructorArguments = argumentsDefinition.getConstructorArgumentValues(); + + assertThat(constructorArguments, is(notNullValue())); + assertThat(constructorArguments.getArgumentCount(), is(equalTo(2))); + assertThat(String.valueOf(constructorArguments.getArgumentValue(0, Object.class).getValue()), + is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)))); + assertThat(String.valueOf(constructorArguments.getArgumentValue(1, String.class).getValue()), + is(equalTo("${gemfire.servers.hosts-and-ports}"))); + + return null; + } + }).when(mockRegistry).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)), + any(BeanDefinition.class)); + + List servers = parser.parseServers(mockElement, mockRegistry); assertThat(servers, is(notNullValue())); assertThat(servers.isEmpty(), is(true)); - BeanDefinition serverDefinition = (BeanDefinition) serversBuilder.getBeanDefinition() - .getPropertyValues().getPropertyValue("serverEndpointList").getValue(); - - assertThat(serverDefinition, is(notNullValue())); - assertThat(serverDefinition.getBeanClassName(), is(equalTo(ConnectionEndpointList.class.getName()))); - assertThat(serverDefinition.getFactoryMethodName(), is(equalTo("parse"))); - assertThat(serverDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue().toString(), - is(equalTo(String.valueOf(PoolParser.DEFAULT_SERVER_PORT)))); - assertThat(serverDefinition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue().toString(), - is(equalTo("${gemfire.servers.hosts-and-ports}"))); - + verify(mockElement, times(1)).getAttribute(eq(PoolParser.ID_ATTRIBUTE)); verify(mockElement, times(1)).getAttribute(eq(PoolParser.SERVERS_ATTRIBUTE_NAME)); + verify(mockRegistry, times(1)).containsBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class))); + verify(mockRegistry, times(1)).registerBeanDefinition(eq(generatedBeanName(MethodInvokingBean.class)), + isA(BeanDefinition.class)); } } diff --git a/src/test/java/org/springframework/data/gemfire/function/config/FunctionExecutionClientCacheTests.java b/src/test/java/org/springframework/data/gemfire/function/config/FunctionExecutionClientCacheTests.java index d4675ae8..d8aea8df 100644 --- a/src/test/java/org/springframework/data/gemfire/function/config/FunctionExecutionClientCacheTests.java +++ b/src/test/java/org/springframework/data/gemfire/function/config/FunctionExecutionClientCacheTests.java @@ -42,32 +42,34 @@ import com.gemstone.gemfire.distributed.DistributedMember; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestClientCacheConfig.class }) public class FunctionExecutionClientCacheTests { + @Autowired ApplicationContext context; @Test - public void testContextCreated() throws Exception { - + public void contextCreated() throws Exception { ClientCache cache = context.getBean("gemfireCache", ClientCache.class); Pool pool = context.getBean("gemfirePool", Pool.class); + assertEquals("gemfirePool", pool.getName()); + assertTrue(cache.getDefaultPool().getLocators().isEmpty()); assertEquals(1, cache.getDefaultPool().getServers().size()); assertEquals(pool.getServers().get(0), cache.getDefaultPool().getServers().get(0)); - context.getBean("r1", Region.class); + Region region = context.getBean("r1", Region.class); + + assertEquals("gemfirePool", region.getAttributes().getPoolName()); GemfireOnServerFunctionTemplate template = context.getBean(GemfireOnServerFunctionTemplate.class); + assertTrue(template.getResultCollector() instanceof MyResultCollector); } } -@ImportResource("/org/springframework/data/gemfire/function/config/FunctionExecutionCacheClientTests-context.xml") -@EnableGemfireFunctionExecutions(basePackages = "org.springframework.data.gemfire.function.config.three", excludeFilters = { -/*@ComponentScan.Filter(type=FilterType.ANNOTATION, value=OnRegion.class), -@ComponentScan.Filter(type=FilterType.ANNOTATION, value=OnServer.class)*/ -}) @Configuration +@ImportResource("/org/springframework/data/gemfire/function/config/FunctionExecutionCacheClientTests-context.xml") +@EnableGemfireFunctionExecutions(basePackages = "org.springframework.data.gemfire.function.config.three") class TestClientCacheConfig { @Bean MyResultCollector myResultCollector() { @@ -83,8 +85,6 @@ class MyResultCollector implements ResultCollector { */ @Override public void addResult(DistributedMember arg0, Object arg1) { - // TODO Auto-generated method stub - } /* (non-Javadoc) @@ -92,8 +92,6 @@ class MyResultCollector implements ResultCollector { */ @Override public void clearResults() { - // TODO Auto-generated method stub - } /* (non-Javadoc) @@ -101,8 +99,6 @@ class MyResultCollector implements ResultCollector { */ @Override public void endResults() { - // TODO Auto-generated method stub - } /* (non-Javadoc) @@ -110,7 +106,6 @@ class MyResultCollector implements ResultCollector { */ @Override public Object getResult() throws FunctionException { - // TODO Auto-generated method stub return null; } @@ -119,7 +114,6 @@ class MyResultCollector implements ResultCollector { */ @Override public Object getResult(long arg0, TimeUnit arg1) throws FunctionException, InterruptedException { - // TODO Auto-generated method stub return null; } diff --git a/src/test/java/org/springframework/data/gemfire/listener/adapter/ContainerXmlSetupTest.java b/src/test/java/org/springframework/data/gemfire/listener/adapter/ContainerXmlSetupTest.java index 02583be2..560350d0 100644 --- a/src/test/java/org/springframework/data/gemfire/listener/adapter/ContainerXmlSetupTest.java +++ b/src/test/java/org/springframework/data/gemfire/listener/adapter/ContainerXmlSetupTest.java @@ -24,9 +24,13 @@ import static org.junit.Assert.assertTrue; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.springframework.context.support.GenericXmlApplicationContext; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.data.gemfire.ForkUtil; import org.springframework.data.gemfire.listener.ContinuousQueryListenerContainer; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.client.Pool; @@ -36,6 +40,9 @@ import com.gemstone.gemfire.cache.query.CqQuery; * @author Costin Leau * @author John Blum */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/org/springframework/data/gemfire/listener/container.xml") +@SuppressWarnings("unused") public class ContainerXmlSetupTest { @BeforeClass @@ -48,38 +55,32 @@ public class ContainerXmlSetupTest { ForkUtil.sendSignal(); } + @Autowired + private ApplicationContext applicationContext; + @Test - public void testContainerSetup() throws Exception { - GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext( - "/org/springframework/data/gemfire/listener/container.xml"); + public void containerSetup() throws Exception { + ContinuousQueryListenerContainer container = applicationContext.getBean( + ContinuousQueryListenerContainer.class); - try { - ContinuousQueryListenerContainer container = applicationContext.getBean( - ContinuousQueryListenerContainer.class); + assertNotNull(container); + assertTrue(container.isRunning()); - assertNotNull(container); - assertTrue(container.isRunning()); + // test getting container listener by bean ID + ContinuousQueryListenerContainer container2 = applicationContext.getBean("testContainerId", + ContinuousQueryListenerContainer.class); - // test getting container listener by bean ID - ContinuousQueryListenerContainer container2 = applicationContext.getBean("testContainerId", - ContinuousQueryListenerContainer.class); + assertSame(container, container2); - assertSame(container, container2); + Cache cache = applicationContext.getBean("gemfireCache", Cache.class); + Pool pool = applicationContext.getBean("client", Pool.class); - Cache cache = applicationContext.getBean("gemfireCache", Cache.class); - Pool pool = applicationContext.getBean("client", Pool.class); + CqQuery[] cqs = cache.getQueryService().getCqs(); + CqQuery[] poolCqs = pool.getQueryService().getCqs(); - CqQuery[] cqs = cache.getQueryService().getCqs(); - CqQuery[] poolCqs = pool.getQueryService().getCqs(); - - assertTrue(pool.getQueryService().getCq("test-bean-1") != null); - assertEquals(3, cqs.length); - assertEquals(3, poolCqs.length); - } - finally { - ForkUtil.sendSignal(); - applicationContext.close(); - } + assertTrue(pool.getQueryService().getCq("test-bean-1") != null); + assertEquals(3, cqs.length); + assertEquals(3, poolCqs.length); } } diff --git a/src/test/java/org/springframework/data/gemfire/repository/config/RepositoryClientRegionTests.java b/src/test/java/org/springframework/data/gemfire/repository/config/RepositoryClientRegionTests.java index b5eb0bff..741ecc03 100644 --- a/src/test/java/org/springframework/data/gemfire/repository/config/RepositoryClientRegionTests.java +++ b/src/test/java/org/springframework/data/gemfire/repository/config/RepositoryClientRegionTests.java @@ -30,18 +30,20 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author David Turanski - * + * @author John Blum */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class RepositoryClientRegionTests { + @Autowired PersonRepository repository; @BeforeClass public static void startUp() throws Exception { - ForkUtil.startCacheServer(SpringCacheServerProcess.class.getName() + " " - + "/org/springframework/data/gemfire/repository/config/RepositoryClientRegionTests-server-context.xml"); + System.setProperty("gemfire.log-level", "warning"); + ForkUtil.startCacheServer(String.format("%1$s %2$s", SpringCacheServerProcess.class.getName(), + "/org/springframework/data/gemfire/repository/config/RepositoryClientRegionTests-server-context.xml")); } @Test diff --git a/src/test/java/org/springframework/data/gemfire/support/ClientCacheManagerTest.java b/src/test/java/org/springframework/data/gemfire/support/ClientCacheManagerTest.java index 55018ee6..494b0faa 100644 --- a/src/test/java/org/springframework/data/gemfire/support/ClientCacheManagerTest.java +++ b/src/test/java/org/springframework/data/gemfire/support/ClientCacheManagerTest.java @@ -14,36 +14,26 @@ package org.springframework.data.gemfire.support; import static org.junit.Assert.assertNotNull; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.gemfire.ForkUtil; -import org.springframework.data.gemfire.fork.SpringCacheServerProcess; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author David Turanski - * + * @author John Blum */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/org/springframework/data/gemfire/support/cache-manager-client-cache.xml") public class ClientCacheManagerTest { + @Autowired GemfireCacheManager cacheManager; - @BeforeClass - public static void startUp() throws Exception { - ForkUtil.startCacheServer(SpringCacheServerProcess.class.getName() + " " - + "/org/springframework/data/gemfire/client/datasource-server.xml"); - } + @Test - public void test() { - assertNotNull(cacheManager.getCache("r1")); - } - @AfterClass - public static void cleanUp() { - ForkUtil.sendSignal(); + public void cacheManagerUsesConfiguredGemFireRegionAsCache() { + assertNotNull(cacheManager.getCache("Example")); } + } diff --git a/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java index 6eb44ea1..230055b9 100644 --- a/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java +++ b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointListTest.java @@ -16,10 +16,11 @@ package org.springframework.data.gemfire.support; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; import java.net.InetSocketAddress; @@ -36,15 +37,18 @@ import org.junit.rules.ExpectedException; * of the ConnectionEndpointList class. * * @author John Blum + * @see java.net.InetSocketAddress * @see org.junit.Rule * @see org.junit.Test + * @see org.junit.rules.ExpectedException + * @see org.springframework.data.gemfire.support.ConnectionEndpoint * @see org.springframework.data.gemfire.support.ConnectionEndpointList * @since 1.6.3 */ public class ConnectionEndpointListTest { @Rule - public ExpectedException expectedException = ExpectedException.none(); + public ExpectedException exception = ExpectedException.none(); protected ConnectionEndpoint newConnectionEndpoint(String host, int port) { return new ConnectionEndpoint(host, port); @@ -77,6 +81,26 @@ public class ConnectionEndpointListTest { } } + @Test + public void fromConnectionEndpoints() { + ConnectionEndpoint[] connectionEndpoints = { + newConnectionEndpoint("boombox", 10334), + newConnectionEndpoint("skullbox", 40404), + newConnectionEndpoint("toolbox", 1099) + }; + + ConnectionEndpointList list = ConnectionEndpointList.from(connectionEndpoints); + + assertThat(list, is(notNullValue())); + assertThat(list.size(), is(equalTo(connectionEndpoints.length))); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : list) { + assertThat(connectionEndpoint, is(equalTo(connectionEndpoints[index++]))); + } + } + @Test public void fromInetSocketAddresses() { InetSocketAddress[] inetSocketAddresses = { @@ -84,15 +108,14 @@ public class ConnectionEndpointListTest { new InetSocketAddress("localhost", 9876) }; - ConnectionEndpointList connectionEndpoints = ConnectionEndpointList.from(inetSocketAddresses); + ConnectionEndpointList list = ConnectionEndpointList.from(inetSocketAddresses); - assertThat(connectionEndpoints, is(notNullValue())); - assertThat(connectionEndpoints.isEmpty(), is(false)); - assertThat(connectionEndpoints.size(), is(equalTo(2))); + assertThat(list, is(notNullValue())); + assertThat(list.size(), is(equalTo(inetSocketAddresses.length))); int index = 0; - for (ConnectionEndpoint connectionEndpoint : connectionEndpoints) { + for (ConnectionEndpoint connectionEndpoint : list) { assertThat(connectionEndpoint.getHost(), is(equalTo(inetSocketAddresses[index].getHostString()))); assertThat(connectionEndpoint.getPort(), is(equalTo(inetSocketAddresses[index++].getPort()))); } @@ -101,46 +124,44 @@ public class ConnectionEndpointListTest { @Test @SuppressWarnings("unchecked") public void fromIterableInetSocketAddressesIsNullSafe() { - ConnectionEndpointList connectionEndpoints = ConnectionEndpointList.from((Iterable) null); + ConnectionEndpointList list = ConnectionEndpointList.from((Iterable) null); - assertThat(connectionEndpoints, is(notNullValue())); - assertThat(connectionEndpoints.isEmpty(), is(true)); - assertThat(connectionEndpoints.size(), is(equalTo(0))); + assertThat(list, is(notNullValue())); + assertThat(list.isEmpty(), is(true)); } @Test public void parse() { - ConnectionEndpointList connectionEndpoints = ConnectionEndpointList - .parse(24842, "mercury[11235]", "venus", "[12480]", - "[]", "jupiter[]", "saturn[1, 2-Hundred and 34.zero5]", "neptune[four]"); + ConnectionEndpointList list = ConnectionEndpointList.parse(24842, "mercury[11235]", "venus", "[12480]", "[]", + "jupiter[]", "saturn[1, 2-Hundred and 34.zero5]", "neptune[four]"); String[] expectedHostPorts = { "mercury[11235]", "venus[24842]", "localhost[12480]", "localhost[24842]", "jupiter[24842]", "saturn[12345]", "neptune[24842]" }; - assertThat(connectionEndpoints, is(notNullValue())); + assertThat(list, is(notNullValue())); + assertThat(list.size(), is(equalTo(expectedHostPorts.length))); int index = 0; - for (ConnectionEndpoint connectionEndpoint : connectionEndpoints) { + for (ConnectionEndpoint connectionEndpoint : list) { assertThat(connectionEndpoint.toString(), is(equalTo(expectedHostPorts[index++]))); } } @Test public void parseWithEmptyHostsPortsArgument() { - ConnectionEndpointList connectionEndpoints = ConnectionEndpointList.parse(1234); + ConnectionEndpointList list = ConnectionEndpointList.parse(1234); - assertThat(connectionEndpoints, is(notNullValue())); - assertThat(connectionEndpoints.isEmpty(), is(true)); - assertThat(connectionEndpoints.size(), is(equalTo(0))); + assertThat(list, is(notNullValue())); + assertThat(list.isEmpty(), is(true)); } @Test @SuppressWarnings("unchecked") public void addAdditionalConnectionEndpoints() { - ConnectionEndpointList connectionEndpointList = new ConnectionEndpointList(); + ConnectionEndpointList list = new ConnectionEndpointList(); - assertThat(connectionEndpointList.isEmpty(), is(true)); + assertThat(list.isEmpty(), is(true)); ConnectionEndpoint[] connectionEndpointsArray = { newConnectionEndpoint("Mercury", 1111) }; @@ -155,8 +176,8 @@ public class ConnectionEndpointListTest { newConnectionEndpoint("Pluto", 9999) ); - assertThat(connectionEndpointList.add(connectionEndpointsArray).add(connectionEndpointsIterable), - is(sameInstance(connectionEndpointList))); + assertThat(list.add(connectionEndpointsArray).add(connectionEndpointsIterable), + is(sameInstance(list))); List expected = new ArrayList(9); @@ -165,14 +186,14 @@ public class ConnectionEndpointListTest { int index = 0; - for (ConnectionEndpoint connectionEndpoint : connectionEndpointList) { + for (ConnectionEndpoint connectionEndpoint : list) { assertThat(connectionEndpoint, is(equalTo(expected.get(index++)))); } } @Test public void findByHostName() { - ConnectionEndpointList connectionEndpoints = new ConnectionEndpointList( + ConnectionEndpointList list = new ConnectionEndpointList( newConnectionEndpoint("Earth", 10334), newConnectionEndpoint("Earth", 40404), newConnectionEndpoint("Mars", 10334), @@ -181,39 +202,38 @@ public class ConnectionEndpointListTest { newConnectionEndpoint("Neptune", 12345) ); - assertThat(connectionEndpoints.isEmpty(), is(false)); - assertThat(connectionEndpoints.size(), is(equalTo(6))); + assertThat(list.size(), is(equalTo(6))); - ConnectionEndpointList actual = connectionEndpoints.findBy("Earth"); + ConnectionEndpointList result = list.findBy("Earth"); - assertThat(actual, is(notNullValue())); - assertThat(actual.isEmpty(), is(false)); - assertThat(actual.size(), is(equalTo(2))); + assertThat(result, is(notNullValue())); + assertThat(result.size(), is(equalTo(2))); String[] expected = { "Earth[10334]", "Earth[40404]" }; + int index = 0; - for (ConnectionEndpoint connectionEndpoint : actual) { + for (ConnectionEndpoint connectionEndpoint : result) { assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++]))); } - actual = connectionEndpoints.findBy("Saturn"); + result = list.findBy("Saturn"); - assertThat(actual, is(notNullValue())); - assertThat(actual.isEmpty(), is(false)); - assertThat(actual.size(), is(equalTo(1))); - assertThat(actual.iterator().next().toString(), is(equalTo("Saturn[9876]"))); + assertThat(result, is(notNullValue())); + assertThat(result.isEmpty(), is(false)); + assertThat(result.size(), is(equalTo(1))); + assertThat(result.iterator().next().toString(), is(equalTo("Saturn[9876]"))); - actual = connectionEndpoints.findBy("Pluto"); + result = list.findBy("Pluto"); - assertThat(actual, is(notNullValue())); - assertThat(actual.isEmpty(), is(true)); - assertThat(actual.size(), is(equalTo(0))); + assertThat(result, is(notNullValue())); + assertThat(result.isEmpty(), is(true)); + assertThat(result.size(), is(equalTo(0))); } @Test public void findByPortNumber() { - ConnectionEndpointList connectionEndpoints = new ConnectionEndpointList( + ConnectionEndpointList list = new ConnectionEndpointList( newConnectionEndpoint("Earth", 10334), newConnectionEndpoint("Earth", 40404), newConnectionEndpoint("Mars", 10334), @@ -222,42 +242,150 @@ public class ConnectionEndpointListTest { newConnectionEndpoint("Neptune", 12345) ); - assertThat(connectionEndpoints.isEmpty(), is(false)); - assertThat(connectionEndpoints.size(), is(equalTo(6))); + assertThat(list.size(), is(equalTo(6))); - ConnectionEndpointList actual = connectionEndpoints.findBy(10334); + ConnectionEndpointList result = list.findBy(10334); - assertThat(actual, is(notNullValue())); - assertThat(actual.isEmpty(), is(false)); - assertThat(actual.size(), is(equalTo(2))); + assertThat(result, is(notNullValue())); + assertThat(result.size(), is(equalTo(2))); String[] expected = { "Earth[10334]", "Mars[10334]" }; + int index = 0; - for (ConnectionEndpoint connectionEndpoint : actual) { + for (ConnectionEndpoint connectionEndpoint : result) { assertThat(connectionEndpoint.toString(), is(equalTo(expected[index++]))); } - actual = connectionEndpoints.findBy(1234); + result = list.findBy(1234); - assertThat(actual, is(notNullValue())); - assertThat(actual.isEmpty(), is(false)); - assertThat(actual.size(), is(equalTo(1))); - assertThat(actual.iterator().next().toString(), is(equalTo("Jupiter[1234]"))); + assertThat(result, is(notNullValue())); + assertThat(result.size(), is(equalTo(1))); + assertThat(result.iterator().next().toString(), is(equalTo("Jupiter[1234]"))); - actual = connectionEndpoints.findBy(80); + result = list.findBy(80); - assertThat(actual, is(notNullValue())); - assertThat(actual.isEmpty(), is(true)); - assertThat(actual.size(), is(equalTo(0))); + assertThat(result, is(notNullValue())); + assertThat(result.isEmpty(), is(true)); } @Test - public void toStringRepresentation() { - ConnectionEndpointList connectionEndpoints = ConnectionEndpointList.parse(10334, + public void findOneByHostName() { + ConnectionEndpointList list = new ConnectionEndpointList(); + + assertThat(list.findOne("localhost"), is(nullValue())); + + list.add(newConnectionEndpoint("skullbox", 11235)); + + assertThat(list.findOne("localhost"), is(nullValue())); + assertThat(list.findOne("skullbox"), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); + + list.add(newConnectionEndpoint("toolbox", 12480)); + + assertThat(list.findOne("boombox"), is(nullValue())); + assertThat(list.findOne("localhost"), is(nullValue())); + assertThat(list.findOne("skullbox"), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); + assertThat(list.findOne("toolbox"), is(equalTo(newConnectionEndpoint("toolbox", 12480)))); + + list.add(newConnectionEndpoint("skullbox", 10334)); + + assertThat(list.findOne("localhost"), is(nullValue())); + assertThat(list.findOne("boombox"), is(nullValue())); + assertThat(list.findOne("skullbox"), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); + assertThat(list.findOne("toolbox"), is(equalTo(newConnectionEndpoint("toolbox", 12480)))); + } + + @Test + public void findOneByPortNumber() { + ConnectionEndpointList list = new ConnectionEndpointList(); + + assertThat(list.findOne(10334), is(nullValue())); + + list.add(newConnectionEndpoint("skullbox", 11235)); + + assertThat(list.findOne(10334), is(nullValue())); + assertThat(list.findOne(11235), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); + + list.add(newConnectionEndpoint("toolbox", 12480)); + + assertThat(list.findOne(10334), is(nullValue())); + assertThat(list.findOne(40404), is(nullValue())); + assertThat(list.findOne(11235), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); + assertThat(list.findOne(12480), is(equalTo(newConnectionEndpoint("toolbox", 12480)))); + + list.add(newConnectionEndpoint("boombox", 11235)); + + assertThat(list.findOne(10334), is(nullValue())); + assertThat(list.findOne(40404), is(nullValue())); + assertThat(list.findOne(11235), is(equalTo(newConnectionEndpoint("skullbox", 11235)))); + assertThat(list.findOne(12480), is(equalTo(newConnectionEndpoint("toolbox", 12480)))); + } + + @Test + public void toArrayFromList() { + ConnectionEndpointList list = ConnectionEndpointList.from( + newConnectionEndpoint("boombox", 11235), + newConnectionEndpoint("skullbox", 12480), + newConnectionEndpoint("toolbox", 10334)); + + ConnectionEndpoint[] connectionEndpointArray = list.toArray(); + + assertThat(connectionEndpointArray, is(notNullValue())); + assertThat(connectionEndpointArray.length, is(equalTo(list.size()))); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : list) { + assertThat(connectionEndpointArray[index++], is(equalTo(connectionEndpoint))); + } + } + + @Test + public void toArrayFromEmptyList() { + ConnectionEndpoint[] connectionEndpoints = new ConnectionEndpointList().toArray(); + + assertThat(connectionEndpoints, is(notNullValue())); + assertThat(connectionEndpoints.length, is(equalTo(0))); + } + + @Test + public void toInetSocketAddressesFromList() { + ConnectionEndpointList list = ConnectionEndpointList.from( + newConnectionEndpoint("localhost", 10334), + newConnectionEndpoint("localhost", 40404)); + + List socketAddresses = list.toInetSocketAddresses(); + + assertThat(socketAddresses, is(notNullValue())); + assertThat(socketAddresses.size(), is(equalTo(list.size()))); + + int index = 0; + + for (ConnectionEndpoint connectionEndpoint : list) { + assertThat(socketAddresses.get(index).getHostName(), is(equalTo(connectionEndpoint.getHost()))); + assertThat(socketAddresses.get(index++).getPort(), is(equalTo(connectionEndpoint.getPort()))); + } + } + + @Test + public void toInetSocketAddressesFromEmptyList() { + List socketAddresses = new ConnectionEndpointList().toInetSocketAddresses(); + + assertThat(socketAddresses, is(notNullValue())); + assertThat(socketAddresses.isEmpty(), is(true)); + } + + @Test + public void toStringFromList() { + ConnectionEndpointList list = ConnectionEndpointList.parse(10334, "skullbox[12480]", "saturn[ 1 12 3 5]", "neptune"); - assertThat(connectionEndpoints.toString(), is(equalTo("[skullbox[12480], saturn[11235], neptune[10334]]"))); + assertThat(list.toString(), is(equalTo("[skullbox[12480], saturn[11235], neptune[10334]]"))); + } + + @Test + public void toStringFromEmptyList() { + assertThat(new ConnectionEndpointList().toString(), is(equalTo("[]"))); } } diff --git a/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java index 7f57c124..7d91b1dc 100644 --- a/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java +++ b/src/test/java/org/springframework/data/gemfire/support/ConnectionEndpointTest.java @@ -16,10 +16,10 @@ package org.springframework.data.gemfire.support; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.Assert.assertThat; @@ -45,7 +45,7 @@ import org.junit.rules.ExpectedException; public class ConnectionEndpointTest { @Rule - public ExpectedException expectedException = ExpectedException.none(); + public ExpectedException exception = ExpectedException.none(); @Test public void fromInetSocketAddress() { @@ -150,33 +150,33 @@ public class ConnectionEndpointTest { @Test public void parseWithBlankHost() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage("'hostPort' must be specified"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("'hostPort' must be specified"); ConnectionEndpoint.parse(" ", 12345); } @Test public void parseWithEmptyHost() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage("'hostPort' must be specified"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("'hostPort' must be specified"); ConnectionEndpoint.parse("", 12345); } @Test public void parseWithNullHost() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage("'hostPort' must be specified"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("'hostPort' must be specified"); ConnectionEndpoint.parse(null, 12345); } @Test public void parseWithInvalidDefaultPort() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage("port number (-1248) must be between 0 and 65535"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("port number (-1248) must be between 0 and 65535"); ConnectionEndpoint.parse("localhost", -1248); } @@ -217,9 +217,9 @@ public class ConnectionEndpointTest { @Test public void constructConnectionEndpointWithInvalidPort() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectCause(is(nullValue(Throwable.class))); - expectedException.expectMessage("port number (-1) must be between 0 and 65535"); + exception.expect(IllegalArgumentException.class); + exception.expectCause(is(nullValue(Throwable.class))); + exception.expectMessage("port number (-1) must be between 0 and 65535"); new ConnectionEndpoint("localhost", -1); } @@ -253,4 +253,18 @@ public class ConnectionEndpointTest { assertThat(connectionEndpointThree.compareTo(connectionEndpointThree), is(equalTo(0))); } + @Test + public void toInetSocketAddressEqualsHostPort() { + ConnectionEndpoint connectionEndpoint = new ConnectionEndpoint("localhost", 12345); + + assertThat(connectionEndpoint.getHost(), is(equalTo("localhost"))); + assertThat(connectionEndpoint.getPort(), is(equalTo(12345))); + + InetSocketAddress socketAddress = connectionEndpoint.toInetSocketAddress(); + + assertThat(socketAddress, is(notNullValue())); + assertThat(socketAddress.getHostName(), is(equalTo(connectionEndpoint.getHost()))); + assertThat(socketAddress.getPort(), is(equalTo(connectionEndpoint.getPort()))); + } + } diff --git a/src/test/java/org/springframework/data/gemfire/test/GemfireTestBeanPostProcessor.java b/src/test/java/org/springframework/data/gemfire/test/GemfireTestBeanPostProcessor.java index 420a1113..d4339b8b 100644 --- a/src/test/java/org/springframework/data/gemfire/test/GemfireTestBeanPostProcessor.java +++ b/src/test/java/org/springframework/data/gemfire/test/GemfireTestBeanPostProcessor.java @@ -41,7 +41,7 @@ public class GemfireTestBeanPostProcessor implements BeanPostProcessor { ? new MockClientCacheFactoryBean((ClientCacheFactoryBean) bean) : new MockCacheFactoryBean((CacheFactoryBean) bean)); - logger.info(String.format("Replacing the '%1$s' bean definition having type '%2$s' with mock (%3$s)...", + logger.info(String.format("Replacing the [%1$s] bean definition having type [%2$s] with mock [%3$s]...", beanName, beanTypeName, bean.getClass().getName())); } else if (bean instanceof CacheServerFactoryBean) { diff --git a/src/test/java/org/springframework/data/gemfire/test/MockCacheFactoryBean.java b/src/test/java/org/springframework/data/gemfire/test/MockCacheFactoryBean.java index eed5e310..6517e7e3 100644 --- a/src/test/java/org/springframework/data/gemfire/test/MockCacheFactoryBean.java +++ b/src/test/java/org/springframework/data/gemfire/test/MockCacheFactoryBean.java @@ -13,65 +13,59 @@ 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 - * + * @author John Blum */ public class MockCacheFactoryBean extends CacheFactoryBean { public MockCacheFactoryBean() { - this.cache = new StubCache(); - this.useBeanFactoryLocator = false; + this(null); } public MockCacheFactoryBean(CacheFactoryBean cacheFactoryBean) { - this(); + setUseBeanFactoryLocator(false); + if (cacheFactoryBean != null) { this.beanFactoryLocator = cacheFactoryBean.getBeanFactoryLocator(); - this.beanClassLoader = cacheFactoryBean.getBeanClassLoader(); - this.beanFactory = cacheFactoryBean.getBeanFactory(); - this.beanName = cacheFactoryBean.getBeanName(); - this.cacheXml = cacheFactoryBean.getCacheXml(); - this.properties = cacheFactoryBean.getProperties(); - this.copyOnRead = cacheFactoryBean.getCopyOnRead(); - this.criticalHeapPercentage = cacheFactoryBean.getCriticalHeapPercentage(); - this.evictionHeapPercentage = cacheFactoryBean.getEvictionHeapPercentage(); - this.dynamicRegionSupport = cacheFactoryBean.getDynamicRegionSupport(); - this.enableAutoReconnect = cacheFactoryBean.getEnableAutoReconnect(); - 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.pdxReadSerialized = cacheFactoryBean.getPdxReadSerialized(); - this.pdxSerializer = cacheFactoryBean.getPdxSerializer(); - this.searchTimeout = cacheFactoryBean.getSearchTimeout(); - this.transactionListeners = cacheFactoryBean.getTransactionListeners(); - this.transactionWriter = cacheFactoryBean.getTransactionWriter(); + setBeanClassLoader(cacheFactoryBean.getBeanClassLoader()); + setBeanFactory(cacheFactoryBean.getBeanFactory()); + setBeanName(cacheFactoryBean.getBeanName()); + setCacheXml(cacheFactoryBean.getCacheXml()); + setPhase(cacheFactoryBean.getPhase()); + setProperties(cacheFactoryBean.getProperties()); + setClose(cacheFactoryBean.getClose()); + setCopyOnRead(cacheFactoryBean.getCopyOnRead()); + setCriticalHeapPercentage(cacheFactoryBean.getCriticalHeapPercentage()); + setDynamicRegionSupport(cacheFactoryBean.getDynamicRegionSupport()); + setEnableAutoReconnect(cacheFactoryBean.getEnableAutoReconnect()); + setEvictionHeapPercentage(cacheFactoryBean.getEvictionHeapPercentage()); + setGatewayConflictResolver(cacheFactoryBean.getGatewayConflictResolver()); + setJndiDataSources(cacheFactoryBean.getJndiDataSources()); + setLockLease(cacheFactoryBean.getLockLease()); + setLockTimeout(cacheFactoryBean.getLockTimeout()); + setMessageSyncInterval(cacheFactoryBean.getMessageSyncInterval()); + setPdxDiskStoreName(cacheFactoryBean.getPdxDiskStoreName()); + setPdxIgnoreUnreadFields(cacheFactoryBean.getPdxIgnoreUnreadFields()); + setPdxPersistent(cacheFactoryBean.getPdxPersistent()); + setPdxReadSerialized(cacheFactoryBean.getPdxReadSerialized()); + setPdxSerializer(cacheFactoryBean.getPdxSerializer()); + setSearchTimeout(cacheFactoryBean.getSearchTimeout()); + setTransactionListeners(cacheFactoryBean.getTransactionListeners()); + setTransactionWriter(cacheFactoryBean.getTransactionWriter()); } } @Override - protected Object createFactory(Properties gemfireProperties) { - setProperties(gemfireProperties); - return new CacheFactory(gemfireProperties); + @SuppressWarnings("unchecked") + protected T fetchCache() { + StubCache stubCache = new StubCache(); + stubCache.setProperties(getProperties()); + return (T) stubCache; } - @Override - @SuppressWarnings("unchecked") - protected GemFireCache fetchCache() { - ((StubCache) cache).setProperties(getProperties()); - return cache; - } - } diff --git a/src/test/java/org/springframework/data/gemfire/test/MockClientCacheFactoryBean.java b/src/test/java/org/springframework/data/gemfire/test/MockClientCacheFactoryBean.java index cef3f4d6..bf5bf47c 100644 --- a/src/test/java/org/springframework/data/gemfire/test/MockClientCacheFactoryBean.java +++ b/src/test/java/org/springframework/data/gemfire/test/MockClientCacheFactoryBean.java @@ -12,69 +12,57 @@ */ package org.springframework.data.gemfire.test; -import java.util.Properties; - import org.springframework.data.gemfire.client.ClientCacheFactoryBean; import com.gemstone.gemfire.cache.GemFireCache; -import com.gemstone.gemfire.cache.client.ClientCacheFactory; /** * @author David Turanski - * @author Lyndon Adams - * + * @author John Blum */ public class MockClientCacheFactoryBean extends ClientCacheFactoryBean { - - public MockClientCacheFactoryBean() { - this.cache = new StubCache(); - } public MockClientCacheFactoryBean(ClientCacheFactoryBean clientCacheFactoryBean) { - this(); + setUseBeanFactoryLocator(false); if (clientCacheFactoryBean != null) { this.beanFactoryLocator = clientCacheFactoryBean.getBeanFactoryLocator(); - this.beanClassLoader = clientCacheFactoryBean.getBeanClassLoader(); - this.beanFactory = clientCacheFactoryBean.getBeanFactory(); - this.beanName = clientCacheFactoryBean.getBeanName(); - this.cacheXml = clientCacheFactoryBean.getCacheXml(); - this.copyOnRead = clientCacheFactoryBean.getCopyOnRead(); - this.criticalHeapPercentage = clientCacheFactoryBean.getCriticalHeapPercentage(); - this.durableClientId = clientCacheFactoryBean.getDurableClientId(); - this.durableClientTimeout = clientCacheFactoryBean.getDurableClientTimeout(); - this.dynamicRegionSupport = clientCacheFactoryBean.getDynamicRegionSupport(); - this.evictionHeapPercentage = clientCacheFactoryBean.getEvictionHeapPercentage(); - this.gatewayConflictResolver = clientCacheFactoryBean.getGatewayConflictResolver(); - this.jndiDataSources = clientCacheFactoryBean.getJndiDataSources(); - this.keepAlive = clientCacheFactoryBean.isKeepAlive(); - this.lockLease = clientCacheFactoryBean.getLockLease(); - this.lockTimeout = clientCacheFactoryBean.getLockTimeout(); - this.messageSyncInterval = clientCacheFactoryBean.getMessageSyncInterval(); - this.pdxDiskStoreName = clientCacheFactoryBean.getPdxDiskStoreName(); - this.pdxIgnoreUnreadFields = clientCacheFactoryBean.getPdxIgnoreUnreadFields(); - this.pdxPersistent = clientCacheFactoryBean.getPdxPersistent(); - this.pdxReadSerialized = clientCacheFactoryBean.getPdxReadSerialized(); - this.pdxSerializer = clientCacheFactoryBean.getPdxSerializer(); - this.poolName = clientCacheFactoryBean.getPoolName(); - this.properties = clientCacheFactoryBean.getProperties(); - this.readyForEvents = clientCacheFactoryBean.getReadyForEvents(); - this.searchTimeout = clientCacheFactoryBean.getSearchTimeout(); - this.transactionListeners = clientCacheFactoryBean.getTransactionListeners(); - this.transactionWriter = clientCacheFactoryBean.getTransactionWriter(); + setBeanClassLoader(clientCacheFactoryBean.getBeanClassLoader()); + setBeanFactory(clientCacheFactoryBean.getBeanFactory()); + setBeanName(clientCacheFactoryBean.getBeanName()); + setCacheXml(clientCacheFactoryBean.getCacheXml()); + setCopyOnRead(clientCacheFactoryBean.getCopyOnRead()); + setCriticalHeapPercentage(clientCacheFactoryBean.getCriticalHeapPercentage()); + setDurableClientId(clientCacheFactoryBean.getDurableClientId()); + setDurableClientTimeout(clientCacheFactoryBean.getDurableClientTimeout()); + setDynamicRegionSupport(clientCacheFactoryBean.getDynamicRegionSupport()); + setEvictionHeapPercentage(clientCacheFactoryBean.getEvictionHeapPercentage()); + setGatewayConflictResolver(clientCacheFactoryBean.getGatewayConflictResolver()); + setJndiDataSources(clientCacheFactoryBean.getJndiDataSources()); + setKeepAlive(clientCacheFactoryBean.isKeepAlive()); + setLockLease(clientCacheFactoryBean.getLockLease()); + setLockTimeout(clientCacheFactoryBean.getLockTimeout()); + setMessageSyncInterval(clientCacheFactoryBean.getMessageSyncInterval()); + setPdxDiskStoreName(clientCacheFactoryBean.getPdxDiskStoreName()); + setPdxIgnoreUnreadFields(clientCacheFactoryBean.getPdxIgnoreUnreadFields()); + setPdxPersistent(clientCacheFactoryBean.getPdxPersistent()); + setPdxReadSerialized(clientCacheFactoryBean.getPdxReadSerialized()); + setPdxSerializer(clientCacheFactoryBean.getPdxSerializer()); + setPoolName(clientCacheFactoryBean.getPoolName()); + setProperties(clientCacheFactoryBean.getProperties()); + setReadyForEvents(clientCacheFactoryBean.getReadyForEvents()); + setSearchTimeout(clientCacheFactoryBean.getSearchTimeout()); + setTransactionListeners(clientCacheFactoryBean.getTransactionListeners()); + setTransactionWriter(clientCacheFactoryBean.getTransactionWriter()); } } - @Override - protected Object createFactory(Properties gemfireProperties) { - setProperties(gemfireProperties); - return new ClientCacheFactory(gemfireProperties); + @SuppressWarnings("unchecked") + protected T fetchCache() { + StubCache stubCache = new StubCache(); + stubCache.setProperties(getProperties()); + return (T) stubCache; } - @Override - protected GemFireCache fetchCache() { - ((StubCache) cache).setProperties(getProperties()); - return cache; - } } diff --git a/src/test/java/org/springframework/data/gemfire/test/MockClientRegionFactory.java b/src/test/java/org/springframework/data/gemfire/test/MockClientRegionFactory.java index db9cf26f..6197f63e 100644 --- a/src/test/java/org/springframework/data/gemfire/test/MockClientRegionFactory.java +++ b/src/test/java/org/springframework/data/gemfire/test/MockClientRegionFactory.java @@ -27,7 +27,6 @@ import static org.mockito.Mockito.when; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.springframework.data.gemfire.config.GemfireConstants; import org.springframework.util.StringUtils; import com.gemstone.gemfire.cache.CacheListener; @@ -239,7 +238,7 @@ public class MockClientRegionFactory extends MockRegionFactory { new Answer() { @Override public ClientRegionFactory answer(final InvocationOnMock invocation) throws Throwable { String poolName = invocation.getArgumentAt(0, String.class); - poolName = (StringUtils.hasText(poolName) ? poolName : GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME); + poolName = (StringUtils.hasText(poolName) ? poolName : null); attributesFactory.setPoolName(poolName); return mockClientRegionFactory; } diff --git a/src/test/java/org/springframework/data/gemfire/test/StubCache.java b/src/test/java/org/springframework/data/gemfire/test/StubCache.java index 6186a43b..31925123 100644 --- a/src/test/java/org/springframework/data/gemfire/test/StubCache.java +++ b/src/test/java/org/springframework/data/gemfire/test/StubCache.java @@ -163,8 +163,8 @@ public class StubCache implements Cache, ClientCache { public DistributedSystem getDistributedSystem() { if (distributedSystem == null) { distributedSystem = mockDistributedSystem(); - } + return distributedSystem; } @@ -206,7 +206,7 @@ public class StubCache implements Cache, ClientCache { */ @Override public String getName() { - return this.properties == null? null: (String)this.properties.get("name"); + return (this.properties != null ? this.properties.getProperty("name") : null); } /* (non-Javadoc) diff --git a/src/test/resources/org/springframework/data/gemfire/basic-cache.xml b/src/test/resources/org/springframework/data/gemfire/basic-cache.xml index 01ecba1c..bc200cb8 100644 --- a/src/test/resources/org/springframework/data/gemfire/basic-cache.xml +++ b/src/test/resources/org/springframework/data/gemfire/basic-cache.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-lazy-init="true"> - - + + diff --git a/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-context.xml b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-context.xml index 03b24711..f60edbd8 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableLocatorsTest-context.xml @@ -18,7 +18,7 @@ - config + warning diff --git a/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-context.xml b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-context.xml index 39d7bd0c..d7aeed79 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/ClientCacheVariableServersTest-context.xml @@ -11,13 +11,13 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd "> - + localhost[23579],localhost[23654] localhost 24448 - + warning diff --git a/src/test/resources/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-context.xml b/src/test/resources/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-context.xml index 5525f8fa..ef04847e 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-context.xml @@ -14,18 +14,18 @@ "> - localhost - 42082 + localhost + 42084 - + - + - + diff --git a/src/test/resources/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-server-context.xml b/src/test/resources/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-server-context.xml index e5aca411..14b2ab60 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-server-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/GemFireDataSourceIntegrationTest-server-context.xml @@ -11,12 +11,12 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd "> - - localhost - 42082 + + localhost + 42084 - + GemFireDataSourceIntegrationTestServer @@ -26,11 +26,11 @@ - + - + - + diff --git a/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml b/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml index e3880f04..e96a3ee8 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/PoolUsingLocatorsAndServersPropertyPlaceholdersTest-context.xml @@ -11,17 +11,18 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd "> - - - - backspace,jambox[11235],skullbox[12480] + pluto 20668 + backspace,jambox[11235],skullbox[12480] saturn 41414 + boombox[1234],jambox,toolbox[81$81%]* - + + + @@ -33,4 +34,6 @@ + + diff --git a/src/test/resources/org/springframework/data/gemfire/client/client-cache-no-close.xml b/src/test/resources/org/springframework/data/gemfire/client/client-cache-no-close.xml index 95617e52..99b44d59 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/client-cache-no-close.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/client-cache-no-close.xml @@ -13,7 +13,8 @@ warning - - + + + diff --git a/src/test/resources/org/springframework/data/gemfire/client/client-cache-ready-for-events.xml b/src/test/resources/org/springframework/data/gemfire/client/client-cache-ready-for-events.xml deleted file mode 100644 index 0c97851c..00000000 --- a/src/test/resources/org/springframework/data/gemfire/client/client-cache-ready-for-events.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - ClientReadyForEventsTest - 0 - warning - - - - - - - - - - - diff --git a/src/test/resources/org/springframework/data/gemfire/client/client-cache.xml b/src/test/resources/org/springframework/data/gemfire/client/client-cache.xml index 48024c42..302ff952 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/client-cache.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/client-cache.xml @@ -10,15 +10,11 @@ "> - ClientCacheTests - 0 warning - - - - + + diff --git a/src/test/resources/org/springframework/data/gemfire/client/clientcache-with-region-using-cache-loader-writer.xml b/src/test/resources/org/springframework/data/gemfire/client/clientcache-with-region-using-cache-loader-writer.xml index 038adc2e..f16e20b8 100644 --- a/src/test/resources/org/springframework/data/gemfire/client/clientcache-with-region-using-cache-loader-writer.xml +++ b/src/test/resources/org/springframework/data/gemfire/client/clientcache-with-region-using-cache-loader-writer.xml @@ -17,10 +17,6 @@ - - - - diff --git a/src/test/resources/org/springframework/data/gemfire/config/ClientCacheNamespaceTest-context.xml b/src/test/resources/org/springframework/data/gemfire/config/ClientCacheNamespaceTest-context.xml index 6698fa35..c864c09b 100644 --- a/src/test/resources/org/springframework/data/gemfire/config/ClientCacheNamespaceTest-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/config/ClientCacheNamespaceTest-context.xml @@ -12,15 +12,9 @@ - ClientCacheNamespaceTest - 0 warning - - - - - cq-client warning + + - - diff --git a/src/test/resources/org/springframework/data/gemfire/config/client-ns.xml b/src/test/resources/org/springframework/data/gemfire/config/client-ns.xml index 51cd475f..06ebae56 100644 --- a/src/test/resources/org/springframework/data/gemfire/config/client-ns.xml +++ b/src/test/resources/org/springframework/data/gemfire/config/client-ns.xml @@ -21,16 +21,12 @@ + + - ClientRegionNamespaceTest - 0 warning - - - - diff --git a/src/test/resources/org/springframework/data/gemfire/config/pool-ns.xml b/src/test/resources/org/springframework/data/gemfire/config/pool-ns.xml index 8c374f87..ab9be42d 100644 --- a/src/test/resources/org/springframework/data/gemfire/config/pool-ns.xml +++ b/src/test/resources/org/springframework/data/gemfire/config/pool-ns.xml @@ -14,8 +14,6 @@ - PoolNamespaceConfig - 0 warning diff --git a/src/test/resources/org/springframework/data/gemfire/function/ExceptionThrowingFunctionExecutionIntegrationTest-context.xml b/src/test/resources/org/springframework/data/gemfire/function/ExceptionThrowingFunctionExecutionIntegrationTest-context.xml index 820d3ec7..d4dd8704 100644 --- a/src/test/resources/org/springframework/data/gemfire/function/ExceptionThrowingFunctionExecutionIntegrationTest-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/function/ExceptionThrowingFunctionExecutionIntegrationTest-context.xml @@ -12,7 +12,7 @@ "> - config + warning diff --git a/src/test/resources/org/springframework/data/gemfire/function/config/FunctionExecutionCacheClientTests-context.xml b/src/test/resources/org/springframework/data/gemfire/function/config/FunctionExecutionCacheClientTests-context.xml index 48ec0c9e..f721d114 100644 --- a/src/test/resources/org/springframework/data/gemfire/function/config/FunctionExecutionCacheClientTests-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/function/config/FunctionExecutionCacheClientTests-context.xml @@ -1,19 +1,24 @@ + http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd + http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd +"> - - - - - + + warning + + + + + - + + diff --git a/src/test/resources/org/springframework/data/gemfire/function/execution/FunctionIntegrationTests-context.xml b/src/test/resources/org/springframework/data/gemfire/function/execution/FunctionIntegrationTests-context.xml index aa73f33a..cd56cd88 100644 --- a/src/test/resources/org/springframework/data/gemfire/function/execution/FunctionIntegrationTests-context.xml +++ b/src/test/resources/org/springframework/data/gemfire/function/execution/FunctionIntegrationTests-context.xml @@ -1,17 +1,23 @@ + + warning + + - + diff --git a/src/test/resources/org/springframework/data/gemfire/listener/container.xml b/src/test/resources/org/springframework/data/gemfire/listener/container.xml index 31973ba8..7e6a5f7b 100644 --- a/src/test/resources/org/springframework/data/gemfire/listener/container.xml +++ b/src/test/resources/org/springframework/data/gemfire/listener/container.xml @@ -11,13 +11,11 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd "> - - cq-client - 0 + warning - + diff --git a/src/test/resources/org/springframework/data/gemfire/support/cache-manager-client-cache.xml b/src/test/resources/org/springframework/data/gemfire/support/cache-manager-client-cache.xml index a783edfd..30340e3c 100644 --- a/src/test/resources/org/springframework/data/gemfire/support/cache-manager-client-cache.xml +++ b/src/test/resources/org/springframework/data/gemfire/support/cache-manager-client-cache.xml @@ -1,16 +1,24 @@ + xmlns:gfe="http://www.springframework.org/schema/gemfire" + xmlns:util="http://www.springframework.org/schema/util" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd + http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd +"> + + + warning + + + + + - - - - - - \ No newline at end of file + +