SGF-656 - Add EnableCachingDefinedRegions annotation to configure GemFire Regions based on Spring Caching annotations.

(cherry picked from commit a23afdb7e3bc0ed73045bb261836e39bf89ac2ec)
Signed-off-by: John Blum <jblum@pivotal.io>
This commit is contained in:
John Blum
2017-08-01 02:08:20 -07:00
parent f33ffffcba
commit b6ab9103d5
17 changed files with 1587 additions and 95 deletions

View File

@@ -0,0 +1,386 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.config.annotation;
import static java.util.Arrays.stream;
import static org.springframework.data.gemfire.util.ArrayUtils.asArray;
import static org.springframework.data.gemfire.util.ArrayUtils.nullSafeArray;
import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionShortcut;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.MethodMetadata;
import org.springframework.data.gemfire.GemfireUtils;
import org.springframework.data.gemfire.config.annotation.support.BeanDefinitionRegistryPostProcessorSupport;
import org.springframework.data.gemfire.config.annotation.support.GemFireCacheTypeAwareRegionFactoryBean;
import org.springframework.data.gemfire.config.xml.GemfireConstants;
import org.springframework.data.gemfire.util.CollectionUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* The {@link CachingDefinedRegionsConfiguration} class is a Spring {@link Configuration @Configuration} class
* that applies configuration to a Spring (Data GemFire/Geode) application to create GemFire/Geode cache
* {@link Region Regions} based on the use of Spring's Cache Abstraction to enable caching for application
* service classes and methods.
*
* @author John Blum
* @see org.apache.geode.cache.GemFireCache
* @see org.apache.geode.cache.Region
* @see org.springframework.beans.factory.config.BeanDefinition
* @see org.springframework.beans.factory.config.BeanPostProcessor
* @see org.springframework.beans.factory.support.BeanDefinitionBuilder
* @see org.springframework.beans.factory.support.BeanDefinitionRegistry
* @see org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor
* @see org.springframework.cache.annotation.CacheConfig
* @see org.springframework.cache.annotation.CacheEvict
* @see org.springframework.cache.annotation.CachePut
* @see org.springframework.cache.annotation.Cacheable
* @see org.springframework.cache.annotation.Caching
* @see org.springframework.context.annotation.Bean
* @see org.springframework.context.annotation.Configuration
* @see org.springframework.core.annotation.AnnotatedElementUtils
* @see org.springframework.core.annotation.AnnotationUtils
* @see org.springframework.data.gemfire.config.annotation.EnableCachingDefinedRegions
* @see org.springframework.data.gemfire.config.annotation.support.BeanDefinitionRegistryPostProcessorSupport
* @see org.springframework.data.gemfire.config.annotation.support.GemFireCacheTypeAwareRegionFactoryBean
* @since 2.0.0
*/
@Configuration
public class CachingDefinedRegionsConfiguration {
private static final Class[] CLASS_CACHE_ANNOTATION_TYPES;
private static final Class[] METHOD_CACHE_ANNOTATION_TYPES =
asArray(Cacheable.class, CacheEvict.class, CachePut.class);
static {
List<Class> annotationTypes = new ArrayList<>();
Collections.addAll(annotationTypes, METHOD_CACHE_ANNOTATION_TYPES);
annotationTypes.add(CacheConfig.class);
CLASS_CACHE_ANNOTATION_TYPES = annotationTypes.toArray(new Class[annotationTypes.size()]);
}
private static final Set<Integer> INFRASTRUCTURE_ROLES =
asSet(BeanDefinition.ROLE_INFRASTRUCTURE, BeanDefinition.ROLE_SUPPORT);
private static final String ORG_SPRINGFRAMEWORK_DATA_GEMFIRE_PACKAGE = "org.springframework.data.gemfire";
private static final String ORG_SPRINGFRAMEWORK_PACKAGE = "org.springframework";
@Bean
@SuppressWarnings("all")
public BeanDefinitionRegistryPostProcessor cacheAbstractionAnnotationsRegionBeanDefinitionRegistrar() {
return new BeanDefinitionRegistryPostProcessorSupport() {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
registerBeanDefinitions(registry);
}
};
}
@Bean
@SuppressWarnings("all")
public BeanPostProcessor cacheAbstractionAnnotationsRegionBeanRegistrar(ConfigurableBeanFactory beanFactory) {
return new BeanPostProcessor() {
@Nullable @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (isNotInfrastructureBean(bean)) {
registerRegionBeans(collectCacheNames(bean.getClass()), beanFactory);
}
return bean;
}
};
}
void registerBeanDefinitions(BeanDefinitionRegistry registry) {
for (String beanName : registry.getBeanDefinitionNames()) {
BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
if (isNotInfrastructureBean(beanDefinition)) {
resolveBeanClass(beanDefinition, registry).ifPresent(beanClass ->
registerRegionBeanDefinitions(collectCacheNames(beanClass), registry));
}
}
}
private boolean isNotInfrastructureBean(Object bean) {
return isNotInfrastructureClass(bean.getClass().getName());
}
boolean isNotInfrastructureBean(BeanDefinition beanDefinition) {
return (isNotInfrastructureRole(beanDefinition) && isNotInfrastructureClass(beanDefinition));
}
boolean isNotInfrastructureClass(BeanDefinition beanDefinition) {
return resolveBeanClassName(beanDefinition).filter(this::isNotInfrastructureClass).isPresent();
}
boolean isNotInfrastructureClass(String className) {
return (className.startsWith(ORG_SPRINGFRAMEWORK_DATA_GEMFIRE_PACKAGE)
|| !className.startsWith(ORG_SPRINGFRAMEWORK_PACKAGE));
}
boolean isNotInfrastructureRole(BeanDefinition beanDefinition) {
return !INFRASTRUCTURE_ROLES.contains(beanDefinition.getRole());
}
boolean isUserLevelMethod(Method method) {
return Optional.ofNullable(method)
.filter(ClassUtils::isUserLevelMethod)
.filter(it -> !Object.class.equals(it.getDeclaringClass()))
.isPresent();
}
@SuppressWarnings("unchecked")
private Set<String> collectCacheNames(Class<?> type) {
Set<String> cacheNames = new HashSet<>();
cacheNames.addAll(collectCachingCacheNames(type));
cacheNames.addAll(collectCacheNames(type, CLASS_CACHE_ANNOTATION_TYPES));
stream(type.getMethods()).forEach(method -> {
if (isUserLevelMethod(method)) {
cacheNames.addAll(collectCachingCacheNames(method));
cacheNames.addAll(collectCacheNames(method, METHOD_CACHE_ANNOTATION_TYPES));
}
});
return cacheNames;
}
@SuppressWarnings("all")
Set<String> collectCacheNames(AnnotatedElement annotatedElement,
Class<? extends Annotation>... annotationTypes) {
Stream<String> cacheNames = stream(nullSafeArray(annotationTypes, Class.class))
.map(annotationType -> resolveAnnotation(annotatedElement, annotationType))
.flatMap(annotation -> collectCacheNames((Annotation) annotation).stream());
return cacheNames.collect(Collectors.toSet());
}
private Set<String> collectCacheNames(Annotation annotation) {
return Optional.ofNullable(annotation)
.map(AnnotationUtils::getAnnotationAttributes)
.map(annotationAttributes -> (String[]) annotationAttributes.get("cacheNames"))
.map(CollectionUtils::asSet)
.orElse(Collections.emptySet());
}
private Set<String> collectCachingCacheNames(AnnotatedElement annotatedElement) {
Set<String> cacheNames = new HashSet<>();
Optional.ofNullable(resolveAnnotation(annotatedElement, Caching.class))
.ifPresent(caching -> {
cacheNames.addAll(stream(nullSafeArray(caching.cacheable(), Cacheable.class))
.flatMap(cacheable -> collectCacheNames(cacheable).stream())
.collect(Collectors.toSet()));
cacheNames.addAll(stream(nullSafeArray(caching.evict(), CacheEvict.class))
.flatMap(cacheable -> collectCacheNames(cacheable).stream())
.collect(Collectors.toSet()));
cacheNames.addAll(stream(nullSafeArray(caching.put(), CachePut.class))
.flatMap(cacheable -> collectCacheNames(cacheable).stream())
.collect(Collectors.toSet()));
});
return cacheNames;
}
private BeanDefinitionRegistry registerRegionBeanDefinitions(Set<String> cacheNames,
BeanDefinitionRegistry registry) {
boolean containsGemFirePoolBeanDefinition =
registry.containsBeanDefinition(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME);
cacheNames.forEach(cacheName -> {
if (!registry.containsBeanDefinition(cacheName)) {
BeanDefinitionBuilder builder =
BeanDefinitionBuilder.genericBeanDefinition(GemFireCacheTypeAwareRegionFactoryBean.class);
builder.addPropertyReference("cache", GemfireConstants.DEFAULT_GEMFIRE_CACHE_NAME);
if (!containsGemFirePoolBeanDefinition) {
builder.addPropertyValue("poolName", GemfireUtils.DEFAULT_POOL_NAME);
}
builder.addPropertyValue("regionName", cacheName);
builder.addPropertyValue("serverRegionShortcut", RegionShortcut.PARTITION);
registry.registerBeanDefinition(cacheName, builder.getBeanDefinition());
}
});
return registry;
}
private ConfigurableBeanFactory registerRegionBeans(Set<String> cacheNames, ConfigurableBeanFactory beanFactory) {
boolean containsGemFirePoolBean = beanFactory.containsBean(GemfireConstants.DEFAULT_GEMFIRE_POOL_NAME);
cacheNames.forEach(cacheName -> {
if (!beanFactory.containsBean(cacheName)) {
try {
GemFireCacheTypeAwareRegionFactoryBean<?, ?> regionFactoryBean =
new GemFireCacheTypeAwareRegionFactoryBean<>();
regionFactoryBean.setCache(beanFactory.getBean("gemfireCache", GemFireCache.class));
if (!containsGemFirePoolBean) {
regionFactoryBean.setPoolName(GemfireUtils.DEFAULT_POOL_NAME);
}
regionFactoryBean.setRegionName(cacheName);
regionFactoryBean.setServerRegionShortcut(RegionShortcut.PARTITION);
regionFactoryBean.afterPropertiesSet();
Optional.ofNullable(regionFactoryBean.getObject())
.ifPresent(region -> beanFactory.registerSingleton(cacheName, region));
}
catch (Exception cause) {
throw new BeanInstantiationException(Region.class,
String.format("Failed to create Region for cache [%s]", cacheName), cause);
}
}
});
return beanFactory;
}
/* (non-Javadoc) */
<A extends Annotation> A resolveAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType) {
return (annotatedElement instanceof Class
? AnnotatedElementUtils.findMergedAnnotation(annotatedElement, annotationType)
: AnnotationUtils.findAnnotation(annotatedElement, annotationType));
}
/* (non-Javadoc) */
Optional<Class<?>> resolveBeanClass(BeanDefinition beanDefinition, BeanDefinitionRegistry registry) {
return resolveBeanClass(beanDefinition, resolveBeanClassLoader(registry));
}
/* (non-Javadoc) */
private Optional<Class<?>> resolveBeanClass(BeanDefinition beanDefinition, ClassLoader classLoader) {
Class<?> beanClass = (beanDefinition instanceof AbstractBeanDefinition
? safeResolveType(() -> ((AbstractBeanDefinition) beanDefinition).resolveBeanClass(classLoader)) : null);
if (beanClass == null) {
beanClass = resolveBeanClassName(beanDefinition).map(beanClassName ->
safeResolveType(() -> ClassUtils.forName(beanClassName, classLoader))).orElse(null);
}
return Optional.ofNullable(beanClass);
}
/* (non-Javadoc) */
ClassLoader resolveBeanClassLoader(BeanDefinitionRegistry registry) {
return (registry instanceof ConfigurableBeanFactory
? ((ConfigurableBeanFactory) registry).getBeanClassLoader()
: Thread.currentThread().getContextClassLoader());
}
/* (non-Javadoc) */
Optional<String> resolveBeanClassName(BeanDefinition beanDefinition) {
Optional<String> beanClassName =
Optional.ofNullable(beanDefinition.getBeanClassName()).filter(StringUtils::hasText);
if (!beanClassName.isPresent()) {
beanClassName = Optional.of(beanDefinition)
.filter(it -> StringUtils.hasText(it.getFactoryMethodName()))
.filter(it -> it instanceof AnnotatedBeanDefinition)
.map(it -> ((AnnotatedBeanDefinition) it).getFactoryMethodMetadata())
.map(MethodMetadata::getReturnTypeName);
}
return beanClassName;
}
/* (non-Javadoc) */
Class<?> safeResolveType(TypeResolver typeResolver) {
try {
return typeResolver.resolve();
}
catch (ClassNotFoundException cause) {
return null;
}
}
interface TypeResolver {
Class<?> resolve() throws ClassNotFoundException;
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.config.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.geode.cache.Region;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.gemfire.cache.config.EnableGemfireCaching;
/**
* The {@link EnableCachingDefinedRegions} annotation marks a Spring {@link Configuration @Configuration} application
* annotated class to enable the creation of GemFire/Geode {@link Region Regions} based on Spring's Cache Abstraction
* Annotations applied to application service methods and types.
*
* Additionally, this annotation also enable Spring's Cache Abstraction with SDG's {@link EnableGemfireCaching},
* which declares Spring's {@link org.springframework.cache.annotation.EnableCaching} annotation as well as
* declares the SDG {@link org.springframework.data.gemfire.cache.GemfireCacheManager} bean definition.
*
* @author John Blum
* @see java.lang.annotation.Documented
* @see java.lang.annotation.Inherited
* @see java.lang.annotation.Retention
* @see java.lang.annotation.Target
* @see org.apache.geode.cache.Region
* @see org.springframework.context.annotation.Configuration
* @see org.springframework.context.annotation.Import
* @see org.springframework.data.gemfire.cache.config.EnableGemfireCaching
* @since 2.0.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@EnableGemfireCaching
@Import(CachingDefinedRegionsConfiguration.class)
public @interface EnableCachingDefinedRegions {
}

View File

@@ -32,7 +32,7 @@ import org.springframework.core.annotation.AliasFor;
/**
* The {@link EnableEntityDefinedRegions} annotation marks a Spring {@link Configuration @Configuration} application
* annotated class to enable the creation of the GemFire/Geode {@link Region Regions} based on
* annotated class to enable the creation of GemFire/Geode {@link Region Regions} based on
* the application persistent entities.
*
* @author John Blum
@@ -53,7 +53,6 @@ import org.springframework.core.annotation.AliasFor;
@Inherited
@Documented
@Import(IndexConfiguration.class)
@SuppressWarnings({ "unused" })
public @interface EnableEntityDefinedRegions {
/**

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.config.annotation.support;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
/**
* The {@link BeanDefinitionRegistryPostProcessorSupport} is an abstract class supporting the implementation
* of the Spring {@link BeanDefinitionRegistryPostProcessor} interface.
*
* @author John Blum
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory
* @see org.springframework.beans.factory.support.BeanDefinitionRegistry
* @see org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor
* @since 2.0.0
*/
@SuppressWarnings("all")
public abstract class BeanDefinitionRegistryPostProcessorSupport implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}

