SGF-595 - Integrate Spring Data Commons Java 8 support.

(cherry picked from commit d108553870e0d9c169105ac4118bd3163fed6c18)
Signed-off-by: John Blum <jblum@pivotal.io>
This commit is contained in:
John Blum
2017-02-21 09:49:27 -08:00
parent d6c2d0f413
commit 9f52323b69
38 changed files with 672 additions and 564 deletions

View File

@@ -310,11 +310,8 @@ public class GemfireTemplate extends GemfireAccessor implements GemfireOperation
queryString, result));
}
}
catch (IndexInvalidException ex) {
throw convertGemFireQueryException(ex);
}
catch (QueryInvalidException ex) {
throw convertGemFireQueryException(ex);
catch (IndexInvalidException | QueryInvalidException e) {
throw convertGemFireQueryException(e);
}
catch (GemFireCheckedException e) {
throw convertGemFireAccessException(e);
@@ -322,14 +319,14 @@ public class GemfireTemplate extends GemfireAccessor implements GemfireOperation
catch (GemFireException e) {
throw convertGemFireAccessException(e);
}
catch (RuntimeException ex) {
catch (RuntimeException e) {
// test for CqInvalidException (removed in 6.5)
if (GemfireCacheUtils.isCqInvalidException(ex)) {
throw GemfireCacheUtils.convertCqInvalidException(ex);
if (GemfireCacheUtils.isCqInvalidException(e)) {
throw GemfireCacheUtils.convertCqInvalidException(e);
}
// callback code threw application exception
throw ex;
throw e;
}
}

View File

@@ -65,6 +65,7 @@ import org.springframework.data.gemfire.config.annotation.support.GemFireCompone
import org.springframework.data.gemfire.config.xml.GemfireConstants;
import org.springframework.data.gemfire.mapping.GemfireMappingContext;
import org.springframework.data.gemfire.mapping.GemfirePersistentEntity;
import org.springframework.data.gemfire.mapping.GemfirePersistentProperty;
import org.springframework.data.gemfire.mapping.annotation.ClientRegion;
import org.springframework.data.gemfire.mapping.annotation.LocalRegion;
import org.springframework.data.gemfire.mapping.annotation.PartitionRegion;
@@ -230,7 +231,9 @@ public class EntityDefinedRegionsConfiguration
/* (non-Javadoc) */
protected GemfirePersistentEntity<?> getPersistentEntity(Class<?> persistentEntityType) {
return resolveMappingContext().getPersistentEntity(persistentEntityType);
return resolveMappingContext().getPersistentEntity(persistentEntityType).orElseThrow(
() -> new IllegalStateException(String.format("PersistentEntity for type [%s] not found",
persistentEntityType)));
}
/* (non-Javadoc) */
@@ -484,14 +487,15 @@ public class EntityDefinedRegionsConfiguration
/* (non-Javadoc) */
protected Class<?> resolveDomainType(GemfirePersistentEntity persistentEntity) {
return Optional.ofNullable(persistentEntity.getType()).orElse(Object.class);
return Optional.of(persistentEntity.getType()).orElse(Object.class);
}
/* (non-Javadoc) */
@SuppressWarnings("unchecked")
protected Class<?> resolveIdType(GemfirePersistentEntity persistentEntity) {
return (persistentEntity.hasIdProperty()
? Optional.ofNullable(persistentEntity.getIdProperty().getActualType()).orElse(Object.class)
: Object.class);
return (Class<?>) persistentEntity.getIdProperty()
.map(idProperty -> ((GemfirePersistentProperty) idProperty).getActualType())
.orElse(Object.class);
}
/* (non-Javadoc) */

View File

@@ -116,22 +116,29 @@ public class IndexConfiguration extends EntityDefinedRegionsConfiguration {
GemfirePersistentEntity<?> localPersistentEntity =
super.postProcess(importingClassMetadata, registry, persistentEntity);
if (isAnnotationPresent(importingClassMetadata, getEnableIndexingAnnotationTypeName())) {
AnnotationAttributes enableIndexingAttributes =
getAnnotationAttributes(importingClassMetadata, getEnableIndexingAnnotationTypeName());
localPersistentEntity.doWithProperties((PropertyHandler<GemfirePersistentProperty>) persistentProperty -> {
Optional.ofNullable(persistentProperty.findAnnotation(Id.class)).ifPresent(idAnnotation ->
registerIndexBeanDefinition(enableIndexingAttributes, localPersistentEntity, persistentProperty,
IndexType.KEY, idAnnotation, registry));
Optional<Id> idAnnotation = persistentProperty.findAnnotation(Id.class);
Optional.ofNullable(persistentProperty.findAnnotation(Indexed.class)).ifPresent(indexedAnnotation ->
idAnnotation.ifPresent(id ->
registerIndexBeanDefinition(enableIndexingAttributes, localPersistentEntity, persistentProperty,
indexedAnnotation.type(), indexedAnnotation, registry));
IndexType.KEY, id, registry));
Optional.ofNullable(persistentProperty.findAnnotation(LuceneIndexed.class)).ifPresent(
luceneIndexAnnotation -> registerLuceneIndexBeanDefinition(enableIndexingAttributes,
localPersistentEntity, persistentProperty, luceneIndexAnnotation, registry));
Optional<Indexed> indexedAnnotation = persistentProperty.findAnnotation(Indexed.class);
indexedAnnotation.ifPresent(indexed ->
registerIndexBeanDefinition(enableIndexingAttributes, localPersistentEntity, persistentProperty,
indexed.type(), indexed, registry));
Optional<LuceneIndexed> luceneIndexedAnnotation = persistentProperty.findAnnotation(LuceneIndexed.class);
luceneIndexedAnnotation.ifPresent(luceneIndexed ->
registerLuceneIndexBeanDefinition(enableIndexingAttributes, localPersistentEntity,
persistentProperty, luceneIndexed, registry));
});
}

View File

@@ -21,6 +21,8 @@ import java.lang.reflect.Field;
import org.springframework.data.gemfire.mapping.model.GemfireSimpleTypeHolder;
import org.springframework.data.mapping.context.AbstractMappingContext;
import org.springframework.data.mapping.model.MutablePersistentEntity;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.TypeInformation;
@@ -57,9 +59,19 @@ public class GemfireMappingContext extends AbstractMappingContext<GemfirePersist
/**
* @inheritDoc
* @see org.springframework.data.mapping.context.AbstractMappingContext#createPersistentProperty(java.lang.reflect.Field, java.beans.PropertyDescriptor, org.springframework.data.mapping.model.MutablePersistentEntity, org.springframework.data.mapping.model.SimpleTypeHolder)
* @see org.springframework.data.mapping.context.AbstractMappingContext#createPersistentProperty(Property, MutablePersistentEntity, SimpleTypeHolder)
*/
@Override
protected GemfirePersistentProperty createPersistentProperty(Property property, GemfirePersistentEntity<?> owner,
SimpleTypeHolder simpleTypeHolder) {
return new GemfirePersistentProperty(property, owner, simpleTypeHolder);
}
/**
* @deprecated use {@link #createPersistentProperty(Property, GemfirePersistentEntity, SimpleTypeHolder)} instead
*/
@Deprecated
protected GemfirePersistentProperty createPersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
GemfirePersistentEntity<?> owner, SimpleTypeHolder simpleTypeHolder) {

View File

@@ -19,6 +19,7 @@ package org.springframework.data.gemfire.mapping;
import static org.springframework.data.gemfire.util.SpringUtils.defaultIfEmpty;
import java.lang.annotation.Annotation;
import java.util.Optional;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;
@@ -49,7 +50,6 @@ public class GemfirePersistentEntity<T> extends BasicPersistentEntity<T, Gemfire
/* (non-Javadoc) */
protected static Annotation resolveRegionAnnotation(Class<?> persistentEntityType) {
for (Class<? extends Annotation> regionAnnotationType : Region.REGION_ANNOTATION_TYPES) {
Annotation regionAnnotation = AnnotatedElementUtils.getMergedAnnotation(
persistentEntityType, regionAnnotationType);
@@ -64,9 +64,9 @@ public class GemfirePersistentEntity<T> extends BasicPersistentEntity<T, Gemfire
/* (non-Javadoc) */
protected static String resolveRegionName(Class<?> persistentEntityType, Annotation regionAnnotation) {
String regionName = (regionAnnotation != null
? getAnnotationAttributeStringValue(regionAnnotation, "value") : null);
String regionName = Optional.ofNullable(regionAnnotation)
.map((annotation) -> getAnnotationAttributeStringValue(annotation, "value"))
.orElse(null);
return defaultIfEmpty(regionName, persistentEntityType.getSimpleName());
}
@@ -123,8 +123,9 @@ public class GemfirePersistentEntity<T> extends BasicPersistentEntity<T, Gemfire
* @see #getRegionAnnotation()
*/
public Class<? extends Annotation> getRegionAnnotationType() {
Annotation regionAnnotation = getRegionAnnotation();
return (regionAnnotation != null ? regionAnnotation.annotationType() : null);
return Optional.ofNullable(getRegionAnnotation())
.map((annotation) -> ((Annotation) annotation).annotationType())
.orElse(null);
}
/**
@@ -148,15 +149,17 @@ public class GemfirePersistentEntity<T> extends BasicPersistentEntity<T, Gemfire
GemfirePersistentProperty property) {
if (property.isIdProperty()) {
if (hasIdProperty()) {
GemfirePersistentProperty currentIdProperty = getIdProperty();
Optional<GemfirePersistentProperty> optionalIdProperty = getIdProperty();
if (currentIdProperty.isExplicitIdProperty()) {
if (optionalIdProperty.isPresent()) {
GemfirePersistentProperty idProperty = getIdProperty().get();
if (idProperty.isExplicitIdProperty()) {
if (property.isExplicitIdProperty()) {
throw new MappingException(String.format(
"Attempt to add explicit id property [%1$s] but already have id property [%2$s] registered as explicit;"
+ " Please check your object [%3$s] mapping configuration",
property.getName(), currentIdProperty.getName(), getType().getName()));
property.getName(), idProperty.getName(), getType().getName()));
}
return null;

View File

@@ -20,6 +20,7 @@ import static org.springframework.data.gemfire.util.CollectionUtils.asSet;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.Optional;
import java.util.Set;
import org.springframework.data.annotation.Id;
@@ -28,6 +29,7 @@ import org.springframework.data.mapping.Association;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
/**
@@ -39,6 +41,13 @@ public class GemfirePersistentProperty extends AnnotationBasedPersistentProperty
protected static final Set<String> SUPPORTED_IDENTIFIER_NAMES = asSet("id");
/* (non-Javadoc) */
private static Property newProperty(Field field, PropertyDescriptor propertyDescriptor) {
return Optional.ofNullable(field)
.map((theField) -> Property.of(theField, Optional.ofNullable(propertyDescriptor)))
.orElseGet(() -> Property.of(propertyDescriptor));
}
/* (non-Javadoc) */
private static SimpleTypeHolder resolveSimpleTypeHolder(SimpleTypeHolder source) {
return (source instanceof GemfireSimpleTypeHolder ? source
@@ -46,22 +55,45 @@ public class GemfirePersistentProperty extends AnnotationBasedPersistentProperty
}
/**
* Constructs an instance of the {@link GemfirePersistentProperty} initialized with entity
* persistent property information (meta-data).
* Constructs an instance of {@link GemfirePersistentProperty} initialized with entity persistent property
* information (meta-data).
*
* @param field entity {@link Field} corresponding to the persistent property.
* @param propertyDescriptor {@link PropertyDescriptor} for the entity's persistent property.
* @param owner entity owning the persistent property.
* @param field {@link GemfirePersistentEntity entity} {@link Field} for the persistent property.
* @param propertyDescriptor {@link PropertyDescriptor} for the {@link GemfirePersistentEntity entity's}
* persistent property.
* @param owner {@link GemfirePersistentEntity entity} owning the persistent property.
* @param simpleTypeHolder {@link SimpleTypeHolder} used to handle primitive types.
* @see org.springframework.data.mapping.model.SimpleTypeHolder
* @see #GemfirePersistentProperty(Property, PersistentEntity, SimpleTypeHolder)
* @see #newProperty(Field, PropertyDescriptor)
* @see org.springframework.data.mapping.PersistentEntity
* @see org.springframework.data.mapping.PersistentProperty
* @see org.springframework.data.mapping.model.SimpleTypeHolder
* @see java.beans.PropertyDescriptor
* @see java.lang.reflect.Field
*/
public GemfirePersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
PersistentEntity<?, GemfirePersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
super(field, propertyDescriptor, owner, resolveSimpleTypeHolder(simpleTypeHolder));
this(newProperty(field, propertyDescriptor), owner, resolveSimpleTypeHolder(simpleTypeHolder));
}
/**
* Constructs an instance of {@link GemfirePersistentProperty} initialized with entity persistent property
* information (meta-data).
*
* @param property {@link Property} representing the {@link GemfirePersistentEntity entity's} persistent property.
* @param owner {@link GemfirePersistentEntity entity} owning the persistent property.
* @param simpleTypeHolder {@link SimpleTypeHolder} used to handle primitive types.
* @see org.springframework.data.mapping.PersistentEntity
* @see org.springframework.data.mapping.PersistentProperty
* @see org.springframework.data.mapping.model.Property
* @see org.springframework.data.mapping.model.SimpleTypeHolder
* @see AnnotationBasedPersistentProperty(Property, PersistentEntity, SimpleTypeHolder)
*/
public GemfirePersistentProperty(Property property, PersistentEntity<?, GemfirePersistentProperty> owner,
SimpleTypeHolder simpleTypeHolder) {
super(property, owner, simpleTypeHolder);
}
/**
@@ -99,6 +131,6 @@ public class GemfirePersistentProperty extends AnnotationBasedPersistentProperty
*/
@Override
public boolean usePropertyAccess() {
return (super.usePropertyAccess() || (getField() == null && this.propertyDescriptor != null));
return (super.usePropertyAccess() || !getProperty().isFieldBacked());
}
}

View File

@@ -13,17 +13,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.mapping;
import java.util.Optional;
import org.apache.geode.pdx.PdxReader;
import org.springframework.data.mapping.model.PropertyValueProvider;
import org.springframework.util.Assert;
/**
* {@link PropertyValueProvider} to read property values from a {@link PdxReader}.
* {@link PropertyValueProvider} to read property values from {@link PdxReader}.
*
* @author Oliver Gierke
* @author David Turanski
* @author John Blum
*/
class GemfirePropertyValueProvider implements PropertyValueProvider<GemfirePersistentProperty> {
@@ -35,7 +39,7 @@ class GemfirePropertyValueProvider implements PropertyValueProvider<GemfirePersi
* @param reader must not be {@literal null}.
*/
public GemfirePropertyValueProvider(PdxReader reader) {
Assert.notNull(reader);
Assert.notNull(reader, "PdxReader must not be null");
this.reader = reader;
}
@@ -45,7 +49,7 @@ class GemfirePropertyValueProvider implements PropertyValueProvider<GemfirePersi
*/
@Override
@SuppressWarnings("unchecked")
public <T> T getPropertyValue(GemfirePersistentProperty property) {
return (T) reader.readField(property.getName());
public <T> Optional<T> getPropertyValue(GemfirePersistentProperty property) {
return Optional.ofNullable((T) reader.readField(property.getName()));
}
}

View File

@@ -15,8 +15,11 @@
*/
package org.springframework.data.gemfire.mapping;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalArgumentException;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -115,8 +118,8 @@ public class MappingPdxSerializer implements PdxSerializer, ApplicationContextAw
*/
public MappingPdxSerializer(GemfireMappingContext mappingContext, ConversionService conversionService) {
Assert.notNull(mappingContext);
Assert.notNull(conversionService);
Assert.notNull(mappingContext, "GemfireMappingContext must not be null");
Assert.notNull(conversionService, "ConversionService must not be null");
this.mappingContext = mappingContext;
this.conversionService = conversionService;
@@ -130,7 +133,7 @@ public class MappingPdxSerializer implements PdxSerializer, ApplicationContextAw
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = new SpELContext(context, applicationContext);
this.context = new SpELContext(this.context, applicationContext);
}
/* (non-Javadoc) */
@@ -144,7 +147,7 @@ public class MappingPdxSerializer implements PdxSerializer, ApplicationContextAw
* @param customSerializers a mapping of domain object class types and their corresponding PDX serializer.
*/
public void setCustomSerializers(Map<Class<?>, PdxSerializer> customSerializers) {
Assert.notNull(customSerializers);
Assert.notNull(customSerializers, "Custom PdxSerializers must not be null");
this.customSerializers = customSerializers;
}
@@ -159,7 +162,7 @@ public class MappingPdxSerializer implements PdxSerializer, ApplicationContextAw
* @param gemfireInstantiators must not be {@literal null}.
*/
public void setGemfireInstantiators(Map<Class<?>, EntityInstantiator> gemfireInstantiators) {
Assert.notNull(gemfireInstantiators);
Assert.notNull(gemfireInstantiators, "EntityInstantiators must not be null");
this.instantiators = new EntityInstantiators(gemfireInstantiators);
}
@@ -177,46 +180,45 @@ public class MappingPdxSerializer implements PdxSerializer, ApplicationContextAw
* {@inheritDoc}
*/
@Override
public Object fromData(final Class<?> type, final PdxReader reader) {
public Object fromData(Class<?> type, PdxReader reader) {
final GemfirePersistentEntity<?> entity = getPersistentEntity(type);
GemfirePersistentEntity<?> entity = getPersistentEntity(type);
final Object instance = getInstantiatorFor(entity).createInstance(entity,
new PersistentEntityParameterValueProvider<>(entity, new GemfirePropertyValueProvider(reader), null));
Object instance = getInstantiatorFor(entity).createInstance(entity,
new PersistentEntityParameterValueProvider<>(entity, new GemfirePropertyValueProvider(reader),
Optional.empty()));
final PersistentPropertyAccessor propertyAccessor =
PersistentPropertyAccessor propertyAccessor =
new ConvertingPropertyAccessor(entity.getPropertyAccessor(instance), getConversionService());
entity.doWithProperties(new PropertyHandler<GemfirePersistentProperty>() {
public void doWithPersistentProperty(GemfirePersistentProperty persistentProperty) {
if (!entity.isConstructorArgument(persistentProperty)) {
PdxSerializer customSerializer = getCustomSerializer(persistentProperty.getType());
entity.doWithProperties((PropertyHandler<GemfirePersistentProperty>) persistentProperty -> {
if (!entity.isConstructorArgument(persistentProperty)) {
PdxSerializer customSerializer = getCustomSerializer(persistentProperty.getType());
Object value = null;
Object value = null;
try {
if (log.isDebugEnabled()) {
log.debug(String.format("setting property [%1$s] for entity [%2$s] of type [%3$s] from PDX%4$s",
persistentProperty.getName(), instance, type, (customSerializer != null ?
String.format(" using custom PdxSerializer [%1$s]", customSerializer) : "")));
}
value = (customSerializer != null
? customSerializer.fromData(persistentProperty.getType(), reader)
: reader.readField(persistentProperty.getName()));
if (log.isDebugEnabled()) {
log.debug(String.format("with value [%1$s]", value));
}
propertyAccessor.setProperty(persistentProperty, value);
try {
if (log.isDebugEnabled()) {
log.debug(String.format("setting property [%1$s] for entity [%2$s] of type [%3$s] from PDX%4$s",
persistentProperty.getName(), instance, type, (customSerializer != null ?
String.format(" using custom PdxSerializer [%1$s]", customSerializer) : "")));
}
catch (Exception e) {
throw new MappingException(String.format(
"while setting value [%1$s] of property [%2$s] for entity of type [%3$s] from PDX%4$s",
value, persistentProperty.getName(), type, (customSerializer != null ?
String.format(" using custom PdxSerializer [%14s]", customSerializer) : "")), e);
value = (customSerializer != null
? customSerializer.fromData(persistentProperty.getType(), reader)
: reader.readField(persistentProperty.getName()));
if (log.isDebugEnabled()) {
log.debug(String.format("with value [%1$s]", value));
}
propertyAccessor.setProperty(persistentProperty, Optional.ofNullable(value));
}
catch (Exception e) {
throw new MappingException(String.format(
"While setting value [%1$s] of property [%2$s] for entity of type [%3$s] from PDX%4$s",
value, persistentProperty.getName(), type, (customSerializer != null ?
String.format(" using custom PdxSerializer [%14s]", customSerializer) : "")), e);
}
}
});
@@ -228,52 +230,51 @@ public class MappingPdxSerializer implements PdxSerializer, ApplicationContextAw
* {@inheritDoc}
*/
@Override
public boolean toData(final Object value, final PdxWriter writer) {
@SuppressWarnings("unchecked")
public boolean toData(Object value, PdxWriter writer) {
GemfirePersistentEntity<?> entity = getPersistentEntity(value);
final PersistentPropertyAccessor propertyAccessor =
PersistentPropertyAccessor propertyAccessor =
new ConvertingPropertyAccessor(entity.getPropertyAccessor(value), getConversionService());
entity.doWithProperties(new PropertyHandler<GemfirePersistentProperty>() {
@Override @SuppressWarnings("unchecked")
public void doWithPersistentProperty(GemfirePersistentProperty persistentProperty) {
PdxSerializer customSerializer = getCustomSerializer(persistentProperty.getType());
entity.doWithProperties((PropertyHandler<GemfirePersistentProperty>) persistentProperty -> {
PdxSerializer customSerializer = getCustomSerializer(persistentProperty.getType());
Object propertyValue = null;
Optional<Object> propertyValue = null;
try {
propertyValue = propertyAccessor.getProperty(persistentProperty);
try {
propertyValue = propertyAccessor.getProperty(persistentProperty);
if (log.isDebugEnabled()) {
log.debug(String.format("Serializing entity property [%1$s] value [%2$s] of type [%3$s] to PDX%4$s",
persistentProperty.getName(), propertyValue, value.getClass(), (customSerializer != null ?
String.format(" using custom PdxSerializer [%s]", customSerializer) : "")));
}
if (customSerializer != null) {
customSerializer.toData(propertyValue, writer);
}
else {
writer.writeField(persistentProperty.getName(), propertyValue,
(Class<Object>) persistentProperty.getType());
}
if (log.isDebugEnabled()) {
log.debug(String.format("Serializing entity property [%1$s] value [%2$s] of type [%3$s] to PDX%4$s",
persistentProperty.getName(), propertyValue, value.getClass(), (customSerializer != null ?
String.format(" using custom PdxSerializer [%s]", customSerializer) : "")));
}
catch (Exception e) {
throw new MappingException(String.format(
"Error while serializing entity property [%1$s] value [%2$s] of type [%3$s] to PDX%4$s",
persistentProperty.getName(), propertyValue, value.getClass(),
(customSerializer != null ? String.format(" using custom PdxSerializer [%1$s].",
customSerializer.getClass().getName()) : ".")), e);
if (customSerializer != null) {
customSerializer.toData(propertyValue.orElse(null), writer);
}
else {
writer.writeField(persistentProperty.getName(), propertyValue.orElse(null),
(Class<Object>) persistentProperty.getType());
}
}
catch (Exception e) {
Object resolvedPropertyValue = (propertyValue != null ? propertyValue.orElse(null) : null);
throw new MappingException(String.format(
"While serializing entity property [%1$s] value [%2$s] of type [%3$s] to PDX%4$s",
persistentProperty.getName(), resolvedPropertyValue, value.getClass(),
(customSerializer != null ? String.format(" using custom PdxSerializer [%1$s].",
customSerializer.getClass().getName()) : ".")), e);
}
});
GemfirePersistentProperty idProperty = entity.getIdProperty();
Optional<GemfirePersistentProperty> idProperty = entity.getIdProperty();
if (idProperty != null) {
writer.markIdentityField(idProperty.getName());
}
idProperty.ifPresent(gemfirePersistentProperty ->
writer.markIdentityField(gemfirePersistentProperty.getName()));
return true;
}
@@ -325,6 +326,7 @@ public class MappingPdxSerializer implements PdxSerializer, ApplicationContextAw
* @see #getMappingContext()
*/
protected GemfirePersistentEntity<?> getPersistentEntity(Class<?> entityType) {
return getMappingContext().getPersistentEntity(entityType);
return getMappingContext().getPersistentEntity(entityType).orElseThrow(
() -> newIllegalArgumentException("Unable to resolve PersistentEntity for type [%]", entityType));
}
}

View File

@@ -16,6 +16,8 @@
package org.springframework.data.gemfire.mapping;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalArgumentException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
@@ -50,7 +52,7 @@ public class Regions implements Iterable<Region<?, ?>> {
Assert.notNull(regions, "Regions must not be null");
Assert.notNull(mappingContext, "MappingContext must not be null");
Map<String, Region<?, ?>> regionMap = new HashMap<String, Region<?, ?>>();
Map<String, Region<?, ?>> regionMap = new HashMap<>();
for (Region<?, ?> region : regions) {
regionMap.put(region.getName(), region);
@@ -72,12 +74,12 @@ public class Regions implements Iterable<Region<?, ?>> {
*/
@SuppressWarnings("unchecked")
public <T> Region<?, T> getRegion(Class<T> entityType) {
Assert.notNull(entityType, "entityType must not be null");
Assert.notNull(entityType, "Entity type must not be null");
GemfirePersistentEntity<?> entity = mappingContext.getPersistentEntity(entityType);
String regionName = (entity != null ? entity.getRegionName() : entityType.getSimpleName());
String regionName = this.mappingContext.getPersistentEntity(entityType).map((entity) -> entity.getRegionName())
.orElseGet(entityType::getSimpleName);
return (Region<?, T>) regions.get(regionName);
return (Region<?, T>) this.regions.get(regionName);
}
/**
@@ -92,7 +94,7 @@ public class Regions implements Iterable<Region<?, ?>> {
public <S, T> Region<S, T> getRegion(String namePath) {
Assert.hasText(namePath, "Region name/path is required");
return (Region<S, T>) regions.get(namePath);
return (Region<S, T>) this.regions.get(namePath);
}
/*
@@ -102,6 +104,6 @@ public class Regions implements Iterable<Region<?, ?>> {
*/
@Override
public Iterator<Region<?, ?>> iterator() {
return regions.values().iterator();
return this.regions.values().iterator();
}
}

View File

@@ -21,6 +21,7 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
@@ -64,7 +65,7 @@ class GemfireRepositoryBean<T> extends CdiRepositoryBean<T> {
CustomRepositoryImplementationDetector detector, Bean<GemfireMappingContext> gemfireMappingContextBean,
Set<Bean<Region>> regionBeans) {
super(qualifiers, repositoryType, beanManager, detector);
super(qualifiers, repositoryType, beanManager, Optional.ofNullable(detector));
this.beanManager = beanManager;
this.gemfireMappingContextBean = gemfireMappingContextBean;
@@ -148,8 +149,12 @@ class GemfireRepositoryBean<T> extends CdiRepositoryBean<T> {
* @see #newGemfireRepositoryFactory()
*/
@Override
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType, Object customImplementation) {
return newGemfireRepositoryFactory().getRepository(repositoryType, customImplementation);
}
@SuppressWarnings("all")
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType,
Optional<Object> customImplementation) {
return (customImplementation.isPresent()
? newGemfireRepositoryFactory().getRepository(repositoryType, customImplementation.get())
: newGemfireRepositoryFactory().getRepository(repositoryType));
}
}

View File

@@ -32,7 +32,6 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
import org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport;
import org.springframework.data.repository.config.RepositoryConfigurationSource;
import org.springframework.data.repository.config.XmlRepositoryConfigurationSource;
import org.springframework.util.StringUtils;
/**
* {@link RepositoryConfigurationExtension} implementation handling GemFire specific extensions to the Repository XML
@@ -66,7 +65,7 @@ public class GemfireRepositoryConfigurationExtension extends RepositoryConfigura
*/
@Override
protected Collection<Class<?>> getIdentifyingTypes() {
return Collections.<Class<?>>singleton(GemfireRepository.class);
return Collections.singleton(GemfireRepository.class);
}
/*
@@ -93,8 +92,9 @@ public class GemfireRepositoryConfigurationExtension extends RepositoryConfigura
*/
@Override
public void postProcess(BeanDefinitionBuilder builder, AnnotationRepositoryConfigurationSource configurationSource) {
builder.addPropertyReference(MAPPING_CONTEXT_PROPERTY_NAME, resolveMappingContextBeanName(
configurationSource.getAttribute(MAPPING_CONTEXT_REF_ATTRIBUTE_NAME)));
builder.addPropertyReference(MAPPING_CONTEXT_PROPERTY_NAME,
configurationSource.getAttribute(MAPPING_CONTEXT_REF_ATTRIBUTE_NAME)
.orElse(DEFAULT_MAPPING_CONTEXT_BEAN_NAME));
}
/*
@@ -103,13 +103,9 @@ public class GemfireRepositoryConfigurationExtension extends RepositoryConfigura
*/
@Override
public void postProcess(BeanDefinitionBuilder builder, XmlRepositoryConfigurationSource configurationSource) {
builder.addPropertyReference(MAPPING_CONTEXT_PROPERTY_NAME, resolveMappingContextBeanName(
configurationSource.getAttribute(MAPPING_CONTEXT_REF_ATTRIBUTE_NAME)));
}
/* (non-Javadoc) */
private static String resolveMappingContextBeanName(String source) {
return (StringUtils.hasText(source) ? source : DEFAULT_MAPPING_CONTEXT_BEAN_NAME);
builder.addPropertyReference(MAPPING_CONTEXT_PROPERTY_NAME,
configurationSource.getAttribute(MAPPING_CONTEXT_REF_ATTRIBUTE_NAME)
.orElse(DEFAULT_MAPPING_CONTEXT_BEAN_NAME));
}
/*
@@ -121,7 +117,7 @@ public class GemfireRepositoryConfigurationExtension extends RepositoryConfigura
super.registerBeansForRoot(registry, configurationSource);
if (!StringUtils.hasText(configurationSource.getAttribute(MAPPING_CONTEXT_REF_ATTRIBUTE_NAME))) {
if (!configurationSource.getAttribute(MAPPING_CONTEXT_REF_ATTRIBUTE_NAME).isPresent()) {
registry.registerBeanDefinition(DEFAULT_MAPPING_CONTEXT_BEAN_NAME,
new RootBeanDefinition(GemfireMappingContext.class));
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.repository.query;
import java.util.Iterator;
@@ -98,7 +99,7 @@ class GemfireQueryCreator extends AbstractQueryCreator<QueryString, Predicates>
QueryString query = queryBuilder.create(criteria).orderBy(sort);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Created Query '%1$s'", query.toString()));
LOG.debug(String.format("Created Query [%s]", query.toString()));
}
return query;

View File

@@ -43,29 +43,33 @@ import org.springframework.util.StringUtils;
*/
public class GemfireQueryMethod extends QueryMethod {
@SuppressWarnings("all")
protected static final String[] EMPTY_STRING_ARRAY = new String[0];
private final Method method;
private final GemfirePersistentEntity<?> entity;
private final Method method;
/**
* Creates a new {@link GemfireQueryMethod} from the given {@link Method} and {@link RepositoryMetadata}.
*
* @param method must not be {@literal null}.
* @param metadata must not be {@literal null}.
* @param factory must not be {@literal null}.
* @param context must not be {@literal null}.
* @param mappingContext must not be {@literal null}.
*/
public GemfireQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
MappingContext<? extends GemfirePersistentEntity<?>, GemfirePersistentProperty> context) {
MappingContext<? extends GemfirePersistentEntity<?>, GemfirePersistentProperty> mappingContext) {
super(method, metadata, factory);
Assert.notNull(context);
Assert.notNull(mappingContext, "MappingContext must not be null");
assertNonPagingQueryMethod(method);
this.method = method;
this.entity = context.getPersistentEntity(getDomainClass());
this.entity = mappingContext.getPersistentEntity(getDomainClass()).orElseThrow(
() -> new IllegalArgumentException(String.format("Failed to resolve PersistentEntity for type [%s]",
getDomainClass())));
}
/**

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.repository.query;
import java.util.ArrayList;
@@ -29,11 +30,15 @@ import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* The QueryString class is a utility class for working with GemFire OQL query statement syntax.
* {@link QueryString} is a utility class used to construct GemFire OQL query statement syntax.
*
* @author Oliver Gierke
* @author David Turanski
* @author John Blum
* @see java.util.regex.Pattern
* @see org.springframework.data.domain.Sort
* @see org.springframework.data.gemfire.repository.query.support.OqlKeyword
* @see org.apache.geode.cache.Region
*/
public class QueryString {
@@ -117,8 +122,8 @@ public class QueryString {
*/
public QueryString bindIn(Collection<?> values) {
if (values != null) {
String valueString = StringUtils.collectionToDelimitedString(values, ", ", "'", "'");
return new QueryString(this.query.replaceFirst(IN_PATTERN, String.format("(%s)", valueString)));
return new QueryString(this.query.replaceFirst(IN_PATTERN, String.format("(%s)",
StringUtils.collectionToDelimitedString(values, ", ", "'", "'"))));
}
return this;
@@ -147,7 +152,7 @@ public class QueryString {
public Iterable<Integer> getInParameterIndexes() {
Pattern pattern = Pattern.compile(IN_PARAMETER_PATTERN);
Matcher matcher = pattern.matcher(query);
List<Integer> result = new ArrayList<Integer>();
List<Integer> result = new ArrayList<>();
while (matcher.find()) {
result.add(Integer.parseInt(matcher.group()));
@@ -166,7 +171,7 @@ public class QueryString {
* @see org.springframework.data.gemfire.repository.query.QueryString
*/
public QueryString orderBy(Sort sort) {
if (sort != null) {
if (hasSort(sort)) {
StringBuilder orderClause = new StringBuilder("ORDER BY ");
int count = 0;
@@ -181,6 +186,11 @@ public class QueryString {
return this;
}
/* (non-Javadoc) */
private boolean hasSort(Sort sort) {
return (sort != null && sort.iterator().hasNext());
}
/**
* Replaces the SELECT query with a SELECT DISTINCT query if the query does not contain the DISTINCT OQL keyword.
*

View File

@@ -36,11 +36,12 @@ import org.springframework.util.StringUtils;
*/
public class StringBasedGemfireRepositoryQuery extends GemfireRepositoryQuery {
private static final String INVALID_QUERY = "Paging and modifying queries are not supported!";
private static final String INVALID_QUERY = "Paging and modifying queries are not supported";
private boolean userDefinedQuery = false;
private final GemfireTemplate template;
private final QueryString query;
/*
@@ -74,7 +75,7 @@ public class StringBasedGemfireRepositoryQuery extends GemfireRepositoryQuery {
public StringBasedGemfireRepositoryQuery(String query, GemfireQueryMethod queryMethod, GemfireTemplate template) {
super(queryMethod);
Assert.notNull(template);
Assert.notNull(template, "GemfireTemplate must not be null");
this.userDefinedQuery |= !StringUtils.hasText(query);
this.query = new QueryString(StringUtils.hasText(query) ? query : queryMethod.getAnnotatedQuery());
@@ -108,11 +109,11 @@ public class StringBasedGemfireRepositoryQuery extends GemfireRepositoryQuery {
public Object execute(Object[] parameters) {
QueryMethod localQueryMethod = getQueryMethod();
QueryString query = (isUserDefinedQuery() ? this.query : this.query.forRegion(
localQueryMethod.getEntityInformation().getJavaType(), template.getRegion()));
QueryString query = (isUserDefinedQuery() ? this.query
: this.query.forRegion(localQueryMethod.getEntityInformation().getJavaType(), template.getRegion()));
ParametersParameterAccessor parameterAccessor = new ParametersParameterAccessor(
localQueryMethod.getParameters(), parameters);
ParametersParameterAccessor parameterAccessor =
new ParametersParameterAccessor(localQueryMethod.getParameters(), parameters);
for (Integer index : query.getInParameterIndexes()) {
query = query.bindIn(toCollection(parameterAccessor.getBindableValue(index - 1)));
@@ -144,7 +145,7 @@ public class StringBasedGemfireRepositoryQuery extends GemfireRepositoryQuery {
}
}
QueryString applyQueryAnnotationExtensions(final QueryMethod queryMethod, final QueryString queryString) {
QueryString applyQueryAnnotationExtensions(QueryMethod queryMethod, QueryString queryString) {
QueryString resolvedQueryString = queryString;
if (queryMethod instanceof GemfireQueryMethod) {
@@ -199,5 +200,4 @@ public class StringBasedGemfireRepositoryQuery extends GemfireRepositoryQuery {
return (source.getClass().isArray() ? CollectionUtils.arrayToList(source) : Collections.singletonList(source));
}
}

View File

@@ -16,8 +16,11 @@
package org.springframework.data.gemfire.repository.support;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalArgumentException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Optional;
import org.apache.geode.cache.Region;
import org.springframework.data.gemfire.GemfireTemplate;
@@ -38,7 +41,6 @@ import org.springframework.data.repository.core.support.RepositoryFactorySupport
import org.springframework.data.repository.query.EvaluationContextProvider;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -80,8 +82,10 @@ public class GemfireRepositoryFactory extends RepositoryFactorySupport {
@Override
@SuppressWarnings("unchecked")
public <T, ID extends Serializable> GemfireEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
GemfirePersistentEntity<T> entity = (GemfirePersistentEntity<T>) mappingContext.getPersistentEntity(domainClass);
return new DefaultGemfireEntityInformation<T, ID>(entity);
GemfirePersistentEntity<T> entity = (GemfirePersistentEntity<T>) mappingContext.getPersistentEntity(domainClass)
.orElseThrow(() -> newIllegalArgumentException("Unable to resolve PersistentEntity for type [%s]", domainClass));
return new DefaultGemfireEntityInformation<>(entity);
}
/*
@@ -99,7 +103,9 @@ public class GemfireRepositoryFactory extends RepositoryFactorySupport {
}
GemfireTemplate getTemplate(RepositoryMetadata metadata) {
GemfirePersistentEntity<?> entity = mappingContext.getPersistentEntity(metadata.getDomainType());
GemfirePersistentEntity<?> entity = mappingContext.getPersistentEntity(metadata.getDomainType())
.orElseThrow(() -> newIllegalArgumentException("Unable to resolve PersistentEntity for type [%s]",
metadata.getDomainType()));
String entityRegionName = entity.getRegionName();
String repositoryRegionName = getRepositoryRegionName(metadata.getRepositoryInterface());
@@ -148,13 +154,11 @@ public class GemfireRepositoryFactory extends RepositoryFactorySupport {
* #getQueryLookupStrategy(Key, EvaluationContextProvider)
*/
@Override
protected QueryLookupStrategy getQueryLookupStrategy(Key key, EvaluationContextProvider evaluationContextProvider) {
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(Key key,
EvaluationContextProvider evaluationContextProvider) {
return new QueryLookupStrategy() {
@Override
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
NamedQueries namedQueries) {
return Optional.of(
(Method method, RepositoryMetadata metadata, ProjectionFactory factory, NamedQueries namedQueries) -> {
GemfireQueryMethod queryMethod = new GemfireQueryMethod(method, metadata, factory, mappingContext);
GemfireTemplate template = getTemplate(metadata);
@@ -169,7 +173,6 @@ public class GemfireRepositoryFactory extends RepositoryFactorySupport {
}
return new PartTreeGemfireRepositoryQuery(queryMethod, template);
}
};
});
}
}

View File

@@ -16,6 +16,8 @@
package org.springframework.data.gemfire.repository.support;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalArgumentException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
@@ -23,6 +25,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.geode.cache.Cache;
@@ -78,7 +81,11 @@ public class SimpleGemfireRepository<T, ID extends Serializable> implements Gemf
*/
@Override
public <U extends T> U save(U entity) {
template.put(entityInformation.getId(entity), entity);
ID id = entityInformation.getId(entity).orElseThrow(
() -> newIllegalArgumentException("ID for entity [%s] is required", entity));
template.put(id, entity);
return entity;
}
@@ -88,15 +95,18 @@ public class SimpleGemfireRepository<T, ID extends Serializable> implements Gemf
*/
@Override
public <U extends T> Iterable<U> save(Iterable<U> entities) {
Map<ID, U> result = new HashMap<>();
Map<ID, U> entitiesToSave = new HashMap<>();
for (U entity : entities) {
result.put(entityInformation.getId(entity), entity);
ID id = entityInformation.getId(entity).orElseThrow(
() -> newIllegalArgumentException("ID for entity [%s] is required", entity));
entitiesToSave.put(id, entity);
}
template.putAll(result);
template.putAll(entitiesToSave);
return result.values();
return entitiesToSave.values();
}
/*
@@ -116,8 +126,10 @@ public class SimpleGemfireRepository<T, ID extends Serializable> implements Gemf
*/
@Override
public long count() {
SelectResults<Integer> results = template.find("SELECT count(*) FROM " + template.getRegion().getFullPath());
return (long) results.iterator().next();
SelectResults<Integer> results =
template.find(String.format("SELECT count(*) FROM %s", template.getRegion().getFullPath()));
return Long.valueOf(results.iterator().next());
}
/*
@@ -126,7 +138,7 @@ public class SimpleGemfireRepository<T, ID extends Serializable> implements Gemf
*/
@Override
public boolean exists(ID id) {
return (findOne(id) != null);
return findOne(id).isPresent();
}
/*
@@ -135,8 +147,8 @@ public class SimpleGemfireRepository<T, ID extends Serializable> implements Gemf
*/
@Override
@SuppressWarnings("unchecked")
public T findOne(ID id) {
return (T) template.get(id);
public Optional<T> findOne(ID id) {
return Optional.ofNullable(template.get(id));
}
/*
@@ -145,7 +157,9 @@ public class SimpleGemfireRepository<T, ID extends Serializable> implements Gemf
*/
@Override
public Collection<T> findAll() {
SelectResults<T> results = template.find("SELECT * FROM " + template.getRegion().getFullPath());
SelectResults<T> results =
template.find(String.format("SELECT * FROM %s", template.getRegion().getFullPath()));
return results.asList();
}
@@ -196,7 +210,7 @@ public class SimpleGemfireRepository<T, ID extends Serializable> implements Gemf
*/
@Override
public void delete(T entity) {
delete(entityInformation.getId(entity));
delete(entityInformation.getId(entity).orElseThrow(() -> new IllegalArgumentException("ID is required")));
}
/*

View File

@@ -16,6 +16,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.Region;
@@ -102,10 +103,14 @@ public class GemFireDataSourceIntegrationTests extends ClientServerIntegrationTe
@Test
public void repositoryCreatedAndFunctional() {
PersonRepository repo = applicationContext.getBean(PersonRepository.class);
Person daveMathhews = new Person(1L, "Dave", "Mathhews");
Person daveMathews = new Person(1L, "Dave", "Mathews");
PersonRepository repository = applicationContext.getBean(PersonRepository.class);
assertThat(repo.save(daveMathhews)).isSameAs(daveMathhews);
assertThat(repo.findOne(1L).getFirstname()).isEqualTo("Dave");
assertThat(repository.save(daveMathews)).isSameAs(daveMathews);
Optional<Person> result = repository.findOne(1L);
assertThat(result.isPresent()).isTrue();
assertThat(result.get().getFirstname()).isEqualTo("Dave");
}
}

View File

@@ -16,76 +16,67 @@
package org.springframework.data.gemfire.mapping;
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.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalStateException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Optional;
import org.junit.Test;
import org.springframework.data.gemfire.TestUtils;
import org.springframework.data.gemfire.mapping.annotation.Region;
import org.springframework.data.gemfire.mapping.model.GemfireSimpleTypeHolder;
import org.springframework.data.mapping.PersistentEntity;
import lombok.Data;
/**
* The GemfireMappingContextTest class is a test suite of test cases testing the contract and functionality
* of the GemfireMappingContext class.
* Unit tests for {@link GemfireMappingContext} class.
*
* @author John Blum
* @see org.junit.Test
* @see org.springframework.data.gemfire.mapping.GemfireMappingContext
* @since 1.6.3
*/
public class GemfireMappingContextTest {
public class GemfireMappingContextUnitTests {
private GemfireMappingContext mappingContext = new GemfireMappingContext();
@Test
@SuppressWarnings("unchecked")
public void getPersistentEntityForPerson() throws Exception {
GemfirePersistentEntity<Person> personPersistentEntity = (GemfirePersistentEntity<Person>)
mappingContext.getPersistentEntity(Person.class);
GemfirePersistentEntity<Person> personPersistentEntity =
(GemfirePersistentEntity<Person>) mappingContext.getPersistentEntity(Person.class).orElseThrow(
() -> newIllegalStateException("Unable to resolve PersistentEntity for type [%s]",
Person.class.getName()));
assertThat(personPersistentEntity, is(notNullValue()));
assertThat(personPersistentEntity.getRegionName(), is(equalTo("People")));
assertThat(personPersistentEntity).isNotNull();
assertThat(personPersistentEntity.getRegionName()).isEqualTo("People");
GemfirePersistentProperty namePersistentProperty = personPersistentEntity.getPersistentProperty("name");
Optional<GemfirePersistentProperty> namePersistentProperty =
personPersistentEntity.getPersistentProperty("name");
assertThat(namePersistentProperty, is(notNullValue()));
assertThat(namePersistentProperty.isEntity(), is(false));
assertThat(namePersistentProperty.getName(), is(equalTo("name")));
assertThat(namePersistentProperty.getOwner(), is(equalTo((PersistentEntity) personPersistentEntity)));
assertThat(TestUtils.readField("simpleTypeHolder", namePersistentProperty), is(instanceOf(
GemfireSimpleTypeHolder.class)));
assertThat(namePersistentProperty.isPresent()).isTrue();
assertThat(namePersistentProperty.get().isEntity()).isFalse();
assertThat(namePersistentProperty.get().getName()).isEqualTo("name");
assertThat(namePersistentProperty.get().getOwner()).isEqualTo(personPersistentEntity);
assertThat(TestUtils.<Object>readField("simpleTypeHolder", namePersistentProperty.get()))
.isInstanceOf(GemfireSimpleTypeHolder.class);
}
@Test
public void getPersistentEntityForBigDecimal() {
assertThat(mappingContext.getPersistentEntity(BigDecimal.class), is(nullValue()));
assertThat(mappingContext.getPersistentEntity(BigDecimal.class).isPresent()).isFalse();
}
@Test
public void getPersistentEntityForBigInteger() {
assertThat(mappingContext.getPersistentEntity(BigInteger.class), is(nullValue()));
assertThat(mappingContext.getPersistentEntity(BigInteger.class).isPresent()).isFalse();
}
@Data
@Region("People")
class Person {
private String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
}

View File

@@ -19,9 +19,11 @@ package org.springframework.data.gemfire.mapping;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalStateException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
@@ -60,7 +62,8 @@ public class GemfirePersistentEntityUnitTests {
@SuppressWarnings("unchecked")
protected <T> GemfirePersistentEntity<T> getMappingContextPersistentEntity(Class<T> type) {
return (GemfirePersistentEntity<T>) this.mappingContext.getPersistentEntity(type);
return (GemfirePersistentEntity<T>) this.mappingContext.getPersistentEntity(type).orElseThrow(
() -> newIllegalStateException("Unable to resolve PersistentEntity for type [%s]", type));
}
protected <T> GemfirePersistentEntity<T> newPersistentEntity(Class<T> type) {
@@ -93,10 +96,10 @@ public class GemfirePersistentEntityUnitTests {
assertThat(entity).isNotNull();
assertThat(entity.getRegionName()).isEqualTo("Example");
GemfirePersistentProperty currency = entity.getPersistentProperty("currency");
Optional<GemfirePersistentProperty> currency = entity.getPersistentProperty("currency");
assertThat(currency).isNotNull();
assertThat(currency.isEntity()).isFalse();
assertThat(currency.isPresent()).isTrue();
assertThat(currency.get().isEntity()).isFalse();
}
@Test
@@ -108,10 +111,10 @@ public class GemfirePersistentEntityUnitTests {
assertThat(entity).isNotNull();
assertThat(entity.getRegionName()).isEqualTo("Example");
GemfirePersistentProperty bigNumber = entity.getPersistentProperty("bigNumber");
Optional<GemfirePersistentProperty> bigNumber = entity.getPersistentProperty("bigNumber");
assertThat(bigNumber).isNotNull();
assertThat(bigNumber.isEntity()).isFalse();
assertThat(bigNumber.isPresent()).isTrue();
assertThat(bigNumber.get().isEntity()).isFalse();
}
/**
@@ -121,8 +124,7 @@ public class GemfirePersistentEntityUnitTests {
public void identifierForNonIdAnnotatedEntityWithNoIdFieldOrPropertyIsNull() {
IdentifierAccessor identifierAccessor = getIdentifierAccessor(new NonRegionAnnotatedEntity());
assertThat(identifierAccessor).isNotNull();
assertThat(identifierAccessor.getIdentifier()).isNull();
assertThat(identifierAccessor.getIdentifier().orElse(null)).isNull();
}
/**
@@ -132,8 +134,7 @@ public class GemfirePersistentEntityUnitTests {
public void identifierForNonIdAnnotatedEntityWithIdFieldIsNotNull() {
IdentifierAccessor identifierAccessor = getIdentifierAccessor(new NonIdAnnotatedIdFieldEntity());
assertThat(identifierAccessor.getIdentifier()).isNotNull();
assertThat(identifierAccessor.getIdentifier()).isEqualTo(123L);
assertThat(identifierAccessor.getIdentifier().orElse(null)).isEqualTo(123L);
}
/**
@@ -143,16 +144,14 @@ public class GemfirePersistentEntityUnitTests {
public void identifierForNonIdAnnotatedEntityWithIdPropertyIsNotNull() {
IdentifierAccessor identifierAccessor = getIdentifierAccessor(new NonIdAnnotatedIdGetterEntity());
assertThat(identifierAccessor).isNotNull();
assertThat(identifierAccessor.getIdentifier()).isEqualTo(456L);
assertThat(identifierAccessor.getIdentifier().orElse(null)).isEqualTo(456L);
}
@Test
public void identifierForIdAnnotatedFieldAndPropertyEntityShouldNotConflict() {
IdentifierAccessor identifierAccessor = getIdentifierAccessor(new IdAnnotatedFieldAndPropertyEntity());
assertThat(identifierAccessor).isNotNull();
assertThat(identifierAccessor.getIdentifier()).isEqualTo(1L);
assertThat(identifierAccessor.getIdentifier().orElse(null)).isEqualTo(1L);
}
@Test
@@ -170,6 +169,7 @@ public class GemfirePersistentEntityUnitTests {
getIdentifierAccessor(new AmbiguousIdAnnotatedFieldAndIdAnnotatedPropertyEntity());
}
@SuppressWarnings("unused")
static class AmbiguousIdAnnotatedFieldAndIdAnnotatedPropertyEntity {
@Id

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.mapping;
import static org.hamcrest.CoreMatchers.is;
@@ -43,7 +44,7 @@ import org.springframework.data.gemfire.repository.sample.Person;
* @author Oliver Gierke
* @author John Blum
*/
public class MappingPdxSerializerIntegrationTest {
public class MappingPdxSerializerIntegrationTests {
static Region<Object, Object> region;
@@ -55,7 +56,7 @@ public class MappingPdxSerializerIntegrationTest {
new DefaultConversionService());
cache = new CacheFactory()
.set("name", MappingPdxSerializerIntegrationTest.class.getSimpleName())
.set("name", MappingPdxSerializerIntegrationTests.class.getSimpleName())
.set("mcast-port", "0")
.set("log-level", "warning")
.setPdxSerializer(serializer)
@@ -115,7 +116,10 @@ public class MappingPdxSerializerIntegrationTest {
address.zipCode = "01234";
address.city = "London";
PersonWithDataSerializableProperty person = new PersonWithDataSerializableProperty(2L, "Oliver", "Gierke", new DataSerializableProperty("foo"));
PersonWithDataSerializableProperty person =
new PersonWithDataSerializableProperty(2L, "Oliver", "Gierke",
new DataSerializableProperty("foo"));
person.address = address;
region.put(2L, person);
@@ -182,5 +186,4 @@ public class MappingPdxSerializerIntegrationTest {
}
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.mapping;
import static org.assertj.core.api.Assertions.assertThat;
@@ -26,6 +27,8 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalArgumentException;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalStateException;
import java.util.Collections;
@@ -94,8 +97,7 @@ public class MappingPdxSerializerUnitTests {
context = new GemfireMappingContext();
conversionService = new GenericConversionService();
serializer = new MappingPdxSerializer(context, conversionService);
serializer.setCustomSerializers(Collections.<Class<?>, PdxSerializer>singletonMap(
Address.class, mockAddressSerializer));
serializer.setCustomSerializers(Collections.singletonMap(Address.class, mockAddressSerializer));
}
@Test
@@ -158,26 +160,31 @@ public class MappingPdxSerializerUnitTests {
serializer.fromData(Person.class, mockReader);
verify(mockInstantiator, times(1)).createInstance(eq(context.getPersistentEntity(Person.class)),
any(ParameterValueProvider.class));
GemfirePersistentEntity<?> persistentEntity = context.getPersistentEntity(Person.class)
.orElseThrow(() -> newIllegalStateException("Unable to resolve PersistentEntity for type [%s]",
Person.class.getName()));
verify(mockInstantiator, times(1)).createInstance(eq(persistentEntity),
any(ParameterValueProvider.class));
verify(mockAddressSerializer, times(1)).fromData(eq(Address.class), any(PdxReader.class));
}
@Test
@SuppressWarnings("unchecked")
public void fromDataMapsPdxDataToApplicationDomainObject() {
Address expectedAddress = new Address();
expectedAddress.city = "Portland";
expectedAddress.zipCode = "12345";
when(mockInstantiator.createInstance(any(GemfirePersistentEntity.class), any(ParameterValueProvider.class)))
.thenReturn(new Person(null, null, null));
when(mockReader.readField(eq("id"))).thenReturn(1l);
when(mockReader.readField(eq("id"))).thenReturn(1L);
when(mockReader.readField(eq("firstname"))).thenReturn("Jon");
when(mockReader.readField(eq("lastname"))).thenReturn("Doe");
when(mockAddressSerializer.fromData(eq(Address.class), eq(mockReader))).thenReturn(expectedAddress);
serializer.setGemfireInstantiators(Collections.<Class<?>, EntityInstantiator>singletonMap(
Person.class, mockInstantiator));
serializer.setGemfireInstantiators(Collections.singletonMap(Person.class, mockInstantiator));
Object obj = serializer.fromData(Person.class, mockReader);
@@ -186,7 +193,7 @@ public class MappingPdxSerializerUnitTests {
Person jonDoe = (Person) obj;
assertThat(jonDoe.getAddress()).isEqualTo(expectedAddress);
assertThat(jonDoe.getId()).isEqualTo(1l);
assertThat(jonDoe.getId()).isEqualTo(1L);
assertThat(jonDoe.getFirstname()).isEqualTo("Jon");
assertThat(jonDoe.getLastname()).isEqualTo("Doe");
@@ -198,24 +205,26 @@ public class MappingPdxSerializerUnitTests {
}
@Test
@SuppressWarnings("unchecked")
public void fromDataHandlesExceptionProperly() {
when(mockInstantiator.createInstance(any(GemfirePersistentEntity.class), any(ParameterValueProvider.class)))
.thenReturn(new Person(null, null, null));
when(mockReader.readField(eq("id"))).thenThrow(new IllegalArgumentException("test"));
serializer.setGemfireInstantiators(Collections.<Class<?>, EntityInstantiator>singletonMap(
Person.class, mockInstantiator));
when(mockReader.readField(eq("id"))).thenThrow(newIllegalArgumentException("test"));
serializer.setGemfireInstantiators(Collections.singletonMap(Person.class, mockInstantiator));
try {
expectedException.expect(MappingException.class);
expectedException.expectCause(isA(IllegalArgumentException.class));
expectedException.expectMessage(String.format(
"while setting value [null] of property [id] for entity of type [%1$s] from PDX", Person.class));
"While setting value [null] of property [id] for entity of type [%s] from PDX", Person.class));
serializer.fromData(Person.class, mockReader);
}
finally {
verify(mockInstantiator, times(1)).createInstance(any(GemfirePersistentEntity.class), any(ParameterValueProvider.class));
verify(mockInstantiator, times(1))
.createInstance(any(GemfirePersistentEntity.class), any(ParameterValueProvider.class));
verify(mockReader, times(1)).readField(eq("id"));
}
}
@@ -226,16 +235,15 @@ public class MappingPdxSerializerUnitTests {
address.city = "Portland";
address.zipCode = "12345";
Person jonDoe = new Person(1l, "Jon", "Doe");
Person jonDoe = new Person(1L, "Jon", "Doe");
jonDoe.address = address;
serializer.setCustomSerializers(Collections.<Class<?>, PdxSerializer>singletonMap(
Address.class, mockAddressSerializer));
serializer.setCustomSerializers(Collections.singletonMap(Address.class, mockAddressSerializer));
assertThat(serializer.toData(jonDoe, mockWriter)).isTrue();
verify(mockAddressSerializer, times(1)).toData(eq(address), eq(mockWriter));
verify(mockWriter, times(1)).writeField(eq("id"), eq(1l), eq(Long.class));
verify(mockWriter, times(1)).writeField(eq("id"), eq(1L), eq(Long.class));
verify(mockWriter, times(1)).writeField(eq("firstname"), eq("Jon"), eq(String.class));
verify(mockWriter, times(1)).writeField(eq("lastname"), eq("Doe"), eq(String.class));
verify(mockWriter, times(1)).markIdentityField(eq("id"));
@@ -247,23 +255,23 @@ public class MappingPdxSerializerUnitTests {
address.city = "Portland";
address.zipCode = "12345";
Person jonDoe = new Person(1l, "Jon", "Doe");
Person jonDoe = new Person(1L, "Jon", "Doe");
jonDoe.address = address;
when(mockWriter.writeField(eq("address"), eq(address), eq(Address.class)))
.thenThrow(new IllegalArgumentException("test"));
.thenThrow(newIllegalArgumentException("test"));
try {
expectedException.expect(MappingException.class);
expectedException.expectCause(isA(IllegalArgumentException.class));
expectedException.expectMessage(String.format(
"Error while serializing entity property [address] value [Portland, 12345] of type [%s] to PDX",
"While serializing entity property [address] value [Portland, 12345] of type [%s] to PDX",
Person.class));
new MappingPdxSerializer(context, conversionService).toData(jonDoe, mockWriter);
}
finally {
verify(mockWriter, atMost(1)).writeField(eq("id"), eq(1l), eq(Long.class));
verify(mockWriter, atMost(1)).writeField(eq("id"), eq(1L), eq(Long.class));
verify(mockWriter, atMost(1)).writeField(eq("firstname"), eq("Jon"), eq(String.class));
verify(mockWriter, atMost(1)).writeField(eq("lastname"), eq("Doe"), eq(String.class));
verify(mockWriter, times(1)).writeField(eq("address"), eq(address), eq(Address.class));

View File

@@ -16,30 +16,28 @@
package org.springframework.data.gemfire.mapping;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
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.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.apache.geode.cache.Region;
import org.junit.After;
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.repository.sample.GuestUser;
import org.springframework.data.gemfire.repository.sample.RootUser;
import org.springframework.data.gemfire.repository.sample.User;
import org.springframework.data.mapping.context.MappingContext;
@@ -47,6 +45,7 @@ import org.springframework.data.mapping.context.MappingContext;
* The RegionsTest class is a test suite of test cases testing the contract and functionality of the Regions class.
*
* @author John J. Blum
* @see org.junit.Rule
* @see org.junit.Test
* @see org.junit.runner.RunWith
* @see org.mockito.Mockito
@@ -58,6 +57,9 @@ import org.springframework.data.mapping.context.MappingContext;
@RunWith(MockitoJUnitRunner.class)
public class RegionsTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Mock
private MappingContext mockMappingContext;
@@ -67,13 +69,11 @@ public class RegionsTest {
private Regions regions;
protected Region mockRegion(final String fullPath) {
// NOTE if the Region path does not contain a "/" then lastIndexOf returns -1 and substring is appropriately
// based on a 0 index then by adding 1, ;-)
protected Region mockRegion(String fullPath) {
return mockRegion(fullPath.substring(fullPath.lastIndexOf(Region.SEPARATOR) + 1), fullPath);
}
protected Region mockRegion(final String name, final String fullPath) {
protected Region mockRegion(String name, String fullPath) {
Region mockRegion = mock(Region.class, name);
when(mockRegion.getName()).thenReturn(name);
@@ -88,10 +88,9 @@ public class RegionsTest {
mockAdminUsers = mockRegion("/Users/Admin");
mockGuestUsers = mockRegion("/Users/Guest");
regions = new Regions(Arrays.<Region<?, ?>>asList(mockUsers, mockAdminUsers, mockGuestUsers),
mockMappingContext);
regions = new Regions(Arrays.asList(mockUsers, mockAdminUsers, mockGuestUsers), mockMappingContext);
assertThat(regions, is(notNullValue()));
assertThat(regions).isNotNull();
}
@After
@@ -100,9 +99,75 @@ public class RegionsTest {
regions = null;
}
@Test
public void getRegionByEntityTypeReturnsRegionForEntityRegionName() {
GemfirePersistentEntity<User> mockPersistentEntity = mock(GemfirePersistentEntity.class);
when(mockPersistentEntity.getRegionName()).thenReturn("Users");
when(mockMappingContext.getPersistentEntity(eq(User.class))).thenReturn(Optional.of(mockPersistentEntity));
assertThat(regions.getRegion(User.class)).isEqualTo(mockUsers);
}
@Test
public void getRegionByEntityTypeReturnsRegionForEntityTypeSimpleName() {
when(mockMappingContext.getPersistentEntity(any(Class.class))).thenReturn(Optional.empty());
assertThat(regions.getRegion(Users.class)).isEqualTo(mockUsers);
}
@Test
public void getRegionByEntityTypeReturnsNull() {
when(mockMappingContext.getPersistentEntity(any(Class.class))).thenReturn(Optional.empty());
assertThat(regions.getRegion(Object.class)).isNull();
}
@Test
public void getRegionWithNullEntityTypeThrowsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("Entity type must not be null");
regions.getRegion((Class) null);
}
@Test
public void getRegionWithNameReturnsRegion() {
assertThat(regions.getRegion("Users")).isSameAs(mockUsers);
assertThat(regions.getRegion("Admin")).isSameAs(mockAdminUsers);
assertThat(regions.getRegion("Guest")).isSameAs(mockGuestUsers);
}
@Test
public void getRegionWithPathReturnsRegion() {
assertThat(regions.getRegion("/Users")).isSameAs(mockUsers);
assertThat(regions.getRegion("/Users/Admin")).isSameAs(mockAdminUsers);
assertThat(regions.getRegion("/Users/Guest")).isSameAs(mockGuestUsers);
}
@Test
public void getRegionWithNonExistingNameReturnsNull() {
assertThat(regions.getRegion("NonExistingRegionName")).isNull();
}
@Test
public void getRegionWithNonExistingPathReturnsNull() {
assertThat(regions.getRegion("/Non/Existing/Region/Path")).isNull();
}
@Test
public void getRegionWithNullNameNullPathThrowsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectCause(is(nullValue(Throwable.class)));
exception.expectMessage("Region name/path is required");
regions.getRegion((String) null);
}
@Test
public void iterateRegions() {
List<Region> actualRegions = new ArrayList<Region>(3);
List<Region> actualRegions = new ArrayList<>(3);
for (Region region : regions) {
actualRegions.add(region);
@@ -110,67 +175,10 @@ public class RegionsTest {
List<Region> expectedRegions = Arrays.asList(mockUsers, mockAdminUsers, mockGuestUsers);
assertEquals(expectedRegions.size() * 2, actualRegions.size());
assertTrue(actualRegions.containsAll(expectedRegions));
assertThat(actualRegions).hasSize(expectedRegions.size() * 2);
assertThat(actualRegions).containsAll(expectedRegions);
}
@Test
public void getRegionByNameOrPath() {
assertSame(mockUsers, regions.getRegion("Users"));
assertSame(mockUsers, regions.getRegion("/Users"));
assertSame(mockAdminUsers, regions.getRegion("Admin"));
assertSame(mockAdminUsers, regions.getRegion("/Users/Admin"));
assertSame(mockGuestUsers, regions.getRegion("Guest"));
assertSame(mockGuestUsers, regions.getRegion("/Users/Guest"));
interface Users {
}
@Test(expected = IllegalArgumentException.class)
public void getRegionByNameOrPathWithNullArgument() {
regions.getRegion((String) null);
}
@Test
public void getRegionByDomainClassType() {
when(mockMappingContext.getPersistentEntity(Object.class)).thenReturn(null);
assertSame(mockUsers, regions.getRegion(Users.class));
assertNull(regions.getRegion(User.class));
assertNull(regions.getRegion(RootUser.class));
assertNull(regions.getRegion(GuestUser.class));
}
@Test
public void getRegionByDomainClassTypeAndPersistentEntity() {
GemfirePersistentEntity mockUsersEntity = mock(GemfirePersistentEntity.class, "UsersGemfirePeristentEntity");
GemfirePersistentEntity mockAdminUserEntity = mock(GemfirePersistentEntity.class, "AdminUserGemfirePeristentEntity");
GemfirePersistentEntity mockGuestUserEntity = mock(GemfirePersistentEntity.class, "GuestUserGemfirePeristentEntity");
when(mockMappingContext.getPersistentEntity(User.class)).thenReturn(mockUsersEntity);
when(mockUsersEntity.getRegionName()).thenReturn("/Users");
when(mockMappingContext.getPersistentEntity(RootUser.class)).thenReturn(mockAdminUserEntity);
when(mockAdminUserEntity.getRegionName()).thenReturn("Admin");
when(mockMappingContext.getPersistentEntity(GuestUser.class)).thenReturn(mockGuestUserEntity);
when(mockGuestUserEntity.getRegionName()).thenReturn("/Users/Guest");
when(mockMappingContext.getPersistentEntity(Object.class)).thenReturn(null);
assertSame(mockUsers, regions.getRegion(User.class));
assertSame(mockUsers, regions.getRegion(Users.class));
assertSame(mockAdminUsers, regions.getRegion(RootUser.class));
assertSame(mockGuestUsers, regions.getRegion(GuestUser.class));
}
@Test
public void getRegionByPersistentEntity() {
GemfirePersistentEntity mockPersistentEntity = mock(GemfirePersistentEntity.class, "GemfirePersistentEntity");
when(mockMappingContext.getPersistentEntity(any(Class.class))).thenReturn(mockPersistentEntity);
when(mockPersistentEntity.getRegionName()).thenReturn("/Non/Existing/Region");
assertNull(regions.getRegion(User.class));
assertNull(regions.getRegion(RootUser.class));
assertNull(regions.getRegion(GuestUser.class));
}
protected interface Users {
}
}

View File

@@ -83,7 +83,7 @@ public class CdiExtensionIntegrationTest {
Person expectedJonDoe = repositoryClient.newPerson("Jon", "Doe");
assertThat(expectedJonDoe, is(notNullValue()));
assertThat(expectedJonDoe.getId(), is(greaterThan(0l)));
assertThat(expectedJonDoe.getId(), is(greaterThan(0L)));
assertThat(expectedJonDoe.getName(), is(equalTo("Jon Doe")));
Person savedJonDoe = repositoryClient.save(expectedJonDoe);
@@ -94,8 +94,8 @@ public class CdiExtensionIntegrationTest {
assertIsExpectedPerson(foundJonDoe, expectedJonDoe);
assertThat(repositoryClient.delete(expectedJonDoe), is(true));
assertThat(repositoryClient.find(expectedJonDoe.getId()), is(nullValue()));
assertThat(repositoryClient.delete(foundJonDoe), is(true));
assertThat(repositoryClient.find(foundJonDoe.getId()), is(nullValue()));
}
@Test

View File

@@ -39,6 +39,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -55,15 +56,12 @@ import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.data.gemfire.GemfireAccessor;
import org.springframework.data.gemfire.TestUtils;
import org.springframework.data.gemfire.mapping.GemfireMappingContext;
import org.springframework.data.gemfire.repository.GemfireRepository;
import org.springframework.data.gemfire.repository.support.GemfireRepositoryFactory;
import org.springframework.data.gemfire.repository.support.SimpleGemfireRepository;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.support.RepositoryProxyPostProcessor;
/**
* The GemfireRepositoryBeanTest class is a test suite of test cases testing the contract and functionality
@@ -286,37 +284,35 @@ public class GemfireRepositoryBeanTest {
GemfireRepositoryFactory newGemfireRepositoryFactory() {
GemfireRepositoryFactory gemfireRepositoryFactory = super.newGemfireRepositoryFactory();
gemfireRepositoryFactory.addRepositoryProxyPostProcessor(new RepositoryProxyPostProcessor() {
public void postProcess(ProxyFactory factory, RepositoryInformation repositoryInformation) {
try {
assertThat((Class<PersonRepository>) repositoryInformation.getRepositoryInterface(),
is(equalTo(PersonRepository.class)));
assertThat((Class<SimpleGemfireRepository>) repositoryInformation.getRepositoryBaseClass(),
is(equalTo(SimpleGemfireRepository.class)));
assertThat((Class<Person>) repositoryInformation.getDomainType(), is(equalTo(Person.class)));
assertThat((Class<Long>) repositoryInformation.getIdType(), is(equalTo(Long.class)));
assertThat((Class<SimpleGemfireRepository>) factory.getTargetClass(),
is(equalTo(SimpleGemfireRepository.class)));
gemfireRepositoryFactory.addRepositoryProxyPostProcessor((factory, repositoryInformation) -> {
try {
assertThat(repositoryInformation.getRepositoryInterface(),
is(equalTo(PersonRepository.class)));
assertThat(repositoryInformation.getRepositoryBaseClass(),
is(equalTo(SimpleGemfireRepository.class)));
assertThat(repositoryInformation.getDomainType(), is(equalTo(Person.class)));
assertThat(repositoryInformation.getIdType(), is(equalTo(Long.class)));
assertThat(factory.getTargetClass(), is(equalTo(SimpleGemfireRepository.class)));
Object gemfireRepository = factory.getTargetSource().getTarget();
Object gemfireRepository = factory.getTargetSource().getTarget();
GemfireAccessor gemfireAccessor = TestUtils.readField("template", gemfireRepository);
GemfireAccessor gemfireAccessor = TestUtils.readField("template", gemfireRepository);
assertThat(gemfireAccessor, is(notNullValue()));
assertThat(gemfireAccessor.getRegion(), is(equalTo(mockRegion)));
assertThat(gemfireAccessor, is(notNullValue()));
assertThat(gemfireAccessor.getRegion(), is(equalTo(mockRegion)));
repositoryProxyPostProcessed.set(true);
}
catch (Exception e) {
throw new RuntimeException(e);
}
repositoryProxyPostProcessed.set(true);
}
catch (Exception e) {
throw new RuntimeException(e);
}
});
return gemfireRepositoryFactory;
}
};
GemfireRepository<Person, Long> gemfireRepository = repositoryBean.create(null, PersonRepository.class, null);
GemfireRepository<Person, Long> gemfireRepository =
repositoryBean.create(null, PersonRepository.class, Optional.empty());
assertThat(gemfireRepository, is(notNullValue()));
assertThat(repositoryProxyPostProcessed.get(), is(true));

View File

@@ -34,13 +34,13 @@ import org.springframework.util.Assert;
*/
public class RepositoryClient {
private static final AtomicLong ID_SEQUENCE = new AtomicLong(0l);
private static final AtomicLong ID_SEQUENCE = new AtomicLong(0L);
@Inject
private SamplePersonRepository personRepository;
protected SamplePersonRepository getPersonRepository() {
Assert.state(personRepository != null, "personRepository was not properly initialized");
Assert.state(personRepository != null, "PersonRepository was not properly initialized");
return personRepository;
}
@@ -49,7 +49,7 @@ public class RepositoryClient {
}
public Person find(Long id) {
return getPersonRepository().findOne(id);
return getPersonRepository().findOne(id).orElse(null);
}
public Person save(Person person) {

View File

@@ -29,6 +29,7 @@ import static org.mockito.Mockito.when;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Optional;
import org.junit.Test;
import org.springframework.beans.PropertyValue;
@@ -51,8 +52,7 @@ import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Test suite of test cases testing the contract and functionality of the
* {@link GemfireRepositoryConfigurationExtension} class.
* Unit tests for {@link GemfireRepositoryConfigurationExtension}.
*
* @author John Blum
* @see org.junit.Test
@@ -143,7 +143,8 @@ public class GemfireRepositoryConfigurationExtensionTest {
AnnotationRepositoryConfigurationSource mockRepositoryConfigurationSource =
mock(AnnotationRepositoryConfigurationSource.class);
when(mockRepositoryConfigurationSource.getAttribute(eq("mappingContextRef"))).thenReturn("testMappingContext");
when(mockRepositoryConfigurationSource.getAttribute(eq("mappingContextRef")))
.thenReturn(Optional.of("testMappingContext"));
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition();
@@ -162,7 +163,8 @@ public class GemfireRepositoryConfigurationExtensionTest {
AnnotationRepositoryConfigurationSource mockRepositoryConfigurationSource =
mock(AnnotationRepositoryConfigurationSource.class);
when(mockRepositoryConfigurationSource.getAttribute(eq("mappingContextRef"))).thenReturn(" ");
when(mockRepositoryConfigurationSource.getAttribute(eq("mappingContextRef")))
.thenReturn(Optional.empty());
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition();

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.repository.config;
import org.springframework.beans.factory.annotation.Autowired;
@@ -23,12 +24,12 @@ import org.springframework.test.context.ContextConfiguration;
/**
* Integration tests for namespace usage.
*
*
* @author Oliver Gierke
*/
@ContextConfiguration("partitioned-region-repo-context.xml")
public class PartitionedRegionNamespaceRepositoryIntegrationTests extends
AbstractGemfireRepositoryFactoryIntegrationTests {
public class PartitionedRegionNamespaceRepositoryIntegrationTests
extends AbstractGemfireRepositoryFactoryIntegrationTests {
@Autowired
PersonRepository repository;

View File

@@ -16,9 +16,11 @@
package org.springframework.data.gemfire.repository.query;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalStateException;
import java.io.Serializable;
@@ -29,7 +31,6 @@ import org.springframework.data.gemfire.mapping.GemfireMappingContext;
import org.springframework.data.gemfire.mapping.GemfirePersistentEntity;
import org.springframework.data.gemfire.repository.sample.Algorithm;
import org.springframework.data.gemfire.repository.sample.Animal;
import org.springframework.data.mapping.context.MappingContext;
/**
* The DefaultGemfireEntityInformationTest class is a test suite of test cases testing the contract and functionality
@@ -43,103 +44,100 @@ import org.springframework.data.mapping.context.MappingContext;
*/
public class DefaultGemfireEntityInformationTest {
private MappingContext mappingContext;
private GemfireMappingContext mappingContext;
@Before
public void setup() {
mappingContext = new GemfireMappingContext();
}
protected Algorithm createAlgorithm(final String name) {
return new Algorithm() {
public String getName() {
return name;
}
};
@SuppressWarnings("unchecked")
protected <T extends Algorithm> T newAlgorithm(String name) {
return (T) (Algorithm) () -> name;
}
protected Animal createAnimal(final Long id, final String name) {
protected Animal newAnimal(Long id, String name) {
Animal animal = new Animal();
animal.setId(id);
animal.setName(name);
return animal;
}
protected <T, ID extends Serializable> GemfireEntityInformation<T, ID> createEntityInformation(
final GemfirePersistentEntity<T> persistentEntity) {
return new DefaultGemfireEntityInformation<T, ID>(persistentEntity);
protected <T, ID extends Serializable> GemfireEntityInformation<T, ID> newEntityInformation(
GemfirePersistentEntity<T> persistentEntity) {
return new DefaultGemfireEntityInformation<>(persistentEntity);
}
@SuppressWarnings("unchecked")
protected <T> GemfirePersistentEntity<T> createPersistentEntity(final Class<T> domainEntityType) {
return (GemfirePersistentEntity<T>) mappingContext.getPersistentEntity(domainEntityType);
protected <T> GemfirePersistentEntity<T> newPersistentEntity(Class<T> entityType) {
return (GemfirePersistentEntity<T>) mappingContext.getPersistentEntity(entityType).orElseThrow(
() -> newIllegalStateException("Unable to resolve PersistentEntity for type [%s]", entityType));
}
@Test
public void testInterfaceBasedEntity() {
GemfireEntityInformation<Algorithm, String> entityInfo = createEntityInformation(
createPersistentEntity(Algorithm.class));
public void interfaceBasedEntity() {
GemfireEntityInformation<Algorithm, String> entityInfo =
newEntityInformation(newPersistentEntity(Algorithm.class));
assertNotNull(entityInfo);
assertEquals("Algorithms", entityInfo.getRegionName());
assertTrue(Algorithm.class.isAssignableFrom(entityInfo.getJavaType()));
assertEquals(String.class, entityInfo.getIdType());
assertEquals("QuickSort", entityInfo.getId(new QuickSort()));
assertEquals("Quick Sort", entityInfo.getId(createAlgorithm("Quick Sort")));
assertThat(entityInfo.getId(new QuickSort()).orElse(null)).isEqualTo("QuickSort");
assertThat(entityInfo.getId(newAlgorithm("Quick Sort")).orElse(null)).isEqualTo("Quick Sort");
}
@Test
public void testClassBasedEntity() {
GemfireEntityInformation<Animal, Long> entityInfo = createEntityInformation(
createPersistentEntity(Animal.class));
public void classBasedEntity() {
GemfireEntityInformation<Animal, Long> entityInfo =
newEntityInformation(newPersistentEntity(Animal.class));
assertNotNull(entityInfo);
assertEquals("Animal", entityInfo.getRegionName());
assertEquals(Animal.class, entityInfo.getJavaType());
assertEquals(Long.class, entityInfo.getIdType());
assertEquals(new Long(1l), entityInfo.getId(createAnimal(1l, "Tyger")));
assertThat(entityInfo.getId(newAnimal(1L, "Tyger")).orElse(null)).isEqualTo(1L);
}
@Test
public void testConfusedDomainEntityHavingLongId() {
GemfireEntityInformation<MyConfusedDomainEntity, Long> entityInfo = createEntityInformation(
createPersistentEntity(MyConfusedDomainEntity.class));
public void confusedDomainEntityTypedWithLongId() {
GemfireEntityInformation<ConfusedDomainEntity, Long> entityInfo =
newEntityInformation(newPersistentEntity(ConfusedDomainEntity.class));
assertNotNull(entityInfo);
assertEquals("MyConfusedDomainEntity", entityInfo.getRegionName());
assertEquals(MyConfusedDomainEntity.class, entityInfo.getJavaType());
assertEquals(ConfusedDomainEntity.class, entityInfo.getJavaType());
assertEquals(Long.class, entityInfo.getIdType());
assertEquals(new Long(123l), entityInfo.getId(new MyConfusedDomainEntity(123l)));
assertThat(entityInfo.getId(new ConfusedDomainEntity(123L)).orElse(null)).isEqualTo(123L);
}
@Test
public void testConfusedDomainEntityHavingStringId() {
GemfireEntityInformation<MyConfusedDomainEntity, String> entityInfo = createEntityInformation(
createPersistentEntity(MyConfusedDomainEntity.class));
@SuppressWarnings("all")
public void confusedDomainEntityTypedStringId() {
GemfireEntityInformation<ConfusedDomainEntity, ?> entityInfo =
newEntityInformation(newPersistentEntity(ConfusedDomainEntity.class));
assertNotNull(entityInfo);
assertEquals("MyConfusedDomainEntity", entityInfo.getRegionName());
assertEquals(MyConfusedDomainEntity.class, entityInfo.getJavaType());
assertEquals(ConfusedDomainEntity.class, entityInfo.getJavaType());
//assertEquals(String.class, entityInfo.getIdType());
assertTrue(Long.class.equals(entityInfo.getIdType()));
assertEquals(123l, entityInfo.getId(new MyConfusedDomainEntity(123l)));
assertEquals(248l, entityInfo.getId(new MyConfusedDomainEntity("248")));
assertThat(entityInfo.getId(new ConfusedDomainEntity(123L)).orElse(null)).isEqualTo(123L);
assertThat(entityInfo.getId(new ConfusedDomainEntity("248")).orElse(null)).isEqualTo(248L);
}
@SuppressWarnings("unused")
protected static class MyConfusedDomainEntity {
protected static class ConfusedDomainEntity {
@Id private Long id;
@Id
private Long id;
protected MyConfusedDomainEntity() {
this((Long) null);
}
protected MyConfusedDomainEntity(final Long id) {
protected ConfusedDomainEntity(Long id) {
this.id = id;
}
protected MyConfusedDomainEntity(final String id) {
protected ConfusedDomainEntity(String id) {
setId(id);
}
@@ -165,5 +163,4 @@ public class DefaultGemfireEntityInformationTest {
return getClass().getSimpleName();
}
}
}

View File

@@ -18,6 +18,7 @@ package org.springframework.data.gemfire.repository.query;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.springframework.data.gemfire.util.RuntimeExceptionFactory.newIllegalStateException;
import org.junit.Before;
import org.junit.Test;
@@ -39,7 +40,9 @@ public class GemfireQueryCreatorUnitTests {
@Before
@SuppressWarnings("unchecked")
public void setUp() {
entity = (GemfirePersistentEntity<Person>) new GemfireMappingContext().getPersistentEntity(Person.class);
entity = (GemfirePersistentEntity<Person>) new GemfireMappingContext().getPersistentEntity(Person.class)
.orElseThrow(() -> newIllegalStateException("Unable to resolve PersistentEntity for type [%s]",
Person.class));
}
@Test

View File

@@ -28,7 +28,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
/**
* The AlgorithmRepositoryTest class is a test suite of test cases testing the contract and functionality of GemFire's
@@ -42,7 +42,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
* @since 1.4.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("unused")
public class AlgorithmRepositoryTest {
@@ -54,7 +54,7 @@ public class AlgorithmRepositoryTest {
private Region algorithmsRegion;
@Test
public void testAlgorithmsRepo() {
public void algorithmsRepositoryFunctionsCorrectly() {
assertNotNull("A reference to the AlgorithmRepository was not properly configured!", algorithmRepo);
assertNotNull("A reference to the 'Algorithms' GemFire Cache Region was not properly configured!",
algorithmsRegion);
@@ -95,5 +95,4 @@ public class AlgorithmRepositoryTest {
protected static final class HeapSort extends AbstractAlgorithm {
}
}

View File

@@ -16,14 +16,15 @@
package org.springframework.data.gemfire.repository.sample;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
/**
* The AnimalRepositoryTest class is a test suite of test cases testing the functionality behind PR #55 involving
@@ -39,7 +40,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @link https://github.com/spring-projects/spring-data-gemfire/pull/55
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@SuppressWarnings("unused")
public class AnimalRepositoryTest {
@@ -49,7 +50,7 @@ public class AnimalRepositoryTest {
@Autowired
private DogRepository dogRepo;
protected static Animal createAnimal(final long id, final String name) {
protected static Animal newAnimal(long id, String name) {
Animal animal = new Animal();
animal.setId(id);
animal.setName(name);
@@ -58,42 +59,42 @@ public class AnimalRepositoryTest {
@Test
public void testEntityStoredInMultipleRegions() {
Animal felix = createAnimal(1, "Felix");
Animal leo = createAnimal(2, "Leo");
Animal cerberus = createAnimal(3, "Cerberus");
Animal fido = createAnimal(1, "Fido");
Animal felix = newAnimal(1, "Felix");
Animal leo = newAnimal(2, "Leo");
Animal cerberus = newAnimal(3, "Cerberus");
Animal fido = newAnimal(1, "Fido");
assertNotNull(catRepo.save(felix));
assertNotNull(catRepo.save(leo));
assertNotNull(catRepo.save(cerberus));
assertNotNull(dogRepo.save(fido));
assertNotNull(dogRepo.save(cerberus));
assertEquals(3L, catRepo.count());
assertEquals(2L, dogRepo.count());
assertThat(catRepo.save(felix)).isNotNull();
assertThat(catRepo.save(leo)).isNotNull();
assertThat(catRepo.save(cerberus)).isNotNull();
assertThat(dogRepo.save(fido)).isNotNull();
assertThat(dogRepo.save(cerberus)).isNotNull();
assertThat(catRepo.count()).isEqualTo(3L);
assertThat(dogRepo.count()).isEqualTo(2L);
Animal foundFelix = catRepo.findOne(1L);
Optional<Animal> foundFelix = catRepo.findOne(1L);
assertEquals(felix, foundFelix);
assertThat(foundFelix.isPresent()).isTrue();
assertThat(foundFelix.get()).isEqualTo(felix);
Animal foundLeo = catRepo.findBy("Leo");
assertEquals(leo, foundLeo);
assertThat(foundLeo).isEqualTo(leo);
Animal foundCerberusTheCat = catRepo.findByName("Cerberus");
assertEquals(cerberus, foundCerberusTheCat);
assertEquals(foundCerberusTheCat, catRepo.findBy("Cerberus"));
assertEquals(foundCerberusTheCat, catRepo.findOne(3L));
assertThat(foundCerberusTheCat).isEqualTo(cerberus);
assertThat(catRepo.findBy("Cerberus")).isEqualTo(foundCerberusTheCat);
assertThat(catRepo.findOne(3L).orElse(null)).isEqualTo(foundCerberusTheCat);
Animal foundFido = dogRepo.findBy("Fido");
assertEquals(fido, foundFido);
assertThat(foundFido).isEqualTo(fido);
Animal foundCerberusTheDog = dogRepo.findByName("Cerberus");
assertEquals(cerberus, foundCerberusTheDog);
assertEquals(foundCerberusTheDog, dogRepo.findBy("Cerberus"));
assertEquals(foundCerberusTheDog, dogRepo.findOne(3L));
assertThat(foundCerberusTheDog).isEqualTo(cerberus);
assertThat(dogRepo.findBy("Cerberus")).isEqualTo(foundCerberusTheDog);
assertThat(dogRepo.findOne(3L).orElse(null)).isEqualTo(foundCerberusTheDog);
}
}

View File

@@ -16,10 +16,7 @@
package org.springframework.data.gemfire.repository.sample;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
@@ -47,7 +44,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SuppressWarnings("unused")
public class RepositoryQueriesWithJoinsIntegrationTest {
private static final AtomicLong ID_SEQUENCE = new AtomicLong(0l);
private static final AtomicLong ID_SEQUENCE = new AtomicLong(0L);
@Autowired
private AccountRepository accountRepo;
@@ -55,38 +52,33 @@ public class RepositoryQueriesWithJoinsIntegrationTest {
@Autowired
private CustomerRepository customerRepo;
protected Account createAccount(final Customer customer, final String number) {
protected Account newAccount(Customer customer, String number) {
Account account = new Account(ID_SEQUENCE.incrementAndGet(), customer);
account.setNumber(number);
return account;
}
protected Customer createCustomer(final String firstName, final String lastName) {
protected Customer newCustomer(String firstName, String lastName) {
Customer customer = new Customer(firstName, lastName);
customer.setId(ID_SEQUENCE.incrementAndGet());
return customer;
}
@Test
public void testJoinQueries() {
Customer jonDoe = customerRepo.save(createCustomer("Jon", "Doe"));
Customer janeDoe = customerRepo.save(createCustomer("Jane", "Doe"));
Customer jackHandy = customerRepo.save(createCustomer("Jack", "Handy"));
public void joinQueriesWork() {
Customer jonDoe = customerRepo.save(newCustomer("Jon", "Doe"));
Customer janeDoe = customerRepo.save(newCustomer("Jane", "Doe"));
Customer jackHandy = customerRepo.save(newCustomer("Jack", "Handy"));
Account jonAccountOne = accountRepo.save(createAccount(jonDoe, "1"));
Account jonAccountTwo = accountRepo.save(createAccount(jonDoe, "2"));
Account janeAccount = accountRepo.save(createAccount(janeDoe, "1"));
Account jonAccountOne = accountRepo.save(newAccount(jonDoe, "1"));
Account jonAccountTwo = accountRepo.save(newAccount(jonDoe, "2"));
Account janeAccount = accountRepo.save(newAccount(janeDoe, "1"));
List<Customer> actualCustomersWithAccounts = customerRepo.findCustomersWithAccounts();
List<Customer> expectedCustomersWithAccounts = Arrays.asList(jonDoe, janeDoe);
assertNotNull(actualCustomersWithAccounts);
assertFalse(String.format("Expected Customers (%1$s)!", expectedCustomersWithAccounts),
actualCustomersWithAccounts.isEmpty());
assertEquals(String.format("Expected Customers (%1$s); but was (%2$s)!", expectedCustomersWithAccounts, actualCustomersWithAccounts),
2, actualCustomersWithAccounts.size());
assertTrue(String.format("Expected Customers (%1$s); but was (%2$s)!", expectedCustomersWithAccounts, actualCustomersWithAccounts),
actualCustomersWithAccounts.containsAll(expectedCustomersWithAccounts));
assertThat(actualCustomersWithAccounts).isNotNull();
assertThat(actualCustomersWithAccounts).hasSize(2);
assertThat(actualCustomersWithAccounts).containsAll(expectedCustomersWithAccounts);
}
}

View File

@@ -16,6 +16,7 @@
package org.springframework.data.gemfire.repository.sample;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -60,11 +61,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SuppressWarnings("unused")
public class SubRegionRepositoryIntegrationTest {
private static final Map<String, RootUser> ADMIN_USER_DATA = new HashMap<String, RootUser>(5, 0.90f);
private static final Map<String, RootUser> ADMIN_USER_DATA = new HashMap<>(5, 0.90f);
private static final Map<String, GuestUser> GUEST_USER_DATA = new HashMap<String, GuestUser>(3, 0.90f);
private static final Map<String, GuestUser> GUEST_USER_DATA = new HashMap<>(3, 0.90f);
private static final Map<String, Programmer> PROGRAMMER_USER_DATA = new HashMap<String, Programmer>(23, 0.90f);
private static final Map<String, Programmer> PROGRAMMER_USER_DATA = new HashMap<>(23, 0.90f);
static {
createAdminUser("supertool");
@@ -206,7 +207,7 @@ public class SubRegionRepositoryIntegrationTest {
@Test
public void testSubregionRepositoryInteractions() {
assertEquals(PROGRAMMER_USER_DATA.get("JamesGosling"), programmersRepo.findOne("JamesGosling"));
assertThat(programmersRepo.findOne("JamesGosling").orElse(null)).isEqualTo(PROGRAMMER_USER_DATA.get("JamesGosling"));
List<Programmer> javaProgrammers = programmersRepo.findDistinctByProgrammingLanguageOrderByUsernameAsc("Java");
@@ -222,9 +223,9 @@ public class SubRegionRepositoryIntegrationTest {
assertEquals(1, groovyProgrammers.size());
assertEquals(groovyProgrammers, getProgrammers("JamesStrachan"));
programmersRepo.save(new Wrapper<Programmer, String>(createProgrammer("RodJohnson", "Java"), "RodJohnson"));
programmersRepo.save(new Wrapper<Programmer, String>(createProgrammer("GuillaumeLaforge", "Groovy"), "GuillaumeLaforge"));
programmersRepo.save(new Wrapper<Programmer, String>(createProgrammer("GraemeRocher", "Groovy"), "GraemeRocher"));
programmersRepo.save(new Wrapper<>(createProgrammer("RodJohnson", "Java"), "RodJohnson"));
programmersRepo.save(new Wrapper<>(createProgrammer("GuillaumeLaforge", "Groovy"), "GuillaumeLaforge"));
programmersRepo.save(new Wrapper<>(createProgrammer("GraemeRocher", "Groovy"), "GraemeRocher"));
javaProgrammers = programmersRepo.findDistinctByProgrammingLanguageOrderByUsernameAsc("Java");
@@ -255,8 +256,8 @@ public class SubRegionRepositoryIntegrationTest {
@Test
public void testIdenticallyNamedSubregionDataAccess() {
assertEquals(getAdminUser("supertool"), adminUserRepo.findOne("supertool"));
assertEquals(getGuestUser("joeblow"), guestUserRepo.findOne("joeblow"));
assertThat(adminUserRepo.findOne("supertool").orElse(null)).isEqualTo(getAdminUser("supertool"));
assertThat(guestUserRepo.findOne("joeblow").orElse(null)).isEqualTo(getGuestUser("joeblow"));
List<RootUser> rootUsers = adminUserRepo.findDistinctByUsername("zeus");
@@ -273,5 +274,4 @@ public class SubRegionRepositoryIntegrationTest {
assertEquals(1, guestUsers.size());
assertEquals(getGuestUser("bubba"), guestUsers.get(0));
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.repository.support;
import static org.hamcrest.Matchers.hasItem;
@@ -48,14 +49,20 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
public abstract class AbstractGemfireRepositoryFactoryIntegrationTests {
@Autowired
List<Region<?, ?>> regions;
private List<Region<?, ?>> regions;
Person dave, carter, boyd, stefan, leroi, jeff, oliverAugust;
PersonRepository repository;
private Person boyd;
private Person carter;
private Person dave;
private Person jeff;
private Person leroi;
private Person oliverAugust;
private Person stefan;
private PersonRepository repository;
@Before
public void setUp() {
dave = new Person(1L, "Dave", "Matthews");
carter = new Person(2L, "Carter", "Beauford");
boyd = new Person(3L, "Boyd", "Tinsley");
@@ -64,9 +71,8 @@ public abstract class AbstractGemfireRepositoryFactoryIntegrationTests {
jeff = new Person(6L, "Jeff", "Coffin");
oliverAugust = new Person(7L, "Oliver August", "Matthews");
GemfireMappingContext context = new GemfireMappingContext();
Regions regions = new Regions(this.regions, new GemfireMappingContext());
Regions regions = new Regions(this.regions, context);
GemfireTemplate template = new GemfireTemplate(regions.getRegion(Person.class));
template.put(dave.id, dave);
@@ -184,10 +190,10 @@ public abstract class AbstractGemfireRepositoryFactoryIntegrationTests {
assertResultsFound(repository.findByFirstnameLike("Da%"), dave);
}
private <T> void assertResultsFound(Iterable<T> result, T... expected) {
@SafeVarargs
private static <T> void assertResultsFound(Iterable<T> result, T... expected) {
assertThat(result, is(notNullValue()));
assertThat(result, is(Matchers.<T> iterableWithSize(expected.length)));
assertThat(result, is(Matchers.iterableWithSize(expected.length)));
for (T element : expected) {
assertThat(result, hasItem(element));

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire.repository.support;
import static org.hamcrest.CoreMatchers.is;
@@ -36,26 +37,25 @@ import org.springframework.test.context.ContextConfiguration;
* Integration test for {@link GemfireRepositoryFactory}.
*
* @author Oliver Gierke
* @author John Blum
*/
@ContextConfiguration("../config/repo-context.xml")
public class GemfireRepositoryFactoryIntegrationTests extends AbstractGemfireRepositoryFactoryIntegrationTests {
@Autowired ApplicationContext context;
@Autowired GemfireMappingContext mappingContext;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private GemfireMappingContext mappingContext;
@Override
protected PersonRepository getRepository(Regions regions) {
GemfireRepositoryFactory factory = new GemfireRepositoryFactory(regions, mappingContext);
return factory.getRepository(PersonRepository.class);
return new GemfireRepositoryFactory(regions, mappingContext).getRepository(PersonRepository.class);
}
@Test(expected = IllegalStateException.class)
@SuppressWarnings({ "unchecked", "rawtypes" })
public void throwsExceptionIfReferencedRegionIsNotConfigured() {
GemfireRepositoryFactory factory = new GemfireRepositoryFactory((Iterable) Collections.emptySet(), mappingContext);
factory.getRepository(PersonRepository.class);
new GemfireRepositoryFactory(Collections.emptySet(), mappingContext).getRepository(PersonRepository.class);
}
/**
@@ -63,9 +63,9 @@ public class GemfireRepositoryFactoryIntegrationTests extends AbstractGemfireRep
*/
@Test
public void exposesPersistentProperty() {
Repositories repositories = new Repositories(context);
Repositories repositories = new Repositories(applicationContext);
PersistentEntity<?, ?> entity = repositories.getPersistentEntity(Person.class);
assertThat(entity, is(notNullValue()));
}
}

View File

@@ -148,13 +148,13 @@ public class SimpleGemfireRepositoryIntegrationTests {
assertThat(repository.save(oliverGierke)).isEqualTo(oliverGierke);
assertThat(repository.count()).isEqualTo(1L);
assertThat(repository.findOne(oliverGierke.getId())).isEqualTo(oliverGierke);
assertThat(repository.findOne(oliverGierke.getId()).orElse(null)).isEqualTo(oliverGierke);
assertThat(repository.findAll()).isEqualTo(Collections.singletonList(oliverGierke));
repository.delete(oliverGierke);
assertThat(repository.count()).isEqualTo(0L);
assertThat(repository.findOne(oliverGierke.getId())).isNull();
assertThat(repository.findOne(oliverGierke.getId()).orElse(null)).isNull();
assertThat(repository.findAll()).isEmpty();
}

View File

@@ -19,11 +19,6 @@ package org.springframework.data.gemfire.repository.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
@@ -43,6 +38,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
@@ -124,18 +120,20 @@ public class SimpleGemfireRepositoryUnitTests {
protected EntityInformation<Animal, Long> mockEntityInformation() {
EntityInformation<Animal, Long> mockEntityInformation = mock(EntityInformation.class);
doAnswer(new Answer<Long>() {
doAnswer(new Answer<Optional<Long>>() {
private final AtomicLong idSequence = new AtomicLong(0L);
@Override
public Long answer(InvocationOnMock invocation) throws Throwable {
public Optional<Long> answer(InvocationOnMock invocation) throws Throwable {
Animal argument = invocation.getArgumentAt(0, Animal.class);
Long id = argument.getId();
id = (id != null ? id : idSequence.incrementAndGet());
argument.setId(id);
return id;
argument.setId(resolveId(argument.getId()));
return Optional.of(argument.getId());
}
private Long resolveId(Long id) {
return (id != null ? id : idSequence.incrementAndGet());
}
}).when(mockEntityInformation).getId(any(Animal.class));
return mockEntityInformation;
@@ -187,23 +185,23 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testSave() {
public void saveEntityIsCorrect() {
Region<Long, Animal> mockRegion = mockRegion();
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
Animal dog = repository.save(newAnimal("dog"));
assertNotNull(dog);
assertEquals(1L, dog.getId().longValue());
assertEquals("dog", dog.getName());
assertThat(dog).isNotNull();
assertThat(dog.getId().longValue()).isEqualTo(1L);
assertThat(dog.getName()).isEqualTo("dog");
verify(mockRegion, times(1)).put(eq(1L), eq(dog));
}
@Test
public void testSaveEntities() {
public void saveEntitiesIsCorrect() {
List<Animal> animals = new ArrayList<>(3);
animals.add(newAnimal("bird"));
@@ -212,26 +210,26 @@ public class SimpleGemfireRepositoryUnitTests {
Region<Long, Animal> mockRegion = mockRegion();
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
Iterable<Animal> savedAnimals = repository.save(animals);
assertNotNull(savedAnimals);
assertThat(savedAnimals).isNotNull();
verify(mockRegion, times(1)).putAll(eq(asMap(savedAnimals)));
}
@Test
public void testSaveWrapper() {
public void saveWrapperIsCorrect() {
Animal dog = newAnimal(1L, "dog");
Wrapper dogWrapper = new Wrapper(dog, dog.getId());
Region<Long, Animal> mockRegion = mockRegion();
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
assertThat(repository.save(dogWrapper)).isEqualTo(dog);
@@ -258,7 +256,7 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testExists() {
public void existsIsCorrect() {
Animal dog = newAnimal(1L, "dog");
Region<Long, Animal> mockRegion = mockRegion();
@@ -266,15 +264,15 @@ public class SimpleGemfireRepositoryUnitTests {
when(mockRegion.get(any(Long.class))).then(
invocation -> (dog.getId().equals(invocation.getArguments()[0]) ? dog : null));
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
assertTrue(repository.exists(1L));
assertFalse(repository.exists(10L));
assertThat(repository.exists(1L)).isTrue();
assertThat(repository.exists(10L)).isFalse();
}
@Test
public void testFindOne() {
public void findOneIsCorrect() {
Animal dog = newAnimal(1L, "dog");
Region<Long, Animal> mockRegion = mockRegion();
@@ -282,17 +280,18 @@ public class SimpleGemfireRepositoryUnitTests {
when(mockRegion.get(any(Long.class))).then(
invocation -> (dog.getId().equals(invocation.getArguments()[0]) ? dog : null));
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
assertEquals(dog, repository.findOne(1L));
assertNull(repository.findOne(10L));
assertThat(repository.findOne(1L).orElse(null)).isEqualTo(dog);
assertThat(repository.findOne(10L).isPresent()).isFalse();
}
@Test
public void testFindAll() {
Map<Long, Animal> animals = Stream.of(newAnimal(1L, "bird"), newAnimal(2L, "cat"),
newAnimal(3L, "dog")).collect(Collectors.toMap(Animal::getId, Function.identity()));
public void findAllIsCorrect() {
Map<Long, Animal> animals =
Stream.of(newAnimal(1L, "bird"), newAnimal(2L, "cat"), newAnimal(3L, "dog"))
.collect(Collectors.toMap(Animal::getId, Function.identity()));
Region<Long, Animal> mockRegion = mockRegion();
@@ -330,8 +329,8 @@ public class SimpleGemfireRepositoryUnitTests {
return result;
});
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
Collection<Animal> animalsFound = repository.findAll(Arrays.asList(1L, 2L, 3L));
@@ -343,8 +342,9 @@ public class SimpleGemfireRepositoryUnitTests {
@Test
public void findAllWithIdsReturnsPartialMatches() {
Map<Long, Animal> animals = Stream.of(newAnimal(1L, "bird"), newAnimal(2L, "cat"),
newAnimal(3L, "dog")).collect(Collectors.toMap(Animal::getId, Function.identity()));
Map<Long, Animal> animals =
Stream.of(newAnimal(1L, "bird"), newAnimal(2L, "cat"), newAnimal(3L, "dog"))
.collect(Collectors.toMap(Animal::getId, Function.identity()));
Region<Long, Animal> mockRegion = mockRegion();
@@ -359,8 +359,8 @@ public class SimpleGemfireRepositoryUnitTests {
return result;
});
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
Collection<Animal> animalsFound = repository.findAll(Arrays.asList(0L, 1L, 2L, 4L));
@@ -372,11 +372,11 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testDeleteById() {
public void deleteByIdIsCorrect() {
Region<Long, Animal> mockRegion = mockRegion();
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
repository.delete(1L);
@@ -384,11 +384,11 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testDeleteEntity() {
public void deleteEntityIsCorrect() {
Region<Long, Animal> mockRegion = mockRegion();
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
repository.delete(newAnimal(1L, "dog"));
@@ -396,11 +396,11 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testDeleteEntities() {
public void deleteEntitiesIsCorrect() {
Region<Long, Animal> mockRegion = mockRegion();
SimpleGemfireRepository<Animal, Long> repository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> repository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
repository.delete(Arrays.asList(newAnimal(1L, "bird"), newAnimal(2L, "cat"),
newAnimal(3L, "dog")));
@@ -411,13 +411,13 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testDeleteAllWithClear() {
public void deleteAllWithClear() {
Cache mockCache = mockCache("MockCache", false);
Region<Long, Animal> mockRegion = mockRegion("MockRegion", mockCache, DataPolicy.REPLICATE);
SimpleGemfireRepository<Animal, Long> gemfireRepository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> gemfireRepository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
gemfireRepository.deleteAll();
@@ -428,7 +428,7 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testDeleteAllWithKeysWhenClearThrowsException() {
public void deleteAllWithKeysWhenClearThrowsException() {
Cache mockCache = mockCache("MockCache", false);
Region<Long, Animal> mockRegion = mockRegion("MockRegion", mockCache, DataPolicy.PERSISTENT_REPLICATE);
@@ -438,8 +438,8 @@ public class SimpleGemfireRepositoryUnitTests {
doThrow(new UnsupportedOperationException("Not Implemented!")).when(mockRegion).clear();
when(mockRegion.keySet()).thenReturn(keys);
SimpleGemfireRepository<Animal, Long> gemfireRepository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> gemfireRepository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
gemfireRepository.deleteAll();
@@ -451,7 +451,7 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testDeleteAllWithKeysWhenPartitionRegion() {
public void deleteAllWithKeysWhenPartitionRegion() {
Cache mockCache = mockCache("MockCache", false);
Region<Long, Animal> mockRegion = mockRegion("MockRegion", mockCache, DataPolicy.PERSISTENT_PARTITION);
@@ -460,8 +460,8 @@ public class SimpleGemfireRepositoryUnitTests {
when(mockRegion.keySet()).thenReturn(keys);
SimpleGemfireRepository<Animal, Long> gemfireRepository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> gemfireRepository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
gemfireRepository.deleteAll();
@@ -473,7 +473,7 @@ public class SimpleGemfireRepositoryUnitTests {
}
@Test
public void testDeleteAllWithKeysWhenTransactionPresent() {
public void deleteAllWithKeysWhenTransactionPresent() {
Cache mockCache = mockCache("MockCache", true);
Region<Long, Animal> mockRegion = mockRegion("MockRegion", mockCache, DataPolicy.REPLICATE);
@@ -482,8 +482,8 @@ public class SimpleGemfireRepositoryUnitTests {
when(mockRegion.keySet()).thenReturn(keys);
SimpleGemfireRepository<Animal, Long> gemfireRepository = new SimpleGemfireRepository<>(
newGemfireTemplate(mockRegion), mockEntityInformation());
SimpleGemfireRepository<Animal, Long> gemfireRepository =
new SimpleGemfireRepository<>(newGemfireTemplate(mockRegion), mockEntityInformation());
gemfireRepository.deleteAll();