DATACMNS-131 - Formatting.

This commit is contained in:
Oliver Gierke
2012-02-03 11:50:12 +01:00
parent 4fcb4a7649
commit bfd306dba7
79 changed files with 469 additions and 739 deletions

View File

@@ -32,12 +32,13 @@ import org.springframework.data.mapping.PersistentEntity;
*/
@Documented
@Inherited
@Target({ElementType.TYPE})
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeAlias {
/**
* The type alias to be used when persisting
*
* @return
*/
String value();

View File

@@ -44,20 +44,22 @@ public class DefaultTypeMapper<S> implements TypeMapper<S> {
}
public DefaultTypeMapper(TypeAliasAccessor<S> accessor, List<? extends TypeInformationMapper> mappers) {
this(accessor, null, mappers);
}
public DefaultTypeMapper(TypeAliasAccessor<S> accessor, MappingContext<? extends PersistentEntity<?, ?>, ?> mappingContext, List<? extends TypeInformationMapper> additionalMappers) {
public DefaultTypeMapper(TypeAliasAccessor<S> accessor,
MappingContext<? extends PersistentEntity<?, ?>, ?> mappingContext,
List<? extends TypeInformationMapper> additionalMappers) {
Assert.notNull(accessor);
List<TypeInformationMapper> mappers = new ArrayList<TypeInformationMapper>(additionalMappers.size() + 1);
if (mappingContext != null) {
mappers.add(new ConfigurableTypeInformationMapper(mappingContext));
mappers.add(new ConfigurableTypeInformationMapper(mappingContext));
}
mappers.addAll(additionalMappers);
this.mappers = Collections.unmodifiableList(mappers);
this.accessor = accessor;
}
@@ -91,11 +93,11 @@ public class DefaultTypeMapper<S> implements TypeMapper<S> {
Assert.notNull(source);
Class<?> documentsTargetType = getDefaultedTypeToBeUsed(source);
if (documentsTargetType == null) {
return basicType;
}
Class<T> rawType = basicType == null ? null : basicType.getType();
boolean isMoreConcreteCustomType = rawType == null ? true : rawType.isAssignableFrom(documentsTargetType)
@@ -114,10 +116,11 @@ public class DefaultTypeMapper<S> implements TypeMapper<S> {
private Class<?> getDefaultedTypeToBeUsed(S source) {
TypeInformation<?> documentsTargetTypeInformation = readType(source);
documentsTargetTypeInformation = documentsTargetTypeInformation == null ? getFallbackTypeFor(source) : documentsTargetTypeInformation;
documentsTargetTypeInformation = documentsTargetTypeInformation == null ? getFallbackTypeFor(source)
: documentsTargetTypeInformation;
return documentsTargetTypeInformation == null ? null : documentsTargetTypeInformation.getType();
}
/**
* Returns the type fallback {@link TypeInformation} in case none could be extracted from the given source.
*

View File

@@ -33,5 +33,6 @@ public interface EntityInstantiator {
* @param provider will not be {@literal null}.
* @return
*/
<T, E extends PersistentEntity<? extends T, P>, P extends PersistentProperty<P>> T createInstance(E entity, ParameterValueProvider<P> provider);
<T, E extends PersistentEntity<? extends T, P>, P extends PersistentProperty<P>> T createInstance(E entity,
ParameterValueProvider<P> provider);
}

View File

@@ -17,7 +17,7 @@ package org.springframework.data.convert;
/**
* Interface to read object from store specific sources.
*
*
* @author Oliver Gierke
*/
public interface EntityReader<T, S> {

View File

@@ -15,7 +15,6 @@
*/
package org.springframework.data.convert;
/**
* Interface to write objects into store specific sinks.
*

View File

@@ -17,22 +17,22 @@ package org.springframework.data.convert;
/**
* Interface to abstract implementations of how to access a type alias from a given source or sink.
*
*
* @author Oliver Gierke
*/
public interface TypeAliasAccessor<S> {
/**
* Reads the type alias to be used from the given source.
*
*
* @param source
* @return
*/
Object readAliasFrom(S source);
/**
* Writes the given type alias to the given sink.
*
*
* @param sink
* @param alias
*/

View File

@@ -19,7 +19,7 @@ import org.springframework.data.util.TypeInformation;
/**
* Interface to abstract the mapping from a type alias to the actual type.
*
*
* @author Oliver Gierke
*/
public interface TypeInformationMapper {
@@ -31,10 +31,10 @@ public interface TypeInformationMapper {
* @return
*/
TypeInformation<?> resolveTypeFrom(Object alias);
/**
* Returns the alias to be used for the given {@link TypeInformation}.
*
*
* @param type
* @return
*/

View File

@@ -167,10 +167,9 @@ public class Sort implements Iterable<org.springframework.data.domain.Sort.Order
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
@@ -180,10 +179,9 @@ public class Sort implements Iterable<org.springframework.data.domain.Sort.Order
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
@@ -217,14 +215,15 @@ public class Sort implements Iterable<org.springframework.data.domain.Sort.Order
}
/**
* PropertyPath implements the pairing of an {@code Order} and a property. It is used to provide input for {@link Sort}
* PropertyPath implements the pairing of an {@code Order} and a property. It is used to provide input for
* {@link Sort}
*
* @author Oliver Gierke
*/
public static class Order implements Serializable {
private static final long serialVersionUID = 1522511010900108987L;
private final Direction direction;
private final String property;

View File

@@ -45,8 +45,8 @@ public interface PersistentEntity<T, P extends PersistentProperty<P>> {
* {@link PersistentEntity}.
*
* @param property
* @return true if the given {@link PersistentProperty} is referred to by a constructor argument or {@literal false} if
* not or {@literal null}.
* @return true if the given {@link PersistentProperty} is referred to by a constructor argument or {@literal false}
* if not or {@literal null}.
*/
boolean isConstructorArgument(P property);

View File

@@ -43,7 +43,7 @@ public interface PersistentProperty<P extends PersistentProperty<P>> {
/**
* Returns the {@link PropertyDescriptor} backing the {@link PersistentProperty}.
*
*
* @return
*/
PropertyDescriptor getPropertyDescriptor();
@@ -60,7 +60,7 @@ public interface PersistentProperty<P extends PersistentProperty<P>> {
* @return
*/
boolean isIdProperty();
/**
* Returns whether the property is a {@link Collection}, {@link Iterable} or an array.
*
@@ -88,8 +88,7 @@ public interface PersistentProperty<P extends PersistentProperty<P>> {
* @return
*/
boolean isTransient();
boolean shallBePersisted();
/**
@@ -98,7 +97,7 @@ public interface PersistentProperty<P extends PersistentProperty<P>> {
* @return
*/
boolean isAssociation();
/**
* Returns the component type of the type if it is a {@link java.util.Collection}. Will return the type of the key if
* the property is a {@link java.util.Map}.

View File

@@ -100,7 +100,7 @@ public class PreferredConstructor<T, P extends PersistentProperty<P>> {
public boolean isExplicitlyAnnotated() {
return constructor.isAnnotationPresent(PersistenceConstructor.class);
}
/**
* Returns whether the given {@link PersistentProperty} is referenced in a constructor argument of the
* {@link PersistentEntity} backing this {@link MappedConstructor}.
@@ -199,7 +199,7 @@ public class PreferredConstructor<T, P extends PersistentProperty<P>> {
public String getSpelExpression() {
return key;
}
/**
* Returns whether the constructor parameter is equipped with a SpEL expression.
*
@@ -208,7 +208,7 @@ public class PreferredConstructor<T, P extends PersistentProperty<P>> {
public boolean hasSpelExpression() {
return StringUtils.hasText(getSpelExpression());
}
/**
* Returns whether the {@link Parameter} maps the given {@link PersistentProperty}.
*
@@ -216,7 +216,7 @@ public class PreferredConstructor<T, P extends PersistentProperty<P>> {
* @return
*/
boolean maps(P property) {
P referencedProperty = entity == null ? null : entity.getPersistentProperty(name);
return property == null ? false : property.equals(referencedProperty);
}

View File

@@ -138,8 +138,8 @@ public class PropertyPath implements Iterable<PropertyPath> {
}
/**
* Returns whether there is a nested {@link PropertyPath}. If this returns {@literal true} you can expect {@link #next()}
* to return a non- {@literal null} value.
* Returns whether there is a nested {@link PropertyPath}. If this returns {@literal true} you can expect
* {@link #next()} to return a non- {@literal null} value.
*
* @return
*/
@@ -208,7 +208,7 @@ public class PropertyPath implements Iterable<PropertyPath> {
*/
public Iterator<PropertyPath> iterator() {
return new Iterator<PropertyPath>() {
private PropertyPath current = PropertyPath.this;
public boolean hasNext() {
@@ -226,7 +226,7 @@ public class PropertyPath implements Iterable<PropertyPath> {
}
};
}
/**
* Extracts the {@link PropertyPath} chain from the given source {@link String} and type.
*
@@ -243,7 +243,7 @@ public class PropertyPath implements Iterable<PropertyPath> {
* Extracts the {@link PropertyPath} chain from the given source {@link String} and {@link TypeInformation}.
*
* @param source must not be {@literal null}.
* @param type
* @param type
* @return
*/
public static PropertyPath from(String source, TypeInformation<?> type) {
@@ -287,10 +287,10 @@ public class PropertyPath implements Iterable<PropertyPath> {
}
/**
* Factory method to create a new {@link PropertyPath} for the given {@link String} and owning type. It will inspect the
* given source for camel-case parts and traverse the {@link String} along its parts starting with the entire one and
* chewing off parts from the right side then. Whenever a valid property for the given class is found, the tail will
* be traversed for subordinary properties of the just found one and so on.
* Factory method to create a new {@link PropertyPath} for the given {@link String} and owning type. It will inspect
* the given source for camel-case parts and traverse the {@link String} along its parts starting with the entire one
* and chewing off parts from the right side then. Whenever a valid property for the given class is found, the tail
* will be traversed for subordinary properties of the just found one and so on.
*
* @param source
* @param type
@@ -303,8 +303,8 @@ public class PropertyPath implements Iterable<PropertyPath> {
/**
* Tries to look up a chain of {@link PropertyPath}s by trying the givne source first. If that fails it will split the
* source apart at camel case borders (starting from the right side) and try to look up a {@link PropertyPath} from the
* calculated head and recombined new tail and additional tail.
* source apart at camel case borders (starting from the right side) and try to look up a {@link PropertyPath} from
* the calculated head and recombined new tail and additional tail.
*
* @param source
* @param type

View File

@@ -176,7 +176,7 @@ class DefaultPersistentPropertyPath<T extends PersistentProperty<T>> implements
}
return new DefaultPersistentPropertyPath<T>(properties.subList(0, size - 1));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mapping.context.PersistentPropertyPath#getLength()

View File

@@ -97,8 +97,9 @@ public interface PersistentPropertyPath<T extends PersistentProperty<T>> extends
PersistentPropertyPath<T> getExtensionForBaseOf(PersistentPropertyPath<T> base);
/**
* Returns the parent path of the current {@link PersistentPropertyPath}, i.e. the path without the leaf property. This happens up to the base
* property. So for a direct property reference calling this method will result in returning the property.
* Returns the parent path of the current {@link PersistentPropertyPath}, i.e. the path without the leaf property.
* This happens up to the base property. So for a direct property reference calling this method will result in
* returning the property.
*
* @return
*/

View File

@@ -176,7 +176,7 @@ public abstract class AbstractPersistentProperty<P extends PersistentProperty<P>
}
protected boolean isEntity() {
boolean isComplexType = !simpleTypeHolder.isSimpleType(information.getActualType().getType());
return isComplexType && !isTransient() && !isCollectionLike() && !isMap();
}

View File

@@ -40,7 +40,7 @@ import org.springframework.util.StringUtils;
*/
public class BasicPersistentEntity<T, P extends PersistentProperty<P>> implements MutablePersistentEntity<T, P> {
private final PreferredConstructor<T, P> constructor;
private final PreferredConstructor<T, P> constructor;
private final TypeInformation<T> information;
private final Set<P> properties;
private final Set<Association<P>> associations;
@@ -65,16 +65,16 @@ public class BasicPersistentEntity<T, P extends PersistentProperty<P>> implement
* @param comparator
*/
public BasicPersistentEntity(TypeInformation<T> information, Comparator<P> comparator) {
Assert.notNull(information);
this.information = information;
this.properties = comparator == null ? new HashSet<P>() : new TreeSet<P>(comparator);
this.constructor = new PreferredConstructorDiscoverer<T, P>(information, this).getConstructor();
this.associations = comparator == null ? new HashSet<Association<P>>() : new TreeSet<Association<P>>(
new AssociationComparator<P>(comparator));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mapping.PersistentEntity#getPersistenceConstructor()
@@ -82,7 +82,7 @@ public class BasicPersistentEntity<T, P extends PersistentProperty<P>> implement
public PreferredConstructor<T, P> getPersistenceConstructor() {
return constructor;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mapping.PersistentEntity#isConstructorArgument(org.springframework.data.mapping.PersistentProperty)
@@ -153,13 +153,13 @@ public class BasicPersistentEntity<T, P extends PersistentProperty<P>> implement
public Class<T> getType() {
return information.getType();
}
/*
* (non-Javadoc)
* @see org.springframework.data.mapping.PersistentEntity#getTypeAlias()
*/
public Object getTypeAlias() {
TypeAlias alias = getType().getAnnotation(TypeAlias.class);
return alias == null ? null : StringUtils.hasText(alias.value()) ? alias.value() : null;
}

View File

@@ -131,7 +131,7 @@ public class BeanWrapper<E extends PersistentEntity<T, ?>, T> {
Field field = property.getField();
Method getter = (null != property.getPropertyDescriptor() ? property.getPropertyDescriptor().getReadMethod()
: null);
if (fieldAccessOnly || null == getter) {
ReflectionUtils.makeAccessible(field);
obj = ReflectionUtils.getField(field, bean);

View File

@@ -24,7 +24,7 @@ import org.springframework.data.mapping.PreferredConstructor.Parameter;
* @author Oliver Gierke
*/
public interface ParameterValueProvider<P extends PersistentProperty<P>> {
/**
* Returns the value to be used for the given {@link Parameter} (usually when entity instances are created).
*

View File

@@ -19,7 +19,7 @@ import org.springframework.data.mapping.PersistentProperty;
/**
* SPI for components to provide values for as {@link PersistentProperty}.
*
*
* @author Oliver Gierke
*/
public interface PropertyValueProvider<P extends PersistentProperty<P>> {

View File

@@ -17,7 +17,7 @@ package org.springframework.data.mapping.model;
/**
* SPI for components that can evaluate Spring EL expressions.
*
*
* @author Oliver Gierke
*/
public interface SpELExpressionEvaluator {

View File

@@ -7,6 +7,7 @@ import org.springframework.data.convert.EntityInstantiator;
* <p/>
* Can be implemented and registered with the concrete AbstractConstructorEntityInstantiator to provide non reflection
* bases instantiaton for domain classes
*
* @deprecated use {@link EntityInstantiator} abstraction instead.
*/
@Deprecated

View File

@@ -24,8 +24,8 @@ public abstract class QueryDslUtils {
public static final boolean QUERY_DSL_PRESENT = org.springframework.util.ClassUtils.isPresent(
"com.mysema.query.types.Predicate", QueryDslUtils.class.getClassLoader());
private QueryDslUtils() {
}
}

View File

@@ -83,7 +83,7 @@ public abstract class CdiRepositoryBean<T> implements Bean<T> {
return new HashSet<Type>(interfaces);
}
/**
* Returns an instance of an {@link EntityManager}.
*

View File

@@ -63,7 +63,7 @@ public abstract class AbstractRepositoryConfigDefinitionParser<S extends GlobalR
private static final Log LOG = LogFactory.getLog(AbstractRepositoryConfigDefinitionParser.class);
private static final String REPOSITORY_INTERFACE_POST_PROCESSOR = "org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor";
private static final String REPOSITORY_INTERFACE_POST_PROCESSOR = "org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor";
/*
* (non-Javadoc)
@@ -274,11 +274,11 @@ public abstract class AbstractRepositoryConfigDefinitionParser<S extends GlobalR
provider.setResourceLoader(parser.getReaderContext().getResourceLoader());
provider.addIncludeFilter(new RegexPatternTypeFilter(pattern));
Set<BeanDefinition> definitions = provider.findCandidateComponents(config.getBasePackage());
if (definitions.size() == 0) {
return null;
}
if (definitions.size() == 1) {
return (AbstractBeanDefinition) definitions.iterator().next();
}
@@ -287,7 +287,7 @@ public abstract class AbstractRepositoryConfigDefinitionParser<S extends GlobalR
for (BeanDefinition bean : definitions) {
implementationClassNames.add(bean.getBeanClassName());
}
throw new IllegalStateException(String.format(
"Ambiguous custom implementations detected! Found %s but expected a single implementation!",
StringUtils.collectionToCommaDelimitedString(implementationClassNames)));

View File

@@ -47,7 +47,7 @@ public interface RepositoryMetadata {
* @return
*/
Class<?> getRepositoryInterface();
/**
* Returns the domain class returned by the given {@link Method}. Will extract the type from {@link Collection}s and
* {@link org.springframework.data.domain.Page} as well.

View File

@@ -30,19 +30,19 @@ import org.springframework.util.Assert;
public abstract class AbstractRepositoryMetadata implements RepositoryMetadata {
private final TypeInformation<?> typeInformation;
/**
* Creates a new {@link AbstractRepositoryMetadata}.
*
* @param repositoryInterface must not be {@literal null} and must be an interface.
*/
public AbstractRepositoryMetadata(Class<?> repositoryInterface) {
Assert.notNull(repositoryInterface, "Given type must not be null!");
Assert.isTrue(repositoryInterface.isInterface(), "Given type must be an interface!");
this.typeInformation = ClassTypeInformation.from(repositoryInterface);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.core.RepositoryMetadata#getReturnedDomainClass(java.lang.reflect.Method)

View File

@@ -61,10 +61,10 @@ class DefaultRepositoryInformation extends AbstractRepositoryMetadata implements
Class<?> customImplementationClass) {
super(metadata.getRepositoryInterface());
Assert.notNull(metadata);
Assert.notNull(repositoryBaseClass);
this.metadata = metadata;
this.repositoryBaseClass = repositoryBaseClass;
this.customImplementationClass = customImplementationClass;

View File

@@ -39,7 +39,7 @@ import org.springframework.util.ClassUtils;
*/
class RepositoryInterfaceAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements
BeanFactoryAware {
private static final Log LOG = LogFactory.getLog(RepositoryInterfaceAwareBeanPostProcessor.class);
private static final Class<?> REPOSITORY_TYPE = RepositoryFactoryBeanSupport.class;

View File

@@ -133,7 +133,7 @@ public class QueryMethod {
return repositoryDomainClass == null || repositoryDomainClass.isAssignableFrom(methodDomainClass) ? methodDomainClass
: repositoryDomainClass;
}
/**
* Returns the type of the object that will be returned.
*

View File

@@ -45,6 +45,7 @@ public class Part {
*
* @param part must not be {@literal null}.
* @param clazz must not be {@l
*/
public Part(String part, Class<?> clazz) {
@@ -73,12 +74,12 @@ public class Part {
Matcher matcher = IGNORE_CASE.matcher(part);
String result = part;
if (matcher.find()) {
ignoreCase = IgnoreCaseType.ALWAYS;
result = part.substring(0, matcher.start()) + part.substring(matcher.end(), part.length());
}
return result;
}
@@ -172,30 +173,16 @@ public class Part {
*/
public static enum Type {
BETWEEN(2, "Between"),
IS_NOT_NULL(0, "IsNotNull", "NotNull"),
IS_NULL(0, "IsNull", "Null"),
LESS_THAN("LessThan"),
LESS_THAN_EQUAL("LessThanEqual"),
GREATER_THAN("GreaterThan"),
GREATER_THAN_EQUAL("GreaterThanEqual"),
NOT_LIKE("NotLike"),
LIKE("Like"),
NOT_IN("NotIn"),
IN("In"),
NEAR("Near"),
WITHIN("Within"),
REGEX("Regex"),
EXISTS(0, "Exists"),
TRUE(0, "IsTrue", "True"),
FALSE(0, "IsFalse", "False"),
NEGATING_SIMPLE_PROPERTY("Not"),
SIMPLE_PROPERTY;
BETWEEN(2, "Between"), IS_NOT_NULL(0, "IsNotNull", "NotNull"), IS_NULL(0, "IsNull", "Null"), LESS_THAN("LessThan"), LESS_THAN_EQUAL(
"LessThanEqual"), GREATER_THAN("GreaterThan"), GREATER_THAN_EQUAL("GreaterThanEqual"), NOT_LIKE("NotLike"), LIKE(
"Like"), NOT_IN("NotIn"), IN("In"), NEAR("Near"), WITHIN("Within"), REGEX("Regex"), EXISTS(0, "Exists"), TRUE(
0, "IsTrue", "True"), FALSE(0, "IsFalse", "False"), NEGATING_SIMPLE_PROPERTY("Not"), SIMPLE_PROPERTY;
// Need to list them again explicitly as the order is important
// (esp. for IS_NULL, IS_NOT_NULL)
private static final List<Part.Type> ALL = Arrays.asList(IS_NOT_NULL, IS_NULL, BETWEEN, LESS_THAN, LESS_THAN_EQUAL, GREATER_THAN, GREATER_THAN_EQUAL,
NOT_LIKE, LIKE, NOT_IN, IN, NEAR, WITHIN, REGEX, EXISTS, TRUE, FALSE, NEGATING_SIMPLE_PROPERTY, SIMPLE_PROPERTY);
private static final List<Part.Type> ALL = Arrays.asList(IS_NOT_NULL, IS_NULL, BETWEEN, LESS_THAN, LESS_THAN_EQUAL,
GREATER_THAN, GREATER_THAN_EQUAL, NOT_LIKE, LIKE, NOT_IN, IN, NEAR, WITHIN, REGEX, EXISTS, TRUE, FALSE,
NEGATING_SIMPLE_PROPERTY, SIMPLE_PROPERTY);
private final List<String> keywords;
private final int numberOfArguments;
@@ -219,9 +206,9 @@ public class Part {
}
/**
* Returns the {@link Type} of the {@link Part} for the given raw propertyPath. This will
* try to detect e.g. keywords contained in the raw propertyPath that trigger special query creation. Returns
* {@link #SIMPLE_PROPERTY} by default.
* Returns the {@link Type} of the {@link Part} for the given raw propertyPath. This will try to detect e.g.
* keywords contained in the raw propertyPath that trigger special query creation. Returns {@link #SIMPLE_PROPERTY}
* by default.
*
* @param rawProperty
* @return
@@ -238,8 +225,9 @@ public class Part {
}
/**
* Returns whether the the type supports the given raw propertyPath. Default implementation checks whether the propertyPath
* ends with the registered keyword. Does not support the keyword if the propertyPath is a valid field as is.
* Returns whether the the type supports the given raw propertyPath. Default implementation checks whether the
* propertyPath ends with the registered keyword. Does not support the keyword if the propertyPath is a valid field
* as is.
*
* @param propertyPath
* @return

View File

@@ -100,7 +100,7 @@ public class PartTree implements Iterable<OrPart> {
return subject.isDistinct();
}
/**
* Returns an {@link Iterable} of all parts contained in the {@link PartTree}.
*
@@ -116,7 +116,7 @@ public class PartTree implements Iterable<OrPart> {
}
return result;
}
/**
* Returns all {@link Part}s of the {@link PartTree} of the given {@link Type}.
*
@@ -124,15 +124,15 @@ public class PartTree implements Iterable<OrPart> {
* @return
*/
public Iterable<Part> getParts(Type type) {
List<Part> result = new ArrayList<Part>();
for (Part part : getParts()) {
if (part.getType().equals(type)) {
result.add(part);
}
}
return result;
}

View File

@@ -45,26 +45,24 @@ class ParameterizedTypeInformation<T> extends ParentTypeAwareTypeInformation<T>
this.type = type;
}
/*
* (non-Javadoc)
* @see org.springframework.data.util.TypeDiscoverer#getMapValueType()
*/
@Override
public TypeInformation<?> getMapValueType() {
if (Map.class.equals(getType())) {
Type[] arguments = type.getActualTypeArguments();
return createInfo(arguments[1]);
}
Class<?> rawType = getType();
Set<Type> supertypes = new HashSet<Type>();
supertypes.add(rawType.getGenericSuperclass());
supertypes.addAll(Arrays.asList(rawType.getGenericInterfaces()));
for (Type supertype : supertypes) {
Class<?> rawSuperType = GenericTypeResolver.resolveType(supertype, getTypeVariableMap());
if (Map.class.isAssignableFrom(rawSuperType)) {
@@ -73,7 +71,7 @@ class ParameterizedTypeInformation<T> extends ParentTypeAwareTypeInformation<T>
return createInfo(arguments[1]);
}
}
return super.getMapValueType();
}
}

View File

@@ -8,13 +8,13 @@ import org.springframework.util.ObjectUtils;
/**
* Base class for {@link TypeInformation} implementations that need parent type awareness.
*
*
* @author Oliver Gierke
*/
public abstract class ParentTypeAwareTypeInformation<S> extends TypeDiscoverer<S> {
private final TypeDiscoverer<?> parent;
private final TypeDiscoverer<?> parent;
/**
* Creates a new {@link ParentTypeAwareTypeInformation}.
*
@@ -26,7 +26,7 @@ public abstract class ParentTypeAwareTypeInformation<S> extends TypeDiscoverer<S
super(type, map);
this.parent = parent;
}
/**
* Considers the parent's type variable map before invoking the super class method.
*
@@ -36,14 +36,14 @@ public abstract class ParentTypeAwareTypeInformation<S> extends TypeDiscoverer<S
protected Map<TypeVariable, Type> getTypeVariableMap() {
return parent == null ? super.getTypeVariableMap() : parent.getTypeVariableMap();
}
/*
* (non-Javadoc)
* @see org.springframework.data.util.TypeDiscoverer#createInfo(java.lang.reflect.Type)
*/
@Override
protected TypeInformation<?> createInfo(Type fieldType) {
if (parent.getType().equals(fieldType)) {
return parent;
}

View File

@@ -89,7 +89,7 @@ class TypeDiscoverer<S> implements TypeInformation<S> {
if (fieldType instanceof Class) {
return new ClassTypeInformation((Class<?>) fieldType);
}
Map<TypeVariable, Type> variableMap = GenericTypeResolver.getTypeVariableMap(resolveType(fieldType));
if (fieldType instanceof ParameterizedType) {
@@ -105,18 +105,18 @@ class TypeDiscoverer<S> implements TypeInformation<S> {
if (fieldType instanceof GenericArrayType) {
return new GenericArrayTypeInformation((GenericArrayType) fieldType, this);
}
if (fieldType instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) fieldType;
Type[] bounds = wildcardType.getLowerBounds();
if (bounds.length > 0) {
return createInfo(bounds[0]);
}
}
bounds = wildcardType.getUpperBounds();
if (bounds.length > 0) {
return createInfo(bounds[0]);
}
@@ -266,7 +266,7 @@ class TypeDiscoverer<S> implements TypeInformation<S> {
if (!isMap()) {
return null;
}
return getTypeArgument(getType(), Map.class, 1);
}
@@ -320,11 +320,11 @@ class TypeDiscoverer<S> implements TypeInformation<S> {
* @see org.springframework.data.util.TypeInformation#getReturnType(java.lang.reflect.Method)
*/
public TypeInformation<?> getReturnType(Method method) {
Assert.notNull(method);
return createInfo(method.getGenericReturnType());
}
/*
* (non-Javadoc)
*

View File

@@ -83,7 +83,7 @@ public interface TypeInformation<S> {
* @return
*/
TypeInformation<?> getActualType();
/**
* Returns a {@link TypeInformation} for the return type of the given {@link Method}. Will potentially resolve
* generics information against the current types type parameter bindings.

View File

@@ -44,7 +44,8 @@ class TypeVariableTypeInformation<T> extends ParentTypeAwareTypeInformation<T> {
* @param parent
*/
@SuppressWarnings("rawtypes")
public TypeVariableTypeInformation(TypeVariable<?> variable, Type owningType, TypeDiscoverer<?> parent, Map<TypeVariable, Type> map) {
public TypeVariableTypeInformation(TypeVariable<?> variable, Type owningType, TypeDiscoverer<?> parent,
Map<TypeVariable, Type> map) {
super(variable, parent, map);
Assert.notNull(variable);

View File

@@ -22,14 +22,14 @@ import org.junit.Test;
/**
* Unit tests for {@link UserCredentials}.
*
*
* @author Oliver Gierke
*/
public class UserCredentialsUnitTests {
@Test
public void treatsEmptyStringAsNull() {
UserCredentials credentials = new UserCredentials("", "");
assertThat(credentials.getUsername(), is(nullValue()));
assertThat(credentials.getPassword(), is(nullValue()));

View File

@@ -39,42 +39,42 @@ import org.springframework.data.util.TypeInformation;
/**
* Unit tests for {@link ConfigurableTypeMapper}.
*
*
* @author Oliver Gierke
*/
public class ConfigurableTypeInformationMapperUnitTests<T extends PersistentProperty<T>> {
ConfigurableTypeInformationMapper mapper;
@Before
public void setUp() {
mapper = new ConfigurableTypeInformationMapper(Collections.singletonMap(String.class, "1"));
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullTypeMap() {
new ConfigurableTypeInformationMapper((Map<? extends Class<?>, String>) null);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullMappingContext() {
new ConfigurableTypeInformationMapper((MappingContext<?, ?>) null);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNonBijectionalMap() {
Map<Class<?>, String> map = new HashMap<Class<?>, String>();
map.put(String.class, "1");
map.put(Object.class, "1");
new ConfigurableTypeInformationMapper(map);
}
@Test
@SuppressWarnings("unchecked")
public void extractsAliasInfoFromMappingContext() {
AbstractMappingContext<BasicPersistentEntity<Object,T>,T> mappingContext = new AbstractMappingContext<BasicPersistentEntity<Object, T>, T>() {
AbstractMappingContext<BasicPersistentEntity<Object, T>, T> mappingContext = new AbstractMappingContext<BasicPersistentEntity<Object, T>, T>() {
@Override
protected <S> BasicPersistentEntity<Object, T> createPersistentEntity(TypeInformation<S> typeInformation) {
@@ -92,32 +92,32 @@ public class ConfigurableTypeInformationMapperUnitTests<T extends PersistentProp
};
}
};
mappingContext.setInitialEntitySet(Collections.singleton(Entity.class));
mappingContext.afterPropertiesSet();
mapper = new ConfigurableTypeInformationMapper(mappingContext);
assertThat(mapper.createAliasFor(ClassTypeInformation.from(Entity.class)), is((Object) "foo"));
}
@Test
public void writesMapKeyForType() {
assertThat(mapper.createAliasFor(ClassTypeInformation.from(String.class)), is((Object) "1"));
assertThat(mapper.createAliasFor(ClassTypeInformation.from(Object.class)), is(nullValue()));
}
@Test
@SuppressWarnings("rawtypes")
public void readsTypeForMapKey() {
assertThat(mapper.resolveTypeFrom("1"), is((TypeInformation) ClassTypeInformation.from(String.class)));
assertThat(mapper.resolveTypeFrom("unmapped"), is(nullValue()));
}
@TypeAlias("foo")
class Entity {
}
}

View File

@@ -68,20 +68,20 @@ public class ReflectionEntityInstantiatorUnitTest<P extends PersistentProperty<P
public void instantiatesTypeWithPreferredConstructorUsingParameterValueProvider() {
PreferredConstructor constructor = new PreferredConstructorDiscoverer<Foo, P>(Foo.class).getConstructor();
when(entity.getType()).thenReturn((Class) Foo.class);
when(entity.getPersistenceConstructor()).thenReturn(constructor);
Object instance = INSTANCE.createInstance(entity, provider);
assertTrue(instance instanceof Foo);
verify(provider, times(1)).getParameterValue((Parameter) constructor.getParameters().iterator().next());
}
static class Foo {
Foo(String foo) {
}
}
}

View File

@@ -36,37 +36,37 @@ public class SimpleTypeInformationMapperUnitTests {
TypeInformation type = mapper.resolveTypeFrom("java.lang.String");
TypeInformation expected = ClassTypeInformation.from(String.class);
assertThat(type, is(expected));
}
@Test
public void returnsNullForNonStringKey() {
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
assertThat(mapper.resolveTypeFrom(new Object()), is(nullValue()));
}
@Test
public void returnsNullForEmptyTypeKey() {
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
assertThat(mapper.resolveTypeFrom(""), is(nullValue()));
}
@Test
public void returnsNullForUnloadableClass() {
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
assertThat(mapper.resolveTypeFrom("Foo"), is(nullValue()));
}
@Test
public void usesFullyQualifiedClassNameAsTypeKey() {
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
Object alias = mapper.createAliasFor(ClassTypeInformation.from(String.class));
assertTrue(alias instanceof String);
assertThat(alias, is((Object) String.class.getName()));
}

View File

@@ -5,10 +5,9 @@ import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
/**
* Unit test for {@link Direction}.
*
*
* @author Oliver Gierke
*/
public class DirectionUnitTests {
@@ -20,7 +19,6 @@ public class DirectionUnitTests {
assertEquals(Direction.DESC, Direction.fromString("desc"));
}
@Test(expected = IllegalArgumentException.class)
public void rejectsInvalidString() throws Exception {

View File

@@ -26,10 +26,9 @@ import java.util.List;
import org.junit.Test;
/**
* Unit test for {@link PageImpl}.
*
*
* @author Oliver Gierke
*/
public class PageImplUnitTests {
@@ -40,11 +39,9 @@ public class PageImplUnitTests {
PageImpl<String> page = new PageImpl<String>(Arrays.asList("Foo"));
assertEqualsAndHashcode(page, page);
assertEqualsAndHashcode(page,
new PageImpl<String>(Arrays.asList("Foo")));
assertEqualsAndHashcode(page, new PageImpl<String>(Arrays.asList("Foo")));
}
@Test
public void assertEqualsForComplexSetup() throws Exception {
@@ -55,27 +52,21 @@ public class PageImplUnitTests {
assertEqualsAndHashcode(page, page);
assertEqualsAndHashcode(page, new PageImpl<String>(content, pageable,
100));
assertEqualsAndHashcode(page, new PageImpl<String>(content, pageable, 100));
assertNotEqualsAndHashcode(page, new PageImpl<String>(content,
pageable, 90));
assertNotEqualsAndHashcode(page, new PageImpl<String>(content, pageable, 90));
assertNotEqualsAndHashcode(page, new PageImpl<String>(content,
new PageRequest(1, 10), 100));
assertNotEqualsAndHashcode(page, new PageImpl<String>(content, new PageRequest(1, 10), 100));
assertNotEqualsAndHashcode(page, new PageImpl<String>(content,
new PageRequest(0, 15), 100));
assertNotEqualsAndHashcode(page, new PageImpl<String>(content, new PageRequest(0, 15), 100));
}
@Test(expected = IllegalArgumentException.class)
public void preventsNullContentForSimpleSetup() throws Exception {
new PageImpl<Object>(null);
}
@Test(expected = IllegalArgumentException.class)
public void preventsNullContentForAdvancedSetup() throws Exception {

View File

@@ -21,10 +21,9 @@ import static org.springframework.data.domain.UnitTestUtils.*;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
/**
* Unit test for {@link PageRequest}.
*
*
* @author Oliver Gierke
*/
public class PageRequestUnitTests {
@@ -35,21 +34,18 @@ public class PageRequestUnitTests {
new PageRequest(-1, 10);
}
@Test(expected = IllegalArgumentException.class)
public void preventsNegativeSize() {
new PageRequest(0, -1);
}
@Test(expected = IllegalArgumentException.class)
public void preventsZeroSize() {
new PageRequest(0, 0);
}
@Test
public void equalsRegardsSortCorrectly() {
@@ -69,11 +65,9 @@ public class PageRequestUnitTests {
assertNotEqualsAndHashcode(request, new PageRequest(0, 10));
// Is not equal to instance with another sort
assertNotEqualsAndHashcode(request, new PageRequest(0, 10,
Direction.ASC, "foo"));
assertNotEqualsAndHashcode(request, new PageRequest(0, 10, Direction.ASC, "foo"));
}
@Test
public void equalsHonoursPageAndSize() {

View File

@@ -22,33 +22,28 @@ import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
/**
* Unit test for {@link Sort}.
*
*
* @author Oliver Gierke
*/
public class SortUnitTests {
/**
* Asserts that the class applies the default sort order if no order or
* {@code null} was provided.
*
* Asserts that the class applies the default sort order if no order or {@code null} was provided.
*
* @throws Exception
*/
@Test
public void appliesDefaultForOrder() throws Exception {
assertEquals(Sort.DEFAULT_DIRECTION, new Sort("foo").iterator().next()
.getDirection());
assertEquals(Sort.DEFAULT_DIRECTION, new Sort((Direction) null, "foo")
.iterator().next().getDirection());
assertEquals(Sort.DEFAULT_DIRECTION, new Sort("foo").iterator().next().getDirection());
assertEquals(Sort.DEFAULT_DIRECTION, new Sort((Direction) null, "foo").iterator().next().getDirection());
}
/**
* Asserts that the class rejects {@code null} as properties array.
*
*
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
@@ -57,11 +52,9 @@ public class SortUnitTests {
new Sort(Direction.ASC, (String[]) null);
}
/**
* Asserts that the class rejects {@code null} values in the properties
* array.
*
* Asserts that the class rejects {@code null} values in the properties array.
*
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
@@ -70,10 +63,9 @@ public class SortUnitTests {
new Sort(Direction.ASC, (String) null);
}
/**
* Asserts that the class rejects empty strings in the properties array.
*
*
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
@@ -82,10 +74,9 @@ public class SortUnitTests {
new Sort(Direction.ASC, "");
}
/**
* Asserts that the class rejects no properties given at all.
*
*
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
@@ -93,17 +84,17 @@ public class SortUnitTests {
new Sort(Direction.ASC);
}
@Test
public void allowsCombiningSorts() {
Sort sort = new Sort("foo").and(new Sort("bar"));
assertThat(sort, hasItems(new Sort.Order("foo"), new Sort.Order("bar")));
}
@Test
public void handlesAdditionalNullSort() {
Sort sort = new Sort("foo").and(null);
assertThat(sort, hasItem(new Sort.Order("foo")));
}

View File

@@ -2,7 +2,6 @@ package org.springframework.data.domain;
import static org.junit.Assert.*;
/**
* @author Oliver Gierke
*/
@@ -12,11 +11,9 @@ public abstract class UnitTestUtils {
}
/**
* Asserts that delivered objects both equal each other as well as return
* the same hash code.
*
* Asserts that delivered objects both equal each other as well as return the same hash code.
*
* @param first
* @param second
*/
@@ -27,11 +24,9 @@ public abstract class UnitTestUtils {
assertEquals(first.hashCode(), second.hashCode());
}
/**
* Asserts that both objects are not equal to each other and differ in hash
* code, too.
*
* Asserts that both objects are not equal to each other and differ in hash code, too.
*
* @param first
* @param second
*/

View File

@@ -27,10 +27,7 @@ import org.springframework.data.annotation.Persistent;
* @author Jon Brisbin <jbrisbin@vmware.com>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.TYPE,
ElementType.FIELD
})
@Target({ ElementType.TYPE, ElementType.FIELD })
@Persistent
public @interface Document {
}

View File

@@ -43,13 +43,12 @@ public class MappingMetadataTests {
ctx = new SampleMappingContext();
}
@Test
public void testPojoWithId() {
ctx.setInitialEntitySet(Collections.singleton(PersonWithId.class));
ctx.afterPropertiesSet();
PersistentEntity<?, SampleProperty> person = ctx.getPersistentEntity(PersonWithId.class);
assertNotNull(person.getIdProperty());
assertEquals(String.class, person.getIdProperty().getType());
@@ -57,10 +56,10 @@ public class MappingMetadataTests {
@Test
public void testAssociations() {
ctx.setInitialEntitySet(Collections.singleton(PersonWithChildren.class));
ctx.afterPropertiesSet();
PersistentEntity<?, SampleProperty> person = ctx.getPersistentEntity(PersonWithChildren.class);
person.doWithAssociations(new AssociationHandler<MappingMetadataTests.SampleProperty>() {
public void doWithAssociation(Association<SampleProperty> association) {
@@ -72,30 +71,26 @@ public class MappingMetadataTests {
public interface SampleProperty extends PersistentProperty<SampleProperty> {
}
public class SampleMappingContext extends AbstractMappingContext<MutablePersistentEntity<?, SampleProperty>, SampleProperty> {
public class SampleMappingContext extends
AbstractMappingContext<MutablePersistentEntity<?, SampleProperty>, SampleProperty> {
@Override
protected <T> MutablePersistentEntity<?, SampleProperty> createPersistentEntity(
TypeInformation<T> typeInformation) {
protected <T> MutablePersistentEntity<?, SampleProperty> createPersistentEntity(TypeInformation<T> typeInformation) {
return new BasicPersistentEntity<T, MappingMetadataTests.SampleProperty>(typeInformation);
}
@Override
protected SampleProperty createPersistentProperty(Field field,
PropertyDescriptor descriptor,
MutablePersistentEntity<?, SampleProperty> owner,
SimpleTypeHolder simpleTypeHolder) {
protected SampleProperty createPersistentProperty(Field field, PropertyDescriptor descriptor,
MutablePersistentEntity<?, SampleProperty> owner, SimpleTypeHolder simpleTypeHolder) {
return new SamplePropertyImpl(field, descriptor, owner, simpleTypeHolder);
}
}
public class SamplePropertyImpl extends AnnotationBasedPersistentProperty<SampleProperty> implements SampleProperty {
public SamplePropertyImpl(Field field,
PropertyDescriptor propertyDescriptor,
PersistentEntity<?, SampleProperty> owner,
SimpleTypeHolder simpleTypeHolder) {
public SamplePropertyImpl(Field field, PropertyDescriptor propertyDescriptor,
PersistentEntity<?, SampleProperty> owner, SimpleTypeHolder simpleTypeHolder) {
super(field, propertyDescriptor, owner, simpleTypeHolder);
}

View File

@@ -35,7 +35,7 @@ public class SimpleTypeHolderUnitTests {
public void rejectsNullCustomTypes() {
new SimpleTypeHolder(null, false);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullOriginal() {
new SimpleTypeHolder(new HashSet<Class<?>>(), null);
@@ -49,38 +49,38 @@ public class SimpleTypeHolderUnitTests {
SimpleTypeHolder holder = new SimpleTypeHolder();
holder.isSimpleType(null);
}
@Test
public void addsDefaultTypes() {
SimpleTypeHolder holder = new SimpleTypeHolder();
assertThat(holder.isSimpleType(String.class), is(true));
}
@Test
public void doesNotAddDefaultConvertersIfConfigured() {
SimpleTypeHolder holder = new SimpleTypeHolder(new HashSet<Class<?>>(), false);
assertThat(holder.isSimpleType(String.class), is(false));
}
@Test
public void addsCustomTypesToSimpleOnes() {
SimpleTypeHolder holder = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolder.class), true);
assertThat(holder.isSimpleType(SimpleTypeHolder.class), is(true));
assertThat(holder.isSimpleType(SimpleTypeHolderUnitTests.class), is(false));
}
@Test
public void createsHolderFromAnotherOneCorrectly() {
SimpleTypeHolder holder = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolder.class), true);
SimpleTypeHolder second = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolderUnitTests.class), holder);
assertThat(holder.isSimpleType(SimpleTypeHolder.class), is(true));
assertThat(holder.isSimpleType(SimpleTypeHolderUnitTests.class), is(false));
assertThat(second.isSimpleType(SimpleTypeHolder.class), is(true));
@@ -94,33 +94,33 @@ public class SimpleTypeHolderUnitTests {
}
@Test
public void considersSimpleEnumAsSimple() {
SimpleTypeHolder holder = new SimpleTypeHolder();
assertThat(holder.isSimpleType(SimpleEnum.FOO.getClass()), is(true));
}
public void considersSimpleEnumAsSimple() {
SimpleTypeHolder holder = new SimpleTypeHolder();
assertThat(holder.isSimpleType(SimpleEnum.FOO.getClass()), is(true));
}
@Test
public void considersComplexEnumAsSimple() {
SimpleTypeHolder holder = new SimpleTypeHolder();
assertThat(holder.isSimpleType(ComplexEnum.FOO.getClass()), is(true));
assertThat(holder.isSimpleType(ComplexEnum.FOO.getClass()), is(true));
}
enum SimpleEnum {
FOO;
}
enum ComplexEnum {
FOO {
enum SimpleEnum {
FOO;
}
enum ComplexEnum {
FOO {
@Override
boolean method() {
return false;
}
};
abstract boolean method();
}
abstract boolean method();
}
}

View File

@@ -52,7 +52,7 @@ public class AbstractMappingContextIntegrationTests<T extends PersistentProperty
public void run() {
PersistentEntity<Object, T> entity = context.getPersistentEntity(Person.class);
entity.doWithProperties(new PropertyHandler<T>() {
public void doWithPersistentProperty(T persistentProperty) {
try {
@@ -68,7 +68,7 @@ public class AbstractMappingContextIntegrationTests<T extends PersistentProperty
a.start();
Thread.sleep(2800);
b.start();
a.join();
b.join();
}
@@ -87,7 +87,7 @@ public class AbstractMappingContextIntegrationTests<T extends PersistentProperty
final BasicPersistentEntity<Object, T> owner, final SimpleTypeHolder simpleTypeHolder) {
PersistentProperty prop = mock(PersistentProperty.class);
when(prop.getTypeInformation()).thenReturn((TypeInformation) owner.getTypeInformation());
when(prop.getName()).thenReturn(field.getName());
when(prop.getPersistentEntityType()).thenReturn(Collections.EMPTY_SET);
@@ -97,7 +97,7 @@ public class AbstractMappingContextIntegrationTests<T extends PersistentProperty
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return (T) prop;
}
}

View File

@@ -18,23 +18,24 @@ import org.springframework.data.util.TypeInformation;
/**
* Unit test for {@link AbstractMappingContext}.
*
*
* @author Oliver Gierke
*/
public class AbstractMappingContextUnitTests {
final SimpleTypeHolder holder = new SimpleTypeHolder();
DummyMappingContext context;
@Before
public void setUp() {
context = new DummyMappingContext();
context.setSimpleTypeHolder(holder);
context = new DummyMappingContext();
context.setSimpleTypeHolder(holder);
}
@Test
public void doesNotTryToLookupPersistentEntityForLeafProperty() {
PersistentPropertyPath<DummyPersistenProperty> path = context.getPersistentPropertyPath(PropertyPath.from("name", Person.class));
PersistentPropertyPath<DummyPersistenProperty> path = context.getPersistentPropertyPath(PropertyPath.from("name",
Person.class));
assertThat(path, is(notNullValue()));
}
@@ -49,26 +50,27 @@ public class AbstractMappingContextUnitTests {
} catch (MappingException e) {
// expected
}
context.getPersistentEntity(Unsupported.class);
}
class Person {
String name;
}
class Unsupported {
}
class DummyMappingContext extends AbstractMappingContext<BasicPersistentEntity<Object, DummyPersistenProperty>, DummyPersistenProperty> {
class DummyMappingContext extends
AbstractMappingContext<BasicPersistentEntity<Object, DummyPersistenProperty>, DummyPersistenProperty> {
@Override
@SuppressWarnings("unchecked")
protected <S> BasicPersistentEntity<Object, DummyPersistenProperty> createPersistentEntity(TypeInformation<S> typeInformation) {
protected <S> BasicPersistentEntity<Object, DummyPersistenProperty> createPersistentEntity(
TypeInformation<S> typeInformation) {
return new BasicPersistentEntity<Object, DummyPersistenProperty>((TypeInformation<Object>) typeInformation) {
@Override
public void verify() {
if (holder.isSimpleType(getType()) || Unsupported.class.equals(getType())) {
@@ -81,11 +83,11 @@ public class AbstractMappingContextUnitTests {
@Override
protected DummyPersistenProperty createPersistentProperty(final Field field, final PropertyDescriptor descriptor,
final BasicPersistentEntity<Object, DummyPersistenProperty> owner, final SimpleTypeHolder simpleTypeHolder) {
return new DummyPersistenProperty(field, descriptor, owner, simpleTypeHolder);
}
}
class DummyPersistenProperty extends AbstractPersistentProperty<DummyPersistenProperty> {
public DummyPersistenProperty(Field field, PropertyDescriptor propertyDescriptor,

View File

@@ -21,18 +21,17 @@ import org.springframework.util.ReflectionUtils;
* @author Oliver Gierke
*/
public class AbstractPersistentPropertyUnitTests {
TypeInformation<TestClassComplex> typeInfo;
PersistentEntity<TestClassComplex, SamplePersistentProperty> entity;
SimpleTypeHolder typeHolder;
@Before
public void setUp() {
typeInfo = ClassTypeInformation.from(TestClassComplex.class);
entity = new BasicPersistentEntity<TestClassComplex, SamplePersistentProperty>(typeInfo);
typeHolder = new SimpleTypeHolder();
}
/**
* @see DATACMNS-68
@@ -41,20 +40,20 @@ public class AbstractPersistentPropertyUnitTests {
public void discoversComponentTypeCorrectly() throws Exception {
Field field = ReflectionUtils.findField(TestClassComplex.class, "testClassSet");
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
property.getComponentType();
}
@Test
public void returnsNestedEntityTypeCorrectly() {
Field field = ReflectionUtils.findField(TestClassComplex.class, "testClassSet");
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
assertThat(property.getPersistentEntityType().iterator().hasNext(), is(false));
}
@SuppressWarnings("serial")
class TestClassSet extends TreeSet<Object> {
}

View File

@@ -22,24 +22,21 @@ import org.junit.Test;
import com.mysema.query.annotations.QueryEntity;
/**
* Unit test for {@link SimpleEntityPathResolver}.
*
*
* @author Oliver Gierke
*/
public class SimpleEntityPathResolverUnitTests {
EntityPathResolver resolver = SimpleEntityPathResolver.INSTANCE;
@Test
public void createsRepositoryFromDomainClassCorrectly() throws Exception {
assertThat((QUser) resolver.createPath(User.class), isA(QUser.class));
}
@Test
public void resolvesEntityPathForInnerClassCorrectly() throws Exception {
@@ -47,10 +44,8 @@ public class SimpleEntityPathResolverUnitTests {
isA(QSimpleEntityPathResolverUnitTests_NamedUser.class));
}
@Test(expected = IllegalArgumentException.class)
public void rejectsClassWithoutQueryClassConfrmingToTheNamingScheme()
throws Exception {
public void rejectsClassWithoutQueryClassConfrmingToTheNamingScheme() throws Exception {
resolver.createPath(QSimpleEntityPathResolverUnitTests_Sample.class);
}

View File

@@ -61,13 +61,13 @@ public class CdiRepositoryBeanUnitTests {
public void voidRejectsNullBeanManager() {
new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS, SampleRepository.class, null);
}
@Test
public void returnsBasicMetadata() {
DummyCdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(
NO_ANNOTATIONS, SampleRepository.class, beanManager);
DummyCdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS,
SampleRepository.class, beanManager);
assertThat(bean.getBeanClass(), is(typeCompatibleWith(SampleRepository.class)));
assertThat(bean.getName(), is(SampleRepository.class.getName()));
assertThat(bean.isNullable(), is(false));
@@ -77,20 +77,20 @@ public class CdiRepositoryBeanUnitTests {
@SuppressWarnings("unchecked")
public void returnsAllImplementedTypes() {
DummyCdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(
NO_ANNOTATIONS, SampleRepository.class, beanManager);
DummyCdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS,
SampleRepository.class, beanManager);
Set<Type> types = bean.getTypes();
assertThat(types.size(), is(2));
assertThat(types.containsAll(Arrays.asList(SampleRepository.class, Repository.class)), is(true));
}
@Test
public void detectsStereotypes() {
DummyCdiRepositoryBean<StereotypedSampleRepository> bean = new DummyCdiRepositoryBean<StereotypedSampleRepository>(
NO_ANNOTATIONS, StereotypedSampleRepository.class, beanManager);
Set<Class<? extends Annotation>> stereotypes = bean.getStereotypes();
assertThat(stereotypes.size(), is(1));
assertThat(stereotypes, hasItem(StereotypeAnnotation.class));
@@ -115,9 +115,9 @@ public class CdiRepositoryBeanUnitTests {
static interface SampleRepository extends Repository<Object, Serializable> {
}
@StereotypeAnnotation
static interface StereotypedSampleRepository {
}
}

View File

@@ -29,7 +29,7 @@ public abstract class CdiRepositoryExtensionSupportIntegrationTests {
@Test
public void createsSpringDataRepositoryBean() {
assertThat(getBean(SampleRepository.class), is(notNullValue()));
RepositoryClient client = getBean(RepositoryClient.class);

View File

@@ -25,7 +25,8 @@ import org.junit.BeforeClass;
*
* @author Oliver Gierke
*/
public class WebbeansCdiRepositoryExtensionSupportIntegrationTests extends CdiRepositoryExtensionSupportIntegrationTests {
public class WebbeansCdiRepositoryExtensionSupportIntegrationTests extends
CdiRepositoryExtensionSupportIntegrationTests {
static CdiTestContainer container;

View File

@@ -28,17 +28,17 @@ import org.springframework.data.repository.sample.SampleAnnotatedRepository;
/**
* Unit tests for {@link RepositoryComponentProvider}.
*
*
* @author Oliver Gierke
*/
public class RepositoryComponentProviderUnitTests {
@Test
public void findsAnnotatedRepositoryInterface() {
RepositoryComponentProvider provider = new RepositoryComponentProvider(Repository.class);
Set<BeanDefinition> components = provider.findCandidateComponents("org.springframework.data.repository.sample");
assertThat(components.size(), is(1));
assertThat(components.iterator().next().getBeanClassName(), is(SampleAnnotatedRepository.class.getName()));
}

View File

@@ -36,10 +36,9 @@ import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* Unit test for {@link TypeFilterParser}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
@@ -57,51 +56,36 @@ public class TypeFilterParserUnitTests {
@Mock
private ClassPathScanningCandidateComponentProvider scanner;
@Before
public void setUp() throws SAXException, IOException,
ParserConfigurationException {
public void setUp() throws SAXException, IOException, ParserConfigurationException {
parser = new TypeFilterParser(classLoader, context);
Resource sampleXmlFile =
new ClassPathResource("type-filter-test.xml",
TypeFilterParserUnitTests.class);
Resource sampleXmlFile = new ClassPathResource("type-filter-test.xml", TypeFilterParserUnitTests.class);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
documentElement =
factory.newDocumentBuilder()
.parse(sampleXmlFile.getInputStream())
.getDocumentElement();
documentElement = factory.newDocumentBuilder().parse(sampleXmlFile.getInputStream()).getDocumentElement();
}
@Test
public void parsesIncludesCorrectly() throws Exception {
Element element =
DomUtils.getChildElementByTagName(documentElement,
"firstSample");
Element element = DomUtils.getChildElementByTagName(documentElement, "firstSample");
parser.parseFilters(element, scanner);
verify(scanner, atLeastOnce()).addIncludeFilter(
isA(AssignableTypeFilter.class));
verify(scanner, atLeastOnce()).addIncludeFilter(isA(AssignableTypeFilter.class));
}
@Test
public void parsesExcludesCorrectly() throws Exception {
Element element =
DomUtils.getChildElementByTagName(documentElement,
"secondSample");
Element element = DomUtils.getChildElementByTagName(documentElement, "secondSample");
parser.parseFilters(element, scanner);
verify(scanner, atLeastOnce()).addExcludeFilter(
isA(AssignableTypeFilter.class));
verify(scanner, atLeastOnce()).addExcludeFilter(isA(AssignableTypeFilter.class));
}
}

View File

@@ -24,10 +24,9 @@ import org.junit.Test;
import org.springframework.data.repository.core.EntityInformation;
import org.springframework.data.repository.core.support.AbstractEntityInformation;
/**
* Unit tests for {@link AbstractEntityInformation}.
*
*
* @author Oliver Gierke
*/
public class AbstractEntityInformationUnitTests {
@@ -38,25 +37,21 @@ public class AbstractEntityInformationUnitTests {
new DummyAbstractEntityInformation(null);
}
@Test
public void considersEntityNewIfGetIdReturnsNull() throws Exception {
EntityInformation<Object, Serializable> metadata =
new DummyAbstractEntityInformation(Object.class);
EntityInformation<Object, Serializable> metadata = new DummyAbstractEntityInformation(Object.class);
assertThat(metadata.isNew(null), is(true));
assertThat(metadata.isNew(new Object()), is(false));
}
private static class DummyAbstractEntityInformation extends
AbstractEntityInformation<Object, Serializable> {
private static class DummyAbstractEntityInformation extends AbstractEntityInformation<Object, Serializable> {
public DummyAbstractEntityInformation(Class<Object> domainClass) {
super(domainClass);
}
/*
* (non-Javadoc)
*

View File

@@ -72,7 +72,7 @@ public class AbstractRepositoryMetadataUnitTests {
@Test
public void handlesGenericTypeInReturnedCollectionCorrectly() throws SecurityException, NoSuchMethodException {
RepositoryMetadata metadata = new DummyRepositoryMetadata(ExtendingRepository.class);
Method method = ExtendingRepository.class.getMethod("anotherMethod");
assertThat(metadata.getReturnedDomainClass(method), is(typeCompatibleWith(Map.class)));

View File

@@ -23,25 +23,24 @@ import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.AnnotationRepositoryMetadata;
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
/**
* Unit tests for {@link DefaultRepositoryMetadata}.
*
*
* @author Oliver Gierke
*/
public class AnnotationRepositoryMetadataUnitTests {
public class AnnotationRepositoryMetadataUnitTests {
@Test
public void handlesRepositoryProxyAnnotationCorrectly() {
RepositoryMetadata metadata = new AnnotationRepositoryMetadata(AnnotatedRepository.class);
assertEquals(User.class, metadata.getDomainClass());
assertEquals(Integer.class, metadata.getIdClass());
}
@Test(expected = IllegalArgumentException.class)
public void preventsUnannotatedInterface() {
new AnnotationRepositoryMetadata(UnannotatedRepository.class);
}
@@ -50,7 +49,6 @@ public class AnnotationRepositoryMetadataUnitTests {
private String firstname;
public String getAddress() {
return null;
@@ -59,10 +57,10 @@ public class AnnotationRepositoryMetadataUnitTests {
@RepositoryDefinition(domainClass = User.class, idClass = Integer.class)
interface AnnotatedRepository {
}
interface UnannotatedRepository {
}
}

View File

@@ -37,7 +37,7 @@ public class CustomAnnotationTransactionAttributeSourceUnitTests {
CustomAnnotationTransactionAttributeSource source = new TransactionalRepositoryProxyPostProcessor.CustomAnnotationTransactionAttributeSource();
TransactionAttribute attribute = source.getTransactionAttribute(Bar.class.getMethod("bar", Object.class),
FooImpl.class);
FooImpl.class);
assertThat(attribute.isReadOnly(), is(false));
attribute = source.getTransactionAttribute(Bar.class.getMethod("foo"), FooImpl.class);
@@ -76,7 +76,7 @@ public class CustomAnnotationTransactionAttributeSourceUnitTests {
/**
* Interface reconfiguring transactions.
*
*
* @author Oliver Gierke
*/
interface Bar extends Foo<Object> {

View File

@@ -81,21 +81,21 @@ public class DefaultRepositoryInformationUnitTests {
@Test
public void discoversIntermediateMethodsAsBackingMethods() throws NoSuchMethodException, SecurityException {
DefaultRepositoryMetadata metadata = new DefaultRepositoryMetadata(CustomRepository.class);
DefaultRepositoryInformation information = new DefaultRepositoryInformation(metadata,
PagingAndSortingRepository.class, null);
Method method = CustomRepository.class.getMethod("findAll", Pageable.class);
assertThat(information.isBaseClassMethod(method), is(true));
method = getMethodFrom(CustomRepository.class, "exists");
assertThat(information.isBaseClassMethod(method), is(true));
Matcher<Iterable<Method>> empty = iterableWithSize(0);
assertThat(information.getQueryMethods(), is(empty));
}
private Method getMethodFrom(Class<?> type, String name) {
for (Method method : type.getMethods()) {
if (method.getName().equals(name)) {

View File

@@ -27,66 +27,57 @@ import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.util.ClassUtils;
/**
* Unit tests for {@link DefaultRepositoryMetadata}.
*
*
* @author Oliver Gierke
*/
public class DefaultRepositoryMetadataUnitTests {
@Test(expected = IllegalArgumentException.class)
public void preventsNullRepositoryInterface() {
new DefaultRepositoryMetadata(null);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNonInterface() {
new DefaultRepositoryMetadata(Object.class);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNonRepositoryInterface() {
new DefaultRepositoryMetadata(Collection.class);
}
@Test
public void looksUpDomainClassCorrectly() throws Exception {
RepositoryMetadata metadata =
new DefaultRepositoryMetadata(UserRepository.class);
RepositoryMetadata metadata = new DefaultRepositoryMetadata(UserRepository.class);
assertEquals(User.class, metadata.getDomainClass());
metadata = new DefaultRepositoryMetadata(SomeDao.class);
assertEquals(User.class, metadata.getDomainClass());
}
@Test
public void findsDomainClassOnExtensionOfDaoInterface() throws Exception {
RepositoryMetadata metadata =
new DefaultRepositoryMetadata(
ExtensionOfUserCustomExtendedDao.class);
RepositoryMetadata metadata = new DefaultRepositoryMetadata(ExtensionOfUserCustomExtendedDao.class);
assertEquals(User.class, metadata.getDomainClass());
}
@Test
public void detectsParameterizedEntitiesCorrectly() {
RepositoryMetadata metadata =
new DefaultRepositoryMetadata(GenericEntityRepository.class);
RepositoryMetadata metadata = new DefaultRepositoryMetadata(GenericEntityRepository.class);
assertEquals(GenericEntity.class, metadata.getDomainClass());
}
@Test
public void looksUpIdClassCorrectly() throws Exception {
RepositoryMetadata metadata =
new DefaultRepositoryMetadata(UserRepository.class);
RepositoryMetadata metadata = new DefaultRepositoryMetadata(UserRepository.class);
assertEquals(Integer.class, metadata.getIdClass());
}
@@ -96,7 +87,6 @@ public class DefaultRepositoryMetadataUnitTests {
private String firstname;
public String getAddress() {
return null;
@@ -110,12 +100,10 @@ public class DefaultRepositoryMetadataUnitTests {
/**
* Sample interface to serve two purposes:
* <ol>
* <li>Check that {@link ClassUtils#getDomainClass(Class)} skips non
* {@link GenericDao} interfaces</li>
* <li>Check that {@link ClassUtils#getDomainClass(Class)} traverses
* interface hierarchy</li>
* <li>Check that {@link ClassUtils#getDomainClass(Class)} skips non {@link GenericDao} interfaces</li>
* <li>Check that {@link ClassUtils#getDomainClass(Class)} traverses interface hierarchy</li>
* </ol>
*
*
* @author Oliver Gierke
*/
private interface SomeDao extends Serializable, UserRepository {
@@ -125,21 +113,18 @@ public class DefaultRepositoryMetadataUnitTests {
/**
* Sample interface to test recursive lookup of domain class.
*
*
* @author Oliver Gierke
*/
static interface ExtensionOfUserCustomExtendedDao extends
UserCustomExtendedRepository {
static interface ExtensionOfUserCustomExtendedDao extends UserCustomExtendedRepository {
}
static interface UserCustomExtendedRepository extends
CrudRepository<User, Integer> {
static interface UserCustomExtendedRepository extends CrudRepository<User, Integer> {
}
static abstract class DummyGenericRepositorySupport<T, ID extends Serializable>
implements CrudRepository<T, ID> {
static abstract class DummyGenericRepositorySupport<T, ID extends Serializable> implements CrudRepository<T, ID> {
public T findOne(ID id) {
@@ -149,14 +134,13 @@ public class DefaultRepositoryMetadataUnitTests {
/**
* Helper class to reproduce #256.
*
*
* @author Oliver Gierke
*/
static class GenericEntity<T> {
}
static interface GenericEntityRepository extends
CrudRepository<GenericEntity<String>, Long> {
static interface GenericEntityRepository extends CrudRepository<GenericEntity<String>, Long> {
}
}

View File

@@ -26,23 +26,20 @@ import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.domain.Persistable;
import org.springframework.data.repository.core.support.PersistableEntityInformation;
/**
* Unit tests for {@link PersistableEntityMetadata}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
public class PersistableEntityInformationUnitTests {
@SuppressWarnings({"rawtypes", "unchecked"})
static final PersistableEntityInformation metadata =
new PersistableEntityInformation(Persistable.class);
@SuppressWarnings({ "rawtypes", "unchecked" })
static final PersistableEntityInformation metadata = new PersistableEntityInformation(Persistable.class);
@Mock
Persistable<Long> persistable;
@Test
@SuppressWarnings("unchecked")
public void usesPersistablesGetId() throws Exception {
@@ -53,7 +50,6 @@ public class PersistableEntityInformationUnitTests {
assertEquals(3L, metadata.getId(persistable));
}
@Test
@SuppressWarnings("unchecked")
public void usesPersistablesIsNew() throws Exception {
@@ -63,13 +59,11 @@ public class PersistableEntityInformationUnitTests {
assertThat(metadata.isNew(persistable), is(false));
}
@Test
public void returnsGivenClassAsEntityType() throws Exception {
PersistableEntityInformation<PersistableEntity, Long> info =
new PersistableEntityInformation<PersistableEntity, Long>(
PersistableEntity.class);
PersistableEntityInformation<PersistableEntity, Long> info = new PersistableEntityInformation<PersistableEntity, Long>(
PersistableEntity.class);
assertEquals(PersistableEntity.class, info.getJavaType());
}
@@ -82,7 +76,6 @@ public class PersistableEntityInformationUnitTests {
return null;
}
public boolean isNew() {
return false;

View File

@@ -32,17 +32,15 @@ import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
import org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor;
/**
* Unit tests for {@link RepositoryInterfaceAwareBeanPostProcessor}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
public class RepositoryInterfaceAwareBeanPostProcessorUnitTests {
private static final Class<?> FACTORY_CLASS =
RepositoryFactoryBeanSupport.class;
private static final Class<?> FACTORY_CLASS = RepositoryFactoryBeanSupport.class;
private static final String BEAN_NAME = "foo";
private static final String DAO_INTERFACE_PROPERTY = "repositoryInterface";
@@ -52,33 +50,26 @@ public class RepositoryInterfaceAwareBeanPostProcessorUnitTests {
private ConfigurableListableBeanFactory beanFactory;
private BeanDefinition beanDefinition;
@Before
public void setUp() {
BeanDefinitionBuilder builder =
BeanDefinitionBuilder
.rootBeanDefinition(FACTORY_CLASS)
.addPropertyValue(DAO_INTERFACE_PROPERTY, UserDao.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(FACTORY_CLASS).addPropertyValue(
DAO_INTERFACE_PROPERTY, UserDao.class);
this.beanDefinition = builder.getBeanDefinition();
when(beanFactory.getBeanDefinition(BEAN_NAME)).thenReturn(
beanDefinition);
when(beanFactory.getBeanDefinition(BEAN_NAME)).thenReturn(beanDefinition);
processor = new RepositoryInterfaceAwareBeanPostProcessor();
}
@Test
public void returnsDaoInterfaceClassForFactoryBean() throws Exception {
processor.setBeanFactory(beanFactory);
assertEquals(UserDao.class,
processor.predictBeanType(FACTORY_CLASS, BEAN_NAME));
assertEquals(UserDao.class, processor.predictBeanType(FACTORY_CLASS, BEAN_NAME));
}
@Test
public void doesNotResolveInterfaceForNonFactoryClasses() throws Exception {
@@ -86,22 +77,17 @@ public class RepositoryInterfaceAwareBeanPostProcessorUnitTests {
assertNotTypeDetected(BeanFactory.class);
}
@Test
public void doesNotResolveInterfaceForUnloadableClass() throws Exception {
BeanDefinitionBuilder builder =
BeanDefinitionBuilder.rootBeanDefinition(FACTORY_CLASS)
.addPropertyValue(DAO_INTERFACE_PROPERTY,
"com.acme.Foo");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(FACTORY_CLASS).addPropertyValue(
DAO_INTERFACE_PROPERTY, "com.acme.Foo");
when(beanFactory.getBeanDefinition(BEAN_NAME)).thenReturn(
builder.getBeanDefinition());
when(beanFactory.getBeanDefinition(BEAN_NAME)).thenReturn(builder.getBeanDefinition());
assertNotTypeDetected(FACTORY_CLASS);
}
@Test
public void doesNotResolveTypeForPlainBeanFactory() throws Exception {
@@ -111,11 +97,9 @@ public class RepositoryInterfaceAwareBeanPostProcessorUnitTests {
assertNotTypeDetected(FACTORY_CLASS);
}
private void assertNotTypeDetected(Class<?> beanClass) {
assertThat(processor.predictBeanType(beanClass, BEAN_NAME),
is(nullValue()));
assertThat(processor.predictBeanType(beanClass, BEAN_NAME), is(nullValue()));
}
private class User {

View File

@@ -36,10 +36,9 @@ import org.springframework.data.repository.core.support.RepositoryProxyPostProce
import org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
* Unit test for {@link TransactionalRepositoryProxyPostProcessor}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
@@ -52,44 +51,35 @@ public class TransactionRepositoryProxyPostProcessorUnitTests {
@Mock
ProxyFactory proxyFactory;
@Before
public void setUp() {
Map<String, PersistenceExceptionTranslator> beans =
new HashMap<String, PersistenceExceptionTranslator>();
Map<String, PersistenceExceptionTranslator> beans = new HashMap<String, PersistenceExceptionTranslator>();
beans.put("foo", mock(PersistenceExceptionTranslator.class));
when(
beanFactory.getBeansOfType(
eq(PersistenceExceptionTranslator.class), anyBoolean(),
anyBoolean())).thenReturn(beans);
when(beanFactory.getBeansOfType(eq(PersistenceExceptionTranslator.class), anyBoolean(), anyBoolean())).thenReturn(
beans);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullBeanFactory() throws Exception {
new TransactionalRepositoryProxyPostProcessor(null, "transactionManager");
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullTxManagerName() throws Exception {
new TransactionalRepositoryProxyPostProcessor(beanFactory, null);
}
@Test
public void setsUpBasicInstance() throws Exception {
RepositoryProxyPostProcessor postProcessor =
new TransactionalRepositoryProxyPostProcessor(beanFactory, "txManager");
RepositoryProxyPostProcessor postProcessor = new TransactionalRepositoryProxyPostProcessor(beanFactory, "txManager");
postProcessor.postProcess(proxyFactory);
verify(proxyFactory).addAdvice(
isA(PersistenceExceptionTranslationInterceptor.class));
verify(proxyFactory).addAdvice(isA(PersistenceExceptionTranslationInterceptor.class));
verify(proxyFactory).addAdvice(isA(TransactionInterceptor.class));
}
}

View File

@@ -25,62 +25,49 @@ import org.junit.Test;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/**
* Unit test for {@link Parameters}.
*
*
* @author Oliver Gierke
*/
public class ParametersUnitTests {
private Method valid;
@Before
public void setUp() throws SecurityException, NoSuchMethodException {
valid = SampleDao.class.getMethod("valid", String.class);
}
@Test
public void checksValidMethodCorrectly() throws Exception {
Method validWithPageable =
SampleDao.class.getMethod("validWithPageable", String.class,
Pageable.class);
Method validWithSort =
SampleDao.class.getMethod("validWithSort", String.class,
Sort.class);
Method validWithPageable = SampleDao.class.getMethod("validWithPageable", String.class, Pageable.class);
Method validWithSort = SampleDao.class.getMethod("validWithSort", String.class, Sort.class);
new Parameters(valid);
new Parameters(validWithPageable);
new Parameters(validWithSort);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsInvalidMethodWithParamMissing() throws Exception {
Method method =
SampleDao.class.getMethod("invalidParamMissing", String.class,
String.class);
Method method = SampleDao.class.getMethod("invalidParamMissing", String.class, String.class);
new Parameters(method);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullMethod() throws Exception {
new Parameters(null);
}
@Test
public void detectsNamedParameterCorrectly() throws Exception {
Parameters parameters =
getParametersFor("validWithSort", String.class, Sort.class);
Parameters parameters = getParametersFor("validWithSort", String.class, Sort.class);
Parameter parameter = parameters.getParameter(0);
@@ -93,20 +80,15 @@ public class ParametersUnitTests {
assertThat(parameter.isSpecialParameter(), is(true));
}
@Test
public void calculatesPlaceholderPositionCorrectly() throws Exception {
Method method =
SampleDao.class.getMethod("validWithSortFirst", Sort.class,
String.class);
Method method = SampleDao.class.getMethod("validWithSortFirst", Sort.class, String.class);
Parameters parameters = new Parameters(method);
assertThat(parameters.getBindableParameter(0).getIndex(), is(1));
method =
SampleDao.class.getMethod("validWithSortInBetween",
String.class, Sort.class, String.class);
method = SampleDao.class.getMethod("validWithSortInBetween", String.class, Sort.class, String.class);
parameters = new Parameters(method);
@@ -114,29 +96,26 @@ public class ParametersUnitTests {
assertThat(parameters.getBindableParameter(1).getIndex(), is(2));
}
@Test
public void detectsEmptyParameterListCorrectly() throws Exception {
Parameters parameters = getParametersFor("emptyParameters");
assertThat(parameters.hasParameterAt(0), is(false));
}
@Test
public void detectsPageableParameter() throws Exception {
Parameters parameters = getParametersFor("validWithPageable", String.class, Pageable.class);
assertThat(parameters.getPageableIndex(), is(1));
}
@Test
public void detectsSortParameter() throws Exception {
Parameters parameters = getParametersFor("validWithSort", String.class, Sort.class);
assertThat(parameters.getSortIndex(), is(1));
}
private Parameters getParametersFor(String methodName,
Class<?>... parameterTypes) throws SecurityException,
private Parameters getParametersFor(String methodName, Class<?>... parameterTypes) throws SecurityException,
NoSuchMethodException {
Method method = SampleDao.class.getMethod(methodName, parameterTypes);
@@ -152,24 +131,16 @@ public class ParametersUnitTests {
User valid(@Param("username") String username);
User invalidParamMissing(@Param("username") String username, String lastname);
User invalidParamMissing(@Param("username") String username,
String lastname);
User validWithPageable(@Param("username") String username,
Pageable pageable);
User validWithPageable(@Param("username") String username, Pageable pageable);
User validWithSort(@Param("username") String username, Sort sort);
User validWithSortFirst(Sort sort, String username);
User validWithSortInBetween(String firstname, Sort sort, String lastname);
User emptyParameters();
}

View File

@@ -57,14 +57,14 @@ public class QueryMethodUnitTests {
Method method = SampleRepository.class.getMethod("findByUsername", String.class);
new QueryMethod(method, metadata);
}
@Test
public void considersIterableMethodForCollectionQuery() throws Exception {
Method method = SampleRepository.class.getMethod("sampleMethod");
QueryMethod queryMethod = new QueryMethod(method, metadata);
assertThat(queryMethod.isCollectionQuery(), is(true));
}
@Test
public void doesNotConsiderPageMethodCollectionQuery() throws Exception {
Method method = SampleRepository.class.getMethod("anotherSampleMethod", Pageable.class);
@@ -79,8 +79,9 @@ public class QueryMethodUnitTests {
Page<String> pagingMethodWithoutPageable();
String findByUsername(String username);
Iterable<String> sampleMethod();
Page<String> anotherSampleMethod(Pageable pageable);
}
}

View File

@@ -24,108 +24,85 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/**
* Unit tests for {@link ParametersParameterAccessor}.
*
*
* @author Oliver Gierke
*/
public class SimpleParameterAccessorUnitTests {
Parameters parameters, sortParameters, pageableParameters;
@Before
public void setUp() throws SecurityException, NoSuchMethodException {
parameters =
new Parameters(Sample.class.getMethod("sample", String.class));
sortParameters =
new Parameters(Sample.class.getMethod("sample1", String.class,
Sort.class));
pageableParameters =
new Parameters(Sample.class.getMethod("sample2", String.class,
Pageable.class));
parameters = new Parameters(Sample.class.getMethod("sample", String.class));
sortParameters = new Parameters(Sample.class.getMethod("sample1", String.class, Sort.class));
pageableParameters = new Parameters(Sample.class.getMethod("sample2", String.class, Pageable.class));
}
@Test
public void testname() throws Exception {
new ParametersParameterAccessor(parameters, new Object[]{"test"});
new ParametersParameterAccessor(parameters, new Object[] { "test" });
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullParameters() throws Exception {
new ParametersParameterAccessor(null, new Object[0]);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullValues() throws Exception {
new ParametersParameterAccessor(parameters, null);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsTooLittleNumberOfArguments() throws Exception {
new ParametersParameterAccessor(parameters, new Object[0]);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsTooManyArguments() throws Exception {
new ParametersParameterAccessor(parameters, new Object[]{"test", "test"});
new ParametersParameterAccessor(parameters, new Object[] { "test", "test" });
}
@Test
public void returnsNullForPageableAndSortIfNoneAvailable() throws Exception {
ParameterAccessor accessor =
new ParametersParameterAccessor(parameters, new Object[]{"test"});
ParameterAccessor accessor = new ParametersParameterAccessor(parameters, new Object[] { "test" });
assertThat(accessor.getPageable(), is(nullValue()));
assertThat(accessor.getSort(), is(nullValue()));
}
@Test
public void returnsSortIfAvailable() {
Sort sort = new Sort("foo");
ParameterAccessor accessor =
new ParametersParameterAccessor(sortParameters, new Object[]{
"test", sort});
ParameterAccessor accessor = new ParametersParameterAccessor(sortParameters, new Object[] { "test", sort });
assertThat(accessor.getSort(), is(sort));
assertThat(accessor.getPageable(), is(nullValue()));
}
@Test
public void returnsPageableIfAvailable() {
Pageable pageable = new PageRequest(0, 10);
ParameterAccessor accessor =
new ParametersParameterAccessor(pageableParameters, new Object[]{
"test", pageable});
ParameterAccessor accessor = new ParametersParameterAccessor(pageableParameters, new Object[] { "test", pageable });
assertThat(accessor.getPageable(), is(pageable));
assertThat(accessor.getSort(), is(nullValue()));
}
@Test
public void returnsSortFromPageableIfAvailable() throws Exception {
Sort sort = new Sort("foo");
Pageable pageable = new PageRequest(0, 10, sort);
ParameterAccessor accessor =
new ParametersParameterAccessor(pageableParameters, new Object[]{
"test", pageable});
ParameterAccessor accessor = new ParametersParameterAccessor(pageableParameters, new Object[] { "test", pageable });
assertThat(accessor.getPageable(), is(pageable));
assertThat(accessor.getSort(), is(sort));
}
@@ -134,10 +111,8 @@ public class SimpleParameterAccessorUnitTests {
void sample(String firstname);
void sample1(String firstname, Sort sort);
void sample2(String firstname, Pageable pageable);
}
}

View File

@@ -23,10 +23,9 @@ import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
/**
* Unit test for {@link OrderBySource}.
*
*
* @author Oliver Gierke
*/
public class OrderBySourceUnitTests {
@@ -34,36 +33,28 @@ public class OrderBySourceUnitTests {
@Test
public void handlesSingleDirectionAndPropertyCorrectly() throws Exception {
assertThat(new OrderBySource("UsernameDesc").toSort(), is(new Sort(
DESC, "username")));
assertThat(new OrderBySource("UsernameDesc").toSort(), is(new Sort(DESC, "username")));
}
@Test
public void handlesCamelCasePropertyCorrecty() throws Exception {
assertThat(new OrderBySource("LastnameUsernameDesc").toSort(),
is(new Sort(DESC, "lastnameUsername")));
assertThat(new OrderBySource("LastnameUsernameDesc").toSort(), is(new Sort(DESC, "lastnameUsername")));
}
@Test
public void handlesMultipleDirectionsCorrectly() throws Exception {
OrderBySource orderBySource =
new OrderBySource("LastnameAscUsernameDesc");
assertThat(orderBySource.toSort(), is(new Sort(new Order(ASC,
"lastname"), new Order(DESC, "username"))));
OrderBySource orderBySource = new OrderBySource("LastnameAscUsernameDesc");
assertThat(orderBySource.toSort(), is(new Sort(new Order(ASC, "lastname"), new Order(DESC, "username"))));
}
@Test(expected = IllegalArgumentException.class)
public void rejectsMissingProperty() throws Exception {
new OrderBySource("Desc");
}
@Test
public void usesNestedPropertyCorrectly() throws Exception {

View File

@@ -21,7 +21,7 @@ import org.springframework.data.repository.RepositoryDefinition;
/**
* Sample interface for annotation based repository declaration.
*
*
* @author Oliver Gierke
*/
@RepositoryDefinition(domainClass = Object.class, idClass = Serializable.class)

View File

@@ -39,10 +39,9 @@ import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.core.EntityInformation;
import org.springframework.data.repository.core.support.RepositoryFactoryInformation;
/**
* Unit test for {@link DomainClassConverter}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
@@ -69,9 +68,8 @@ public class DomainClassConverterUnitTests {
@Mock
RepositoryFactoryInformation<User, Long> provider;
@Before
@SuppressWarnings({"unchecked", "rawtypes"})
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setUp() {
converter = new DomainClassConverter(service);
@@ -82,16 +80,13 @@ public class DomainClassConverterUnitTests {
Map<String, UserRepository> map = getBeanAsMap(repository);
when(context.getBeansOfType(UserRepository.class)).thenReturn(map);
when(context.getBeansOfType(RepositoryFactoryInformation.class))
.thenReturn(providers);
when(context.getBeansOfType(RepositoryFactoryInformation.class)).thenReturn(providers);
when(provider.getEntityInformation()).thenReturn(information);
when(provider.getRepositoryInterface()).thenReturn(
(Class) UserRepository.class);
when(provider.getRepositoryInterface()).thenReturn((Class) UserRepository.class);
when(information.getJavaType()).thenReturn(User.class);
when(information.getIdType()).thenReturn(Long.class);
}
@Test
public void matchFailsIfNoDaoAvailable() throws Exception {
@@ -99,7 +94,6 @@ public class DomainClassConverterUnitTests {
assertMatches(false);
}
@Test
public void matchesIfConversionInBetweenIsPossible() throws Exception {
@@ -111,10 +105,8 @@ public class DomainClassConverterUnitTests {
assertMatches(true);
}
@Test
public void matchFailsIfNoIntermediateConversionIsPossible()
throws Exception {
public void matchFailsIfNoIntermediateConversionIsPossible() throws Exception {
letContextContain(provider);
converter.setApplicationContext(context);
@@ -124,14 +116,11 @@ public class DomainClassConverterUnitTests {
assertMatches(false);
}
private void assertMatches(boolean matchExpected) {
assertThat(converter.matches(sourceDescriptor, targetDescriptor),
is(matchExpected));
assertThat(converter.matches(sourceDescriptor, targetDescriptor), is(matchExpected));
}
@Test
public void convertsStringToUserCorrectly() throws Exception {
@@ -142,21 +131,17 @@ public class DomainClassConverterUnitTests {
when(service.convert(anyString(), eq(Long.class))).thenReturn(1L);
when(repository.findOne(1L)).thenReturn(USER);
Object user =
converter.convert("1", sourceDescriptor, targetDescriptor);
Object user = converter.convert("1", sourceDescriptor, targetDescriptor);
assertThat(user, is(instanceOf(User.class)));
assertThat(user, is((Object) USER));
}
private void letContextContain(Object bean) {
Map<String, Object> beanMap = getBeanAsMap(bean);
when(context.getBeansOfType(argThat(is(subtypeOf(bean.getClass())))))
.thenReturn(beanMap);
when(context.getBeansOfType(argThat(is(subtypeOf(bean.getClass()))))).thenReturn(beanMap);
}
private <T> Map<String, T> getBeanAsMap(T bean) {
Map<String, T> beanMap = new HashMap<String, T>();
@@ -164,9 +149,7 @@ public class DomainClassConverterUnitTests {
return beanMap;
}
private static <T> TypeSafeMatcher<Class<T>> subtypeOf(
final Class<? extends T> type) {
private static <T> TypeSafeMatcher<Class<T>> subtypeOf(final Class<? extends T> type) {
return new TypeSafeMatcher<Class<T>>() {
@@ -175,7 +158,6 @@ public class DomainClassConverterUnitTests {
arg0.appendText("not a subtype of");
}
@Override
public boolean matchesSafely(Class<T> arg0) {

View File

@@ -37,17 +37,15 @@ import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.core.EntityInformation;
import org.springframework.data.repository.core.support.RepositoryFactoryInformation;
/**
* Unit test for {@link DomainClassPropertyEditorRegistrar}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
public class DomainClassPropertyEditorRegistrarUnitTests {
DomainClassPropertyEditorRegistrar registrar =
new DomainClassPropertyEditorRegistrar();
DomainClassPropertyEditorRegistrar registrar = new DomainClassPropertyEditorRegistrar();
@Mock
ApplicationContext context;
@Mock
@@ -61,27 +59,21 @@ public class DomainClassPropertyEditorRegistrarUnitTests {
DomainClassPropertyEditor<Entity, Long> reference;
@Before
@SuppressWarnings({"unchecked", "rawtypes"})
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setup() {
when(information.getJavaType()).thenReturn(Entity.class);
when(provider.getEntityInformation()).thenReturn(information);
when(provider.getRepositoryInterface()).thenReturn(
(Class) EntityRepository.class);
when(provider.getRepositoryInterface()).thenReturn((Class) EntityRepository.class);
Map<String, EntityRepository> map = getBeanAsMap(repository);
when(context.getBeansOfType(EntityRepository.class)).thenReturn(map);
reference =
new DomainClassPropertyEditor<Entity, Long>(repository,
information, registry);
reference = new DomainClassPropertyEditor<Entity, Long>(repository, information, registry);
}
@Test
public void addsRepositoryForEntityIfAvailableInAppContext()
throws Exception {
public void addsRepositoryForEntityIfAvailableInAppContext() throws Exception {
letContextContain(provider);
registrar.setApplicationContext(context);
@@ -90,27 +82,22 @@ public class DomainClassPropertyEditorRegistrarUnitTests {
verify(registry).registerCustomEditor(eq(Entity.class), eq(reference));
}
@Test
public void doesNotAddDaoAtAllIfNoDaosFound() throws Exception {
letContextContain(provider);
registrar.registerCustomEditors(registry);
verify(registry, never()).registerCustomEditor(eq(Entity.class),
eq(reference));
verify(registry, never()).registerCustomEditor(eq(Entity.class), eq(reference));
}
private void letContextContain(Object bean) {
Map<String, Object> beanMap = getBeanAsMap(bean);
when(context.getBeansOfType(argThat(is(subtypeOf(bean.getClass())))))
.thenReturn(beanMap);
when(context.getBeansOfType(argThat(is(subtypeOf(bean.getClass()))))).thenReturn(beanMap);
}
private <T> Map<String, T> getBeanAsMap(T bean) {
Map<String, T> beanMap = new HashMap<String, T>();
@@ -127,9 +114,7 @@ public class DomainClassPropertyEditorRegistrarUnitTests {
}
private static <T> TypeSafeMatcher<Class<T>> subtypeOf(
final Class<? extends T> type) {
private static <T> TypeSafeMatcher<Class<T>> subtypeOf(final Class<? extends T> type) {
return new TypeSafeMatcher<Class<T>>() {
@@ -138,7 +123,6 @@ public class DomainClassPropertyEditorRegistrarUnitTests {
arg0.appendText("not a subtype of");
}
@Override
public boolean matchesSafely(Class<T> arg0) {

View File

@@ -31,10 +31,9 @@ import org.springframework.data.domain.Persistable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.core.EntityInformation;
/**
* Unit test for {@link DomainClassPropertyEditor}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
@@ -49,17 +48,13 @@ public class DomainClassPropertyEditorUnitTests {
@Mock
EntityInformation<User, Integer> information;
@Before
public void setUp() {
when(information.getIdType()).thenReturn(Integer.class);
editor =
new DomainClassPropertyEditor<User, Integer>(userRepository,
information, registry);
editor = new DomainClassPropertyEditor<User, Integer>(userRepository, information, registry);
}
@Test
public void convertsPlainIdTypeCorrectly() throws Exception {
@@ -72,7 +67,6 @@ public class DomainClassPropertyEditorUnitTests {
verify(userRepository, times(1)).findOne(1);
}
@Test
public void convertsEntityToIdCorrectly() throws Exception {
@@ -82,22 +76,19 @@ public class DomainClassPropertyEditorUnitTests {
assertThat(editor.getAsText(), is("1"));
}
@Test
public void usesCustomEditorIfConfigured() throws Exception {
PropertyEditor customEditor = mock(PropertyEditor.class);
when(customEditor.getValue()).thenReturn(1);
when(registry.findCustomEditor(Integer.class, null)).thenReturn(
customEditor);
when(registry.findCustomEditor(Integer.class, null)).thenReturn(customEditor);
convertsPlainIdTypeCorrectly();
verify(customEditor, times(1)).setAsText("1");
}
@Test
public void returnsNullIdIfNoEntitySet() throws Exception {
@@ -105,23 +96,19 @@ public class DomainClassPropertyEditorUnitTests {
assertThat(editor.getAsText(), is(nullValue()));
}
@Test
public void resetsValueToNullAfterEmptyStringConversion() throws Exception {
assertValueResetToNullAfterConverting("");
}
@Test
public void resetsValueToNullAfterNullStringConversion() throws Exception {
assertValueResetToNullAfterConverting(null);
}
private void assertValueResetToNullAfterConverting(String source)
throws Exception {
private void assertValueResetToNullAfterConverting(String source) throws Exception {
convertsPlainIdTypeCorrectly();
assertThat(editor.getValue(), is(notNullValue()));
@@ -132,7 +119,7 @@ public class DomainClassPropertyEditorUnitTests {
/**
* Sample entity.
*
*
* @author Oliver Gierke
*/
@SuppressWarnings("serial")
@@ -140,13 +127,11 @@ public class DomainClassPropertyEditorUnitTests {
private Integer id;
public User(Integer id) {
this.id = id;
}
/*
* (non-Javadoc)
*
@@ -157,7 +142,6 @@ public class DomainClassPropertyEditorUnitTests {
return id;
}
/*
* (non-Javadoc)
*
@@ -171,7 +155,7 @@ public class DomainClassPropertyEditorUnitTests {
/**
* Sample generic DAO interface.
*
*
* @author Oliver Gierke
*/
private static interface UserRepository extends CrudRepository<User, Integer> {

View File

@@ -27,10 +27,9 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.Repository;
/**
* Unit test for {@link ClassUtils}.
*
*
* @author Oliver Gierke
*/
public class ClassUtilsUnitTests {
@@ -38,8 +37,7 @@ public class ClassUtilsUnitTests {
@Test(expected = IllegalStateException.class)
public void rejectsInvalidReturnType() throws Exception {
assertReturnTypeAssignable(SomeDao.class.getMethod("findByFirstname",
Pageable.class, String.class), User.class);
assertReturnTypeAssignable(SomeDao.class.getMethod("findByFirstname", Pageable.class, String.class), User.class);
}
@Test
@@ -55,7 +53,6 @@ public class ClassUtilsUnitTests {
private String firstname;
public String getAddress() {
return null;

View File

@@ -55,40 +55,33 @@ public class ClassTypeInformationUnitTests {
TypeInformation<?> content = wrapper.getProperty("content");
assertEquals(String.class, content.getType());
assertEquals(String.class,
discoverer.getProperty("wrapped").getProperty("content").getType());
assertEquals(String.class, discoverer.getProperty("wrapped.content")
.getType());
assertEquals(String.class, discoverer.getProperty("wrapped").getProperty("content").getType());
assertEquals(String.class, discoverer.getProperty("wrapped.content").getType());
}
@Test
@SuppressWarnings("rawtypes")
public void discoversBoundType() {
TypeInformation<GenericTypeWithBound> information = ClassTypeInformation.from(
GenericTypeWithBound.class);
TypeInformation<GenericTypeWithBound> information = ClassTypeInformation.from(GenericTypeWithBound.class);
assertEquals(Person.class, information.getProperty("person").getType());
}
@Test
public void discoversBoundTypeForSpecialization() {
TypeInformation<SpecialGenericTypeWithBound> information = ClassTypeInformation.from(
SpecialGenericTypeWithBound.class);
assertEquals(SpecialPerson.class, information.getProperty("person")
.getType());
TypeInformation<SpecialGenericTypeWithBound> information = ClassTypeInformation
.from(SpecialGenericTypeWithBound.class);
assertEquals(SpecialPerson.class, information.getProperty("person").getType());
}
@Test
@SuppressWarnings("rawtypes")
public void discoversBoundTypeForNested() {
TypeInformation<AnotherGenericType> information = ClassTypeInformation.from(
AnotherGenericType.class);
assertEquals(GenericTypeWithBound.class, information.getProperty("nested")
.getType());
assertEquals(Person.class, information.getProperty("nested.person")
.getType());
TypeInformation<AnotherGenericType> information = ClassTypeInformation.from(AnotherGenericType.class);
assertEquals(GenericTypeWithBound.class, information.getProperty("nested").getType());
assertEquals(Person.class, information.getProperty("nested.person").getType());
}
@Test
@@ -125,25 +118,25 @@ public class ClassTypeInformationUnitTests {
assertEquals(Map.class, map.getType());
assertEquals(Calendar.class, map.getMapValueType().getType());
}
@Test
public void typeInfoDoesNotEqualForGenericTypesWithDifferentParent() {
TypeInformation<ConcreteWrapper> first = ClassTypeInformation.from(ConcreteWrapper.class);
TypeInformation<AnotherConcreteWrapper> second = ClassTypeInformation.from(AnotherConcreteWrapper.class);
assertFalse(first.getProperty("wrapped").equals(second.getProperty("wrapped")));
}
@Test
public void handlesPropertyFieldMismatchCorrectly() {
TypeInformation<PropertyGetter> from = ClassTypeInformation.from(PropertyGetter.class);
TypeInformation<?> property = from.getProperty("_name");
assertThat(property, is(notNullValue()));
assertThat(property.getType(), is(typeCompatibleWith(String.class)));
property = from.getProperty("name");
assertThat(property, is(notNullValue()));
assertThat(property.getType(), is(typeCompatibleWith(byte[].class)));
@@ -166,14 +159,14 @@ public class ClassTypeInformationUnitTests {
public void resolvesWildCardTypeCorrectly() {
TypeInformation<ClassWithWildCardBound> information = ClassTypeInformation.from(ClassWithWildCardBound.class);
TypeInformation<?> property = information.getProperty("wildcard");
assertThat(property.isCollectionLike(), is(true));
assertThat(property.getComponentType().getType(), is(typeCompatibleWith(String.class)));
property = information.getProperty("complexWildcard");
assertThat(property.isCollectionLike(), is(true));
TypeInformation<?> component = property.getComponentType();
assertThat(component.isCollectionLike(), is(true));
assertThat(component.getComponentType().getType(), is(typeCompatibleWith(String.class)));
@@ -210,8 +203,7 @@ public class ClassTypeInformationUnitTests {
S nested;
}
static class SpecialGenericTypeWithBound extends
GenericTypeWithBound<SpecialPerson> {
static class SpecialGenericTypeWithBound extends GenericTypeWithBound<SpecialPerson> {
}
@@ -239,14 +231,14 @@ public class ClassTypeInformationUnitTests {
static class ConcreteWrapper extends GenericWrapper<String> {
}
static class AnotherConcreteWrapper extends GenericWrapper<Long> {
}
static class PropertyGetter {
private String _name;
public byte[] getName() {
return _name.getBytes();
}

View File

@@ -29,65 +29,66 @@ import org.mockito.runners.MockitoJUnitRunner;
/**
* Unit tests for {@link ParameterizedTypeInformation}.
*
*
* @author Oliver Gierke
*/
@RunWith(MockitoJUnitRunner.class)
public class ParameterizedTypeUnitTests {
@Mock ParameterizedType one, two;
@Mock
ParameterizedType one, two;
@Test
public void considersTypeInformationsWithDifferingParentsNotEqual() {
TypeDiscoverer<String> stringParent = new TypeDiscoverer<String>(String.class, null);
TypeDiscoverer<Object> objectParent = new TypeDiscoverer<Object>(Object.class, null);
ParameterizedTypeInformation<Object> first = new ParameterizedTypeInformation<Object>(one, stringParent);
ParameterizedTypeInformation<Object> second = new ParameterizedTypeInformation<Object>(one, objectParent);
assertFalse(first.equals(second));
}
@Test
public void considersTypeInformationsWithSameParentsNotEqual() {
TypeDiscoverer<String> stringParent = new TypeDiscoverer<String>(String.class, null);
ParameterizedTypeInformation<Object> first = new ParameterizedTypeInformation<Object>(one, stringParent);
ParameterizedTypeInformation<Object> second = new ParameterizedTypeInformation<Object>(one, stringParent);
assertTrue(first.equals(second));
}
/**
* @see DATACMNS-88
*/
@Test
public void resolvesMapValueTypeCorrectly() {
TypeInformation<Foo> type = ClassTypeInformation.from(Foo.class);
TypeInformation<?> propertyType = type.getProperty("param");
assertThat(propertyType.getProperty("value").getType(), is(typeCompatibleWith(String.class)));
assertThat(propertyType.getMapValueType().getType(), is(typeCompatibleWith(String.class)));
propertyType = type.getProperty("param2");
assertThat(propertyType.getProperty("value").getType(), is(typeCompatibleWith(String.class)));
assertThat(propertyType.getMapValueType().getType(), is(typeCompatibleWith(Locale.class)));
}
@SuppressWarnings("serial")
class Localized<S> extends HashMap<Locale, S> {
S value;
}
@SuppressWarnings("serial")
class Localized2<S> extends HashMap<S, Locale> {
S value;
}
class Foo {
Localized<String> param;
Localized2<String> param2;
Localized<String> param;
Localized2<String> param2;
}
}

View File

@@ -133,7 +133,7 @@ public class TypeDiscovererUnitTests {
assertThat(discoverer.getComponentType(), is(nullValue()));
assertThat(discoverer.getMapValueType(), is(nullValue()));
}
class SelfReferencing {
Map<String, SelfReferencingMap> parent;

View File

@@ -30,10 +30,9 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
/**
* Unit test for {@link PageableArgumentResolver}.
*
*
* @author Oliver Gierke - gierke@synyx.de
*/
public class PageableArgumentResolverUnitTests {
@@ -45,23 +44,14 @@ public class PageableArgumentResolverUnitTests {
MockHttpServletRequest request;
@Before
public void setUp() throws SecurityException, NoSuchMethodException {
correctMethod =
SampleController.class.getMethod("correctMethod",
Pageable.class, Pageable.class);
failedMethod =
SampleController.class.getMethod("failedMethod",
Pageable.class, Pageable.class);
invalidQualifiers =
SampleController.class.getMethod("invalidQualifiers",
Pageable.class, Pageable.class);
correctMethod = SampleController.class.getMethod("correctMethod", Pageable.class, Pageable.class);
failedMethod = SampleController.class.getMethod("failedMethod", Pageable.class, Pageable.class);
invalidQualifiers = SampleController.class.getMethod("invalidQualifiers", Pageable.class, Pageable.class);
defaultsMethod =
SampleController.class.getMethod("defaultsMethod",
Pageable.class);
defaultsMethod = SampleController.class.getMethod("defaultsMethod", Pageable.class);
request = new MockHttpServletRequest();
@@ -74,7 +64,6 @@ public class PageableArgumentResolverUnitTests {
request.addParameter("bar_page.size", "60");
}
@Test
public void testname() throws Exception {
@@ -82,7 +71,6 @@ public class PageableArgumentResolverUnitTests {
assertSizeForPrefix(60, null, 1);
}
@Test(expected = IllegalStateException.class)
public void rejectsInvalidlyMappedPageables() throws Exception {
@@ -92,7 +80,6 @@ public class PageableArgumentResolverUnitTests {
new PageableArgumentResolver().resolveArgument(parameter, webRequest);
}
@Test(expected = IllegalStateException.class)
public void rejectsInvalidQualifiers() throws Exception {
@@ -102,13 +89,11 @@ public class PageableArgumentResolverUnitTests {
new PageableArgumentResolver().resolveArgument(parameter, webRequest);
}
@Test
public void assertDefaults() throws Exception {
MethodParameter parameter = new MethodParameter(defaultsMethod, 0);
NativeWebRequest webRequest =
new ServletWebRequest(new MockHttpServletRequest());
NativeWebRequest webRequest = new ServletWebRequest(new MockHttpServletRequest());
PageableArgumentResolver resolver = new PageableArgumentResolver();
Object argument = resolver.resolveArgument(parameter, webRequest);
@@ -116,11 +101,9 @@ public class PageableArgumentResolverUnitTests {
Pageable pageable = (Pageable) argument;
assertEquals(SampleController.DEFAULT_PAGESIZE, pageable.getPageSize());
assertEquals(SampleController.DEFAULT_PAGENUMBER,
pageable.getPageNumber());
assertEquals(SampleController.DEFAULT_PAGENUMBER, pageable.getPageNumber());
}
@Test
public void assertOverridesDefaults() throws Exception {
@@ -141,9 +124,7 @@ public class PageableArgumentResolverUnitTests {
assertEquals(sizeParam - 1, pageable.getPageNumber());
}
private void assertSizeForPrefix(int size, Sort sort, int index)
throws Exception {
private void assertSizeForPrefix(int size, Sort sort, int index) throws Exception {
MethodParameter parameter = new MethodParameter(correctMethod, index);
NativeWebRequest webRequest = new ServletWebRequest(request);
@@ -167,26 +148,20 @@ public class PageableArgumentResolverUnitTests {
static final int DEFAULT_PAGESIZE = 198;
static final int DEFAULT_PAGENUMBER = 42;
public void defaultsMethod(
@PageableDefaults(value = DEFAULT_PAGESIZE, pageNumber = DEFAULT_PAGENUMBER) Pageable pageable) {
}
public void correctMethod(@Qualifier("foo") Pageable first,
@Qualifier("bar") Pageable second) {
public void correctMethod(@Qualifier("foo") Pageable first, @Qualifier("bar") Pageable second) {
}
public void failedMethod(Pageable first, Pageable second) {
}
public void invalidQualifiers(@Qualifier("foo") Pageable first,
@Qualifier("foo") Pageable second) {
public void invalidQualifiers(@Qualifier("foo") Pageable first, @Qualifier("foo") Pageable second) {
}
}