View File

@@ -16,7 +16,10 @@
package org.springframework.data.gemfire.config.support;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalStateException;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import org.apache.geode.cache.GemFireCache;
@@ -28,20 +31,22 @@ import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* The AutoRegionLookupBeanPostProcessor class is a Spring {@link BeanPostProcessor} that post processes
* a {@link GemFireCache} by registering all cache {@link Region Regions} that have not been explicitly
* defined in the Spring application context. This is usually the case for {@link Region Regions} that
* have been defined in GemFire's native {@literal cache.xml} or defined using GemFire 8's cluster-based
* configuration service.
* The {@link AutoRegionLookupBeanPostProcessor} class is a Spring {@link BeanPostProcessor} that post processes
* a {@link GemFireCache} by registering all cache {@link Region Regions} that have not been explicitly defined
* in the Spring application context.
*
* This is usually the case for {@link Region Regions} that have been defined in GemFire's native {@literal cache.xml}
* or defined using GemFire Cluster-based Configuration Service.
*
* @author John Blum
* @see org.apache.geode.cache.GemFireCache
* @see org.apache.geode.cache.Region
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.beans.factory.BeanFactoryAware
* @see org.springframework.beans.factory.config.BeanPostProcessor
* @see org.apache.geode.cache.GemFireCache
* @see org.apache.geode.cache.Region
* @since 1.5.0
*/
public class AutoRegionLookupBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware {
@@ -52,7 +57,9 @@ public class AutoRegionLookupBeanPostProcessor implements BeanPostProcessor, Bea
* {@inheritDoc}
*/
@Override
@SuppressWarnings("all")
public final void setBeanFactory(BeanFactory beanFactory) throws BeansException {
Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory,
String.format("BeanFactory [%1$s] must be an instance of %2$s",
ObjectUtils.nullSafeClassName(beanFactory), ConfigurableListableBeanFactory.class.getSimpleName()));
@@ -62,16 +69,8 @@ public class AutoRegionLookupBeanPostProcessor implements BeanPostProcessor, Bea
/* (non-Javadoc) */
protected ConfigurableListableBeanFactory getBeanFactory() {
Assert.state(this.beanFactory != null, "BeanFactory was not properly initialized");
return this.beanFactory;
}
/**
* {@inheritDoc}
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
return Optional.ofNullable(this.beanFactory).orElseThrow(() ->
newIllegalStateException("BeanFactory was not properly configured"));
}
/**
@@ -79,6 +78,7 @@ public class AutoRegionLookupBeanPostProcessor implements BeanPostProcessor, Bea
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof GemFireCache) {
registerCacheRegionsAsBeans((GemFireCache) bean);
}
@@ -88,14 +88,14 @@ public class AutoRegionLookupBeanPostProcessor implements BeanPostProcessor, Bea
/* (non-Javadoc) */
void registerCacheRegionsAsBeans(GemFireCache cache) {
for (Region region : cache.rootRegions()) {
registerCacheRegionAsBean(region);
}
cache.rootRegions().forEach(this::registerCacheRegionAsBean);
}
/* (non-Javadoc) */
void registerCacheRegionAsBean(Region<?, ?> region) {
if (region != null) {
String regionBeanName = getBeanName(region);
if (!getBeanFactory().containsBean(regionBeanName)) {
@@ -110,13 +110,15 @@ public class AutoRegionLookupBeanPostProcessor implements BeanPostProcessor, Bea
/* (non-Javadoc) */
String getBeanName(Region region) {
String regionFullPath = region.getFullPath();
return (regionFullPath.lastIndexOf(Region.SEPARATOR) > 0 ? regionFullPath : region.getName());
return Optional.ofNullable(region.getFullPath())
.filter(StringUtils::hasText)
.filter(regionFullPath -> regionFullPath.lastIndexOf(Region.SEPARATOR) > 0)
.orElseGet(region::getName);
}
/* (non-Javadoc) */
Set<Region<?, ?>> nullSafeSubregions(Region<?, ?> parentRegion) {
Set<Region<?, ?>> subregions = parentRegion.subregions(false);
return (subregions != null ? subregions : Collections.<Region<?, ?>>emptySet());
return Optional.ofNullable(parentRegion.subregions(false)).orElse(Collections.emptySet());
}
}

View File

@@ -17,17 +17,21 @@
package org.springframework.data.gemfire.config.support;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
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.client.ClientRegionFactoryBean;
import org.springframework.data.gemfire.client.PoolFactoryBean;
import org.springframework.data.gemfire.util.SpringUtils;
import org.springframework.util.StringUtils;
/**
* {@link ClientRegionPoolBeanFactoryPostProcessor} is a Spring {@link BeanFactoryPostProcessor} implementation
@@ -48,11 +52,14 @@ public class ClientRegionPoolBeanFactoryPostProcessor implements BeanFactoryPost
* {@inheritDoc}
*/
@Override
@SuppressWarnings("all")
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
Set<String> clientRegionBeanNames = new HashSet<String>();
Set<String> poolBeanNames = new HashSet<String>();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
Set<String> clientRegionBeanNames = new HashSet<>();
Set<String> poolBeanNames = new HashSet<>();
Arrays.stream(beanFactory.getBeanDefinitionNames()).forEach(beanName -> {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
if (isClientRegionBean(beanDefinition)) {
@@ -61,26 +68,44 @@ public class ClientRegionPoolBeanFactoryPostProcessor implements BeanFactoryPost
else if (isPoolBean(beanDefinition)) {
poolBeanNames.add(beanName);
}
}
});
clientRegionBeanNames.forEach(clientRegionBeanName -> {
for (String clientRegionBeanName : clientRegionBeanNames) {
BeanDefinition clientRegionBean = beanFactory.getBeanDefinition(clientRegionBeanName);
String poolName = getPoolName(clientRegionBean);
if (poolBeanNames.contains(poolName)) {
SpringUtils.addDependsOn(clientRegionBean, poolName);
}
}
});
}
boolean isBeanDefinitionOfType(BeanDefinition beanDefinition, Class<?> type) {
return Optional.of(beanDefinition)
.map(it -> beanDefinition.getBeanClassName())
.filter(StringUtils::hasText)
.map(beanClassName -> type.getName().equals(beanClassName))
.orElseGet(() ->
Optional.ofNullable(beanDefinition.getFactoryMethodName())
.filter(StringUtils::hasText)
.filter(it -> beanDefinition instanceof AnnotatedBeanDefinition)
.map(it -> ((AnnotatedBeanDefinition) beanDefinition).getFactoryMethodMetadata())
.map(methodMetadata -> type.getName().equals(methodMetadata.getReturnTypeName()))
.orElse(false)
);
}
/* (non-Javadoc)*/
boolean isClientRegionBean(BeanDefinition beanDefinition) {
return ClientRegionFactoryBean.class.getName().equals(beanDefinition.getBeanClassName());
return isBeanDefinitionOfType(beanDefinition, ClientRegionFactoryBean.class);
}
/* (non-Javadoc)*/
boolean isPoolBean(BeanDefinition beanDefinition) {
return PoolFactoryBean.class.getName().equals(beanDefinition.getBeanClassName());
return isBeanDefinitionOfType(beanDefinition, PoolFactoryBean.class);
}
/* (non-Javadoc) */

View File

@@ -56,14 +56,15 @@ import org.springframework.data.gemfire.wan.OrderPolicyConverter;
* @see org.springframework.beans.factory.config.BeanFactoryPostProcessor
* @since 1.6.0
*/
@SuppressWarnings({ "deprecation", "unused" })
public class CustomEditorBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("all")
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerCustomEditor(ConnectionEndpoint.class, StringToConnectionEndpointConverter.class);
//beanFactory.registerCustomEditor(ConnectionEndpoint[].class, ConnectionEndpointArrayToIterableConverter.class);
beanFactory.registerCustomEditor(ConnectionEndpointList.class, StringToConnectionEndpointListConverter.class);
@@ -87,6 +88,7 @@ public class CustomEditorBeanFactoryPostProcessor implements BeanFactoryPostProc
* {@inheritDoc}
*/
@Override
@SuppressWarnings("all")
public Iterable convert(ConnectionEndpoint[] source) {
return ConnectionEndpointList.from(source);
}
@@ -100,6 +102,7 @@ public class CustomEditorBeanFactoryPostProcessor implements BeanFactoryPostProc
* {@inheritDoc}
*/
@Override
@SuppressWarnings("all")
public ConnectionEndpoint convert(String source) {
return assertConverted(source, ConnectionEndpoint.parse(source), ConnectionEndpoint.class);
}
@@ -113,6 +116,7 @@ public class CustomEditorBeanFactoryPostProcessor implements BeanFactoryPostProc
* {@inheritDoc}
*/
@Override
@SuppressWarnings("all")
public ConnectionEndpointList convert(String source) {
return assertConverted(source, ConnectionEndpointList.parse(0, source.split(",")),
ConnectionEndpointList.class);

View File

@@ -16,6 +16,8 @@
package org.springframework.data.gemfire.config.support;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.geode.cache.query.MultiIndexCreationException;
@@ -52,17 +54,19 @@ public class DefinedIndexesApplicationListener implements ApplicationListener<Co
* @see #getQueryService(ContextRefreshedEvent)
*/
@Override
@SuppressWarnings("all")
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
QueryService queryService = getQueryService(event);
if (queryService != null) {
queryService.createDefinedIndexes();
}
}
catch (MultiIndexCreationException ignore) {
logger.warn(String.format("Failed to create pre-defined Indexes: %s", ignore.getMessage()), ignore);
}
Optional.ofNullable(getQueryService(event))
.ifPresent(queryService -> {
try {
queryService.createDefinedIndexes();
}
catch (MultiIndexCreationException cause) {
logger.warn(String.format("Failed to create pre-defined Indexes: %s", cause.getMessage()), cause);
}
});
}
/* (non-Javadoc) */
@@ -72,11 +76,13 @@ public class DefinedIndexesApplicationListener implements ApplicationListener<Co
/* (non-Javadoc) */
private QueryService getQueryService(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
String queryServiceBeanName = getQueryServiceBeanName();
return (applicationContext.containsBean(queryServiceBeanName) ?
applicationContext.getBean(queryServiceBeanName, QueryService.class) : null);
return (applicationContext.containsBean(queryServiceBeanName)
? applicationContext.getBean(queryServiceBeanName, QueryService.class) : null);
}
/* (non-Javadoc) */

View File

@@ -47,6 +47,7 @@ public class DiskStoreDirectoryBeanPostProcessor implements BeanPostProcessor {
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (log.isDebugEnabled()) {
log.debug(String.format("Processing Bean [%1$s] of Type [%2$s] with Name [%3$s] before initialization%n",
bean, ObjectUtils.nullSafeClassName(bean), beanName));
@@ -59,16 +60,9 @@ public class DiskStoreDirectoryBeanPostProcessor implements BeanPostProcessor {
return bean;
}
/**
* {@inheritDoc}
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/* (non-Javadoc) */
private void createIfNotExists(DiskDir diskDirectory) {
String location = readField(diskDirectory, "location");
File diskDirectoryFile = new File(location);
@@ -84,7 +78,9 @@ public class DiskStoreDirectoryBeanPostProcessor implements BeanPostProcessor {
/* (non-Javadoc) */
@SuppressWarnings("unchecked")
private <T> T readField(Object obj, String fieldName) {
try {
Class type = obj.getClass();
Field field;

View File

@@ -0,0 +1,60 @@
/*
* 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.config.support;
/**
* The GemfireFeature enum is an enumeration of features available in Apache Geode and Pivotal GemFire combined.
*
* @author John Blum
* @since 1.7.0
*/
@SuppressWarnings("unused")
public enum GemfireFeature {
AEQ,
BACKUP,
CACHING,
CLIENT_SERVER,
COMPRESSION,
CONFIGURATION,
CONSISTENCY,
CONTINUOUS_QUERY,
DELTA_PROPAGATION,
EVENT_HANDLING,
FUNCTIONS,
HTTP_SESSION_MANAGEMENT,
INDEXING,
JSON,
LOGGING,
MANAGEMENT_MONITORING,
MEMCACHE_SUPPORT,
NETWORK_PARTITIONING,
OFF_HEAP,
PARTITIONING,
PEER_TO_PEER,
PERSISTENCE,
QUERY,
REGISTER_INTEREST,
REPLICATION,
SECURITY,
SERIALIZATION,
STATISTICS,
TRANSACTIONS,
TUNING,
WAN
}

View File

@@ -16,6 +16,10 @@
package org.springframework.data.gemfire.config.support;
import static org.springframework.data.gemfire.util.ArrayUtils.nullSafeArray;
import java.util.Arrays;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.asyncqueue.AsyncEventQueue;
@@ -45,7 +49,7 @@ import org.springframework.util.Assert;
*/
public class PdxDiskStoreAwareBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
protected static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private final String pdxDiskStoreName;
@@ -57,7 +61,7 @@ public class PdxDiskStoreAwareBeanFactoryPostProcessor implements BeanFactoryPos
* @throws IllegalArgumentException if the GemFire PDX {@link DiskStore} name is unspecified.
*/
public PdxDiskStoreAwareBeanFactoryPostProcessor(String pdxDiskStoreName) {
Assert.hasText(pdxDiskStoreName, "The PDX DiskStore name must be specified");
Assert.hasText(pdxDiskStoreName, "PDX DiskStore name is required");
this.pdxDiskStoreName = pdxDiskStoreName;
}
@@ -67,13 +71,14 @@ public class PdxDiskStoreAwareBeanFactoryPostProcessor implements BeanFactoryPos
* @return the name of the GemFire PDX {@link DiskStore}.
*/
public String getPdxDiskStoreName() {
return pdxDiskStoreName;
return this.pdxDiskStoreName;
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("all")
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
postProcessPdxDiskStoreDependencies(beanFactory, AsyncEventQueue.class, DiskStore.class, Region.class);
}
@@ -89,10 +94,13 @@ public class PdxDiskStoreAwareBeanFactoryPostProcessor implements BeanFactoryPos
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanNamesForType(Class)
*/
private void postProcessPdxDiskStoreDependencies(ConfigurableListableBeanFactory beanFactory,
final Class<?>... beanTypes) {
for (Class<?> beanType : beanTypes) {
Class<?>... beanTypes) {
Arrays.stream(nullSafeArray(beanTypes, Class.class)).forEach(beanType -> {
for (String beanName : beanFactory.getBeanNamesForType(beanType)) {
if (!beanName.equalsIgnoreCase(getPdxDiskStoreName())) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
// NOTE for simplicity sake, we add a bean dependency to any bean definition for a bean
@@ -104,7 +112,7 @@ public class PdxDiskStoreAwareBeanFactoryPostProcessor implements BeanFactoryPos
addPdxDiskStoreDependency(beanDefinition);
}
}
}
});
}
/**