DATAREST-1008 - Adapt to API changes in Spring Data Commons, Java 8 upgrades and Mockito 2.7.
This commit is contained in:
@@ -57,6 +57,12 @@
|
||||
<version>${jackson}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jdk8</artifactId>
|
||||
<version>${jackson}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
@@ -73,4 +79,19 @@
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${source.level}</source>
|
||||
<target>${source.level}</target>
|
||||
<compilerArgument>-parameters</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -18,6 +18,7 @@ package org.springframework.data.rest.core;
|
||||
import java.net.URI;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.core.convert.ConversionFailedException;
|
||||
@@ -25,6 +26,7 @@ import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.converter.ConditionalGenericConverter;
|
||||
import org.springframework.core.convert.converter.GenericConverter;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.context.PersistentEntities;
|
||||
import org.springframework.data.repository.support.Repositories;
|
||||
import org.springframework.data.repository.support.RepositoryInvokerFactory;
|
||||
@@ -66,9 +68,9 @@ public class UriToEntityConverter implements ConditionalGenericConverter {
|
||||
for (TypeInformation<?> domainType : entities.getManagedTypes()) {
|
||||
|
||||
Class<?> rawType = domainType.getType();
|
||||
PersistentEntity<?, ?> entity = entities.getPersistentEntity(rawType);
|
||||
Optional<PersistentEntity<?, ? extends PersistentProperty<?>>> entity = entities.getPersistentEntity(rawType);
|
||||
|
||||
if (entity != null && entity.hasIdProperty()) {
|
||||
if (entity.map(it -> it.hasIdProperty()).orElse(false)) {
|
||||
convertiblePairs.add(new ConvertiblePair(URI.class, domainType.getType()));
|
||||
}
|
||||
}
|
||||
@@ -86,7 +88,7 @@ public class UriToEntityConverter implements ConditionalGenericConverter {
|
||||
@Override
|
||||
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
|
||||
return !sourceType.equals(URI_TYPE) ? false
|
||||
: repositories.getRepositoryInformationFor(targetType.getType()) != null;
|
||||
: repositories.getRepositoryInformationFor(targetType.getType()).isPresent();
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -105,9 +107,10 @@ public class UriToEntityConverter implements ConditionalGenericConverter {
|
||||
@Override
|
||||
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
|
||||
|
||||
PersistentEntity<?, ?> entity = entities.getPersistentEntity(targetType.getType());
|
||||
Optional<PersistentEntity<?, ? extends PersistentProperty<?>>> entity = entities
|
||||
.getPersistentEntity(targetType.getType());
|
||||
|
||||
if (entity == null) {
|
||||
if (!entity.isPresent()) {
|
||||
throw new ConversionFailedException(sourceType, targetType, source,
|
||||
new IllegalArgumentException("No PersistentEntity information available for " + targetType.getType()));
|
||||
}
|
||||
@@ -120,6 +123,6 @@ public class UriToEntityConverter implements ConditionalGenericConverter {
|
||||
"Cannot resolve URI " + uri + ". Is it local or remote? Only local URIs are resolvable."));
|
||||
}
|
||||
|
||||
return invokerFactory.getInvokerFor(targetType.getType()).invokeFindOne(parts[parts.length - 1]);
|
||||
return invokerFactory.getInvokerFor(targetType.getType()).invokeFindOne(parts[parts.length - 1]).orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ package org.springframework.data.rest.core;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.ConfigurablePropertyAccessor;
|
||||
@@ -83,17 +84,11 @@ public class ValidationErrors extends AbstractPropertyBindingResult {
|
||||
do {
|
||||
|
||||
String segment = iterator.next();
|
||||
PersistentEntity<?, ?> entity = entities.getPersistentEntity(value.getClass());
|
||||
PersistentProperty<?> property = entity.getPersistentProperty(PropertyAccessorUtils.getPropertyName(segment));
|
||||
|
||||
if (property == null) {
|
||||
throw new NotReadablePropertyException(source.getClass(), propertyName);
|
||||
}
|
||||
Optional<? extends PersistentProperty<?>> property = entities.getPersistentEntity(value.getClass())//
|
||||
.flatMap(it -> it.getPersistentProperty(PropertyAccessorUtils.getPropertyName(segment)));
|
||||
|
||||
ConfigurablePropertyAccessor accessor = property.usePropertyAccess()
|
||||
? PropertyAccessorFactory.forBeanPropertyAccess(value)
|
||||
: PropertyAccessorFactory.forDirectFieldAccess(value);
|
||||
value = accessor.getPropertyValue(segment);
|
||||
value = getValue(value, property, segment, propertyName);
|
||||
|
||||
} while (iterator.hasNext());
|
||||
|
||||
@@ -110,4 +105,18 @@ public class ValidationErrors extends AbstractPropertyBindingResult {
|
||||
public Object getTarget() {
|
||||
return source;
|
||||
}
|
||||
|
||||
private static Object getValue(Object source, Optional<? extends PersistentProperty<?>> property, String segment,
|
||||
String name) {
|
||||
|
||||
return property.map(it -> {
|
||||
|
||||
ConfigurablePropertyAccessor accessor = it.usePropertyAccess()
|
||||
? PropertyAccessorFactory.forBeanPropertyAccess(source)
|
||||
: PropertyAccessorFactory.forDirectFieldAccess(source);
|
||||
|
||||
return accessor.getPropertyValue(segment);
|
||||
|
||||
}).orElseThrow(() -> new NotReadablePropertyException(source.getClass(), name));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import lombok.Value;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.repository.Repository;
|
||||
@@ -188,11 +189,15 @@ class EntityLookupConfiguration implements EntityLookupRegistrar {
|
||||
Assert.notNull(repositories, "Repositories must not be null!");
|
||||
Assert.notNull(lookupInformation, "LookupInformation must not be null!");
|
||||
|
||||
RepositoryInformation information = repositories.getRepositoryInformation(lookupInformation.repositoryType);
|
||||
RepositoryInformation information = repositories.getRepositoryInformation(lookupInformation.repositoryType)//
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"No repository found for type " + lookupInformation.repositoryType.getName() + "!"));
|
||||
|
||||
this.repository = (Repository<? extends T, ?>) repositories.getRepositoryFor(information.getDomainType());
|
||||
this.domainType = information.getDomainType();
|
||||
this.lookupInfo = lookupInformation;
|
||||
this.repository = (Repository<? extends T, ?>) repositories.getRepositoryFor(information.getDomainType())//
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"No repository found for type " + information.getDomainType().getName() + "!"));
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -209,8 +214,8 @@ class EntityLookupConfiguration implements EntityLookupRegistrar {
|
||||
* @see org.springframework.data.rest.core.support.EntityLookup#lookupEntity(java.io.Serializable)
|
||||
*/
|
||||
@Override
|
||||
public Object lookupEntity(Serializable id) {
|
||||
return lookupInfo.getLookup().lookup(repository, id);
|
||||
public Optional<Object> lookupEntity(Serializable id) {
|
||||
return Optional.ofNullable(lookupInfo.getLookup().lookup(repository, id));
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -64,7 +64,6 @@ public class RepositoryRestConfiguration {
|
||||
private final ProjectionDefinitionConfiguration projectionConfiguration;
|
||||
private final MetadataConfiguration metadataConfiguration;
|
||||
private final EntityLookupConfiguration entityLookupConfiguration;
|
||||
private final List<Class<?>> valueTypes = new ArrayList<Class<?>>();
|
||||
|
||||
private final EnumTranslationConfiguration enumTranslationConfiguration;
|
||||
private boolean enableEnumTranslation = false;
|
||||
|
||||
@@ -24,6 +24,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
@@ -179,14 +180,14 @@ public class CrudMethodsSupportedHttpMethods implements SupportedHttpMethods {
|
||||
return exposes(crudMethods.getFindAllMethod());
|
||||
}
|
||||
|
||||
private static boolean exposes(Method method) {
|
||||
private static boolean exposes(Optional<Method> method) {
|
||||
|
||||
if (method == null) {
|
||||
return false;
|
||||
}
|
||||
return method.map(it -> {
|
||||
|
||||
RestResource annotation = AnnotationUtils.findAnnotation(method, RestResource.class);
|
||||
return annotation == null ? true : annotation.exported();
|
||||
RestResource annotation = AnnotationUtils.findAnnotation(it, RestResource.class);
|
||||
return annotation == null ? true : annotation.exported();
|
||||
|
||||
}).orElse(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ package org.springframework.data.rest.core.mapping;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.mapping.Association;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
@@ -55,8 +56,8 @@ class MappingResourceMetadata extends TypeBasedCollectionResourceMapping impleme
|
||||
this.entity.doWithAssociations(propertyMappings);
|
||||
this.entity.doWithProperties(propertyMappings);
|
||||
|
||||
RestResource annotation = entity.findAnnotation(RestResource.class);
|
||||
this.explicitlyExported = annotation != null && annotation.exported();
|
||||
Optional<RestResource> annotation = entity.findAnnotation(RestResource.class);
|
||||
this.explicitlyExported = annotation.map(it -> it.exported()).orElse(false);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -20,6 +20,7 @@ import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
@@ -84,23 +85,23 @@ public class PersistentEntitiesResourceMappings implements ResourceMappings {
|
||||
MappingResourceMetadata getMappingMetadataFor(Class<?> type) {
|
||||
|
||||
Assert.notNull(type, "Type must not be null!");
|
||||
type = ClassUtils.getUserClass(type);
|
||||
Class<?> userType = ClassUtils.getUserClass(type);
|
||||
|
||||
MappingResourceMetadata mappingMetadata = mappingCache.get(type);
|
||||
MappingResourceMetadata mappingMetadata = mappingCache.get(userType);
|
||||
|
||||
if (mappingMetadata != null) {
|
||||
return mappingMetadata;
|
||||
}
|
||||
|
||||
PersistentEntity<?, ?> entity = entities.getPersistentEntity(type);
|
||||
Optional<PersistentEntity<?, ? extends PersistentProperty<?>>> entity = entities.getPersistentEntity(userType);
|
||||
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
return entity.map(it -> {
|
||||
|
||||
mappingMetadata = new MappingResourceMetadata(entity, this);
|
||||
mappingCache.put(type, mappingMetadata);
|
||||
return mappingMetadata;
|
||||
MappingResourceMetadata metadata = new MappingResourceMetadata(it, this);
|
||||
mappingCache.put(userType, metadata);
|
||||
return metadata;
|
||||
|
||||
}).orElse(null);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -15,10 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.rest.core.Path;
|
||||
import org.springframework.data.rest.core.annotation.Description;
|
||||
import org.springframework.data.rest.core.annotation.RestResource;
|
||||
import org.springframework.data.util.Optionals;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@@ -31,8 +34,8 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping
|
||||
|
||||
private final PersistentProperty<?> property;
|
||||
private final ResourceMappings mappings;
|
||||
private final RestResource annotation;
|
||||
private final Description description;
|
||||
private final Optional<RestResource> annotation;
|
||||
private final Optional<Description> description;
|
||||
|
||||
/**
|
||||
* Creates a new {@link RootPropertyResourceMapping}.
|
||||
@@ -46,7 +49,7 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping
|
||||
|
||||
this.property = property;
|
||||
this.mappings = mappings;
|
||||
this.annotation = property.isAssociation() ? property.findAnnotation(RestResource.class) : null;
|
||||
this.annotation = property.isAssociation() ? property.findAnnotation(RestResource.class) : Optional.empty();
|
||||
this.description = property.findAnnotation(Description.class);
|
||||
}
|
||||
|
||||
@@ -56,8 +59,10 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping
|
||||
*/
|
||||
@Override
|
||||
public Path getPath() {
|
||||
return annotation != null && StringUtils.hasText(annotation.path()) ? new Path(annotation.path()) : new Path(
|
||||
property.getName());
|
||||
|
||||
return annotation.filter(it -> StringUtils.hasText(it.path()))//
|
||||
.map(it -> new Path(it.path()))//
|
||||
.orElseGet(() -> new Path(property.getName()));
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -66,7 +71,10 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping
|
||||
*/
|
||||
@Override
|
||||
public String getRel() {
|
||||
return annotation != null && StringUtils.hasText(annotation.rel()) ? annotation.rel() : property.getName();
|
||||
|
||||
return annotation.filter(it -> StringUtils.hasText(it.rel()))//
|
||||
.map(it -> it.rel())//
|
||||
.orElseGet(() -> property.getName());
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -81,7 +89,7 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping
|
||||
}
|
||||
|
||||
ResourceMapping typeMapping = mappings.getMetadataFor(property.getActualType());
|
||||
return !typeMapping.isExported() ? false : annotation == null ? true : annotation.exported();
|
||||
return !typeMapping.isExported() ? false : annotation.map(it -> it.exported()).orElse(true);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -103,15 +111,11 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping
|
||||
CollectionResourceMapping ownerTypeMapping = mappings.getMetadataFor(property.getOwner().getType());
|
||||
ResourceDescription fallback = TypedResourceDescription.defaultFor(ownerTypeMapping.getItemResourceRel(), property);
|
||||
|
||||
if (description != null) {
|
||||
return new AnnotationBasedResourceDescription(description, fallback);
|
||||
}
|
||||
|
||||
if (annotation != null) {
|
||||
return new AnnotationBasedResourceDescription(annotation.description(), fallback);
|
||||
}
|
||||
|
||||
return fallback;
|
||||
return Optionals
|
||||
.<ResourceDescription> firstNonEmpty(//
|
||||
() -> description.map(it -> new AnnotationBasedResourceDescription(it, fallback)), //
|
||||
() -> annotation.map(it -> new AnnotationBasedResourceDescription(it.description(), fallback)))
|
||||
.orElse(fallback);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -81,7 +81,7 @@ public class RepositoryResourceMappings extends PersistentEntitiesResourceMappin
|
||||
|
||||
for (Class<?> type : repositories) {
|
||||
|
||||
RepositoryInformation repositoryInformation = repositories.getRepositoryInformationFor(type);
|
||||
RepositoryInformation repositoryInformation = repositories.getRequiredRepositoryInformation(type);
|
||||
Class<?> repositoryInterface = repositoryInformation.getRepositoryInterface();
|
||||
PersistentEntity<?, ?> entity = repositories.getPersistentEntity(type);
|
||||
|
||||
@@ -111,7 +111,7 @@ public class RepositoryResourceMappings extends PersistentEntitiesResourceMappin
|
||||
return searchCache.get(domainType);
|
||||
}
|
||||
|
||||
RepositoryInformation repositoryInformation = repositories.getRepositoryInformationFor(domainType);
|
||||
RepositoryInformation repositoryInformation = repositories.getRequiredRepositoryInformation(domainType);
|
||||
List<MethodResourceMapping> mappings = new ArrayList<MethodResourceMapping>();
|
||||
ResourceMetadata resourceMapping = getMetadataFor(domainType);
|
||||
|
||||
|
||||
@@ -15,10 +15,12 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import org.springframework.data.util.Streamable;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface ResourceMappings extends Iterable<ResourceMetadata> {
|
||||
public interface ResourceMappings extends Streamable<ResourceMetadata> {
|
||||
|
||||
/**
|
||||
* Returns a {@link ResourceMetadata} for the given type if available.
|
||||
|
||||
@@ -17,12 +17,10 @@ package org.springframework.data.rest.core.support;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.context.PersistentEntities;
|
||||
import org.springframework.data.rest.core.util.Java8PluginRegistry;
|
||||
import org.springframework.hateoas.EntityLinks;
|
||||
import org.springframework.hateoas.Link;
|
||||
import org.springframework.plugin.core.OrderAwarePluginRegistry;
|
||||
import org.springframework.plugin.core.PluginRegistry;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
@@ -37,7 +35,7 @@ public class DefaultSelfLinkProvider implements SelfLinkProvider {
|
||||
|
||||
private final PersistentEntities entities;
|
||||
private final EntityLinks entityLinks;
|
||||
private final PluginRegistry<EntityLookup<?>, Class<?>> lookups;
|
||||
private final Java8PluginRegistry<EntityLookup<?>, Class<?>> lookups;
|
||||
|
||||
/**
|
||||
* Creates a new {@link DefaultSelfLinkProvider} from the {@link PersistentEntities}, {@link EntityLinks} and
|
||||
@@ -56,7 +54,7 @@ public class DefaultSelfLinkProvider implements SelfLinkProvider {
|
||||
|
||||
this.entities = entities;
|
||||
this.entityLinks = entityLinks;
|
||||
this.lookups = OrderAwarePluginRegistry.create(lookups);
|
||||
this.lookups = Java8PluginRegistry.of(lookups);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -81,19 +79,16 @@ public class DefaultSelfLinkProvider implements SelfLinkProvider {
|
||||
|
||||
Class<? extends Object> instanceType = instance.getClass();
|
||||
|
||||
EntityLookup<Object> lookup = (EntityLookup<Object>) lookups.getPluginFor(instanceType);
|
||||
return lookups.getPluginFor(instanceType)//
|
||||
.map(it -> it.getClass().cast(it))//
|
||||
.map(it -> (Object) it.getResourceIdentifier(instance))//
|
||||
.orElseGet(() -> identifierOrNull(instance));
|
||||
}
|
||||
|
||||
if (lookup != null) {
|
||||
return lookup.getResourceIdentifier(instance);
|
||||
}
|
||||
private Object identifierOrNull(Object instance) {
|
||||
|
||||
PersistentEntity<?, ?> entity = entities.getPersistentEntity(instanceType);
|
||||
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Cannot create self link for %s! No persistent entity found!", instanceType));
|
||||
}
|
||||
|
||||
return entity.getIdentifierAccessor(instance).getIdentifier();
|
||||
return entities.getRequiredPersistentEntity(instance.getClass())//
|
||||
.getIdentifierAccessor(instance).getIdentifier()//
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ package org.springframework.data.rest.core.support;
|
||||
|
||||
import static org.springframework.data.rest.core.support.DomainObjectMerger.NullHandlingPolicy.*;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.data.mapping.Association;
|
||||
@@ -87,18 +89,18 @@ public class DomainObjectMerger {
|
||||
@Override
|
||||
public void doWithPersistentProperty(PersistentProperty<?> persistentProperty) {
|
||||
|
||||
Object sourceValue = sourceWrapper.getProperty(persistentProperty);
|
||||
Object targetValue = targetWrapper.getProperty(persistentProperty);
|
||||
Optional<Object> sourceValue = sourceWrapper.getProperty(persistentProperty);
|
||||
Optional<Object> targetValue = targetWrapper.getProperty(persistentProperty);
|
||||
|
||||
if (targetEntity.isIdProperty(persistentProperty)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ObjectUtils.nullSafeEquals(sourceValue, targetValue)) {
|
||||
if (sourceValue.equals(targetValue)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nullPolicy == APPLY_NULLS || sourceValue != null) {
|
||||
if (nullPolicy == APPLY_NULLS || sourceValue.isPresent()) {
|
||||
targetWrapper.setProperty(persistentProperty, sourceValue);
|
||||
}
|
||||
}
|
||||
@@ -114,7 +116,7 @@ public class DomainObjectMerger {
|
||||
public void doWithAssociation(Association<? extends PersistentProperty<?>> association) {
|
||||
|
||||
PersistentProperty<?> persistentProperty = association.getInverse();
|
||||
Object fromVal = sourceWrapper.getProperty(persistentProperty);
|
||||
Optional<Object> fromVal = sourceWrapper.getProperty(persistentProperty);
|
||||
|
||||
if (!isNullOrEmpty(fromVal) && !fromVal.equals(targetWrapper.getProperty(persistentProperty))) {
|
||||
targetWrapper.setProperty(persistentProperty, fromVal);
|
||||
@@ -130,21 +132,21 @@ public class DomainObjectMerger {
|
||||
* @param source can be {@literal null}.
|
||||
* @return
|
||||
*/
|
||||
static boolean isNullOrEmpty(Object source) {
|
||||
static boolean isNullOrEmpty(Optional<Object> source) {
|
||||
|
||||
if (source == null) {
|
||||
return true;
|
||||
}
|
||||
return source.map(it -> {
|
||||
|
||||
if (source instanceof Iterable) {
|
||||
return !((Iterable<?>) source).iterator().hasNext();
|
||||
}
|
||||
if (it instanceof Iterable) {
|
||||
return !((Iterable<?>) it).iterator().hasNext();
|
||||
}
|
||||
|
||||
if (ObjectUtils.isArray(source)) {
|
||||
return ObjectUtils.isEmpty((Object[]) source);
|
||||
}
|
||||
if (ObjectUtils.isArray(it)) {
|
||||
return ObjectUtils.isEmpty((Object[]) it);
|
||||
}
|
||||
|
||||
return false;
|
||||
return false;
|
||||
|
||||
}).orElse(true);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
package org.springframework.data.rest.core.support;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.plugin.core.Plugin;
|
||||
|
||||
@@ -54,5 +55,5 @@ public interface EntityLookup<T> extends Plugin<Class<?>> {
|
||||
* @param id will never be {@literal null}.
|
||||
* @return can be {@literal null}.
|
||||
*/
|
||||
Object lookupEntity(Serializable id);
|
||||
Optional<Object> lookupEntity(Serializable id);
|
||||
}
|
||||
|
||||
@@ -20,11 +20,7 @@ import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
@@ -32,10 +28,8 @@ import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.repository.support.RepositoryInvoker;
|
||||
import org.springframework.data.repository.support.RepositoryInvokerFactory;
|
||||
import org.springframework.plugin.core.OrderAwarePluginRegistry;
|
||||
import org.springframework.plugin.core.PluginRegistry;
|
||||
import org.springframework.data.rest.core.util.Java8PluginRegistry;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
/**
|
||||
@@ -46,42 +40,8 @@ import org.springframework.util.MultiValueMap;
|
||||
*/
|
||||
public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFactory {
|
||||
|
||||
private static final List<Converter<Object, Object>> CONVERTERS;
|
||||
|
||||
static {
|
||||
|
||||
List<Converter<Object, Object>> converters = new ArrayList<Converter<Object, Object>>();
|
||||
ClassLoader classLoader = UnwrappingRepositoryInvokerFactory.class.getClassLoader();
|
||||
|
||||
// Add unwrapper for Java 8 Optional
|
||||
|
||||
if (ClassUtils.isPresent("java.util.Optional", classLoader)) {
|
||||
converters.add(new Converter<Object, Object>() {
|
||||
@Override
|
||||
public Object convert(Object source) {
|
||||
return source instanceof Optional ? ((Optional<?>) source).orElse(null) : source;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Add unwrapper for Guava Optional
|
||||
|
||||
if (ClassUtils.isPresent("com.google.common.base.Optional", classLoader)) {
|
||||
|
||||
converters.add(new Converter<Object, Object>() {
|
||||
@Override
|
||||
public Object convert(Object source) {
|
||||
return source instanceof com.google.common.base.Optional
|
||||
? ((com.google.common.base.Optional<?>) source).orNull() : source;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
CONVERTERS = Collections.unmodifiableList(converters);
|
||||
}
|
||||
|
||||
private final RepositoryInvokerFactory delegate;
|
||||
private final PluginRegistry<EntityLookup<?>, Class<?>> lookups;
|
||||
private final Java8PluginRegistry<EntityLookup<?>, Class<?>> lookups;
|
||||
|
||||
/**
|
||||
* @param delegate must not be {@literal null}.
|
||||
@@ -94,7 +54,7 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact
|
||||
Assert.notNull(lookups, "EntityLookups must not be null!");
|
||||
|
||||
this.delegate = delegate;
|
||||
this.lookups = OrderAwarePluginRegistry.create(lookups);
|
||||
this.lookups = Java8PluginRegistry.of(lookups);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -104,9 +64,9 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact
|
||||
@Override
|
||||
public RepositoryInvoker getInvokerFor(Class<?> domainType) {
|
||||
|
||||
EntityLookup<?> lookup = lookups.getPluginFor(domainType);
|
||||
Optional<EntityLookup<?>> lookup = lookups.getPluginFor(domainType);
|
||||
|
||||
return new UnwrappingRepositoryInvoker(delegate.getInvokerFor(domainType), CONVERTERS, lookup);
|
||||
return new UnwrappingRepositoryInvoker(delegate.getInvokerFor(domainType), lookup);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,25 +79,18 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact
|
||||
private static class UnwrappingRepositoryInvoker implements RepositoryInvoker {
|
||||
|
||||
private final @NonNull RepositoryInvoker delegate;
|
||||
private final @NonNull Collection<Converter<Object, Object>> converters;
|
||||
private final EntityLookup<?> lookup;
|
||||
private final @NonNull Optional<EntityLookup<?>> lookup;
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.support.RepositoryInvoker#invokeFindOne(java.io.Serializable)
|
||||
*/
|
||||
public <T> T invokeFindOne(Serializable id) {
|
||||
return postProcess(lookup != null ? lookup.lookupEntity(id) : delegate.invokeFindOne(id));
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> Optional<T> invokeFindOne(Serializable id) {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.support.RepositoryInvoker#invokeQueryMethod(java.lang.reflect.Method, java.util.Map, org.springframework.data.domain.Pageable, org.springframework.data.domain.Sort)
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public Object invokeQueryMethod(Method method, Map<String, String[]> parameters, Pageable pageable, Sort sort) {
|
||||
return postProcess(delegate.invokeQueryMethod(method, parameters, pageable, sort));
|
||||
return (Optional<T>) lookup//
|
||||
.map(it -> it.lookupEntity(id).orElse(Optional.empty()))//
|
||||
.orElseGet(() -> delegate.invokeFindOne(id));
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -145,9 +98,9 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact
|
||||
* @see org.springframework.data.repository.support.RepositoryInvoker#invokeQueryMethod(java.lang.reflect.Method, org.springframework.util.MultiValueMap, org.springframework.data.domain.Pageable, org.springframework.data.domain.Sort)
|
||||
*/
|
||||
@Override
|
||||
public Object invokeQueryMethod(Method method, MultiValueMap<String, ? extends Object> parameters,
|
||||
public Optional<Object> invokeQueryMethod(Method method, MultiValueMap<String, ? extends Object> parameters,
|
||||
Pageable pageable, Sort sort) {
|
||||
return postProcess(delegate.invokeQueryMethod(method, parameters, pageable, sort));
|
||||
return delegate.invokeQueryMethod(method, parameters, pageable, sort);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -221,21 +174,5 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact
|
||||
public <T> T invokeSave(T object) {
|
||||
return delegate.invokeSave(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the configured converters for the given result.
|
||||
*
|
||||
* @param result can be {@literal null}.
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> T postProcess(Object result) {
|
||||
|
||||
for (Converter<Object, Object> converter : converters) {
|
||||
result = converter.convert(result);
|
||||
}
|
||||
|
||||
return (T) result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.rest.core.util;
|
||||
|
||||
/**
|
||||
* Simple function interface.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface Function<S, T> {
|
||||
|
||||
T apply(S input) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright 2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.rest.core.util;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.plugin.core.OrderAwarePluginRegistry;
|
||||
import org.springframework.plugin.core.Plugin;
|
||||
import org.springframework.plugin.core.PluginRegistry;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class Java8PluginRegistry<T extends Plugin<S>, S> {
|
||||
|
||||
private final PluginRegistry<T, S> registry;
|
||||
|
||||
public static <T extends Plugin<S>, S> Java8PluginRegistry<T, S> of(List<? extends T> plugins) {
|
||||
return Java8PluginRegistry.of(OrderAwarePluginRegistry.create(plugins));
|
||||
}
|
||||
|
||||
public static <T extends Plugin<S>, S> Java8PluginRegistry<T, S> of(PluginRegistry<T, S> plugins) {
|
||||
return new Java8PluginRegistry<>(plugins);
|
||||
}
|
||||
|
||||
public static <T extends Plugin<S>, S> Java8PluginRegistry<T, S> empty() {
|
||||
return Java8PluginRegistry.of(Collections.emptyList());
|
||||
}
|
||||
|
||||
public Optional<T> getPluginFor(S delimiter) {
|
||||
return Optional.ofNullable(registry.getPluginFor(delimiter));
|
||||
}
|
||||
|
||||
public T getPluginOrDefaultFor(S delimiter, T fallback) {
|
||||
return getPluginFor(delimiter).orElse(fallback);
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ import org.springframework.util.MultiValueMap;
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public abstract class MapUtils {
|
||||
public interface MapUtils {
|
||||
|
||||
/**
|
||||
* Turns a {@link MultiValueMap} into its {@link Map} equivalent.
|
||||
|
||||
@@ -26,11 +26,9 @@ import org.springframework.util.ReflectionUtils;
|
||||
* @author Jon Brisbin
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public abstract class Methods {
|
||||
public interface Methods {
|
||||
|
||||
private Methods() {}
|
||||
|
||||
public static final ReflectionUtils.MethodFilter USER_METHODS = new ReflectionUtils.MethodFilter() {
|
||||
static final ReflectionUtils.MethodFilter USER_METHODS = new ReflectionUtils.MethodFilter() {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
@@ -38,12 +36,12 @@ public abstract class Methods {
|
||||
*/
|
||||
@Override
|
||||
public boolean matches(Method method) {
|
||||
|
||||
|
||||
return !method.isSynthetic() && //
|
||||
!method.isBridge() && //
|
||||
!ReflectionUtils.isObjectMethod(method) && //
|
||||
!ClassUtils.isCglibProxyClass(method.getDeclaringClass()) && //
|
||||
!ReflectionUtils.isCglibRenamedMethod(method);
|
||||
!method.isBridge() && //
|
||||
!ReflectionUtils.isObjectMethod(method) && //
|
||||
!ClassUtils.isCglibProxyClass(method.getDeclaringClass()) && //
|
||||
!ReflectionUtils.isCglibRenamedMethod(method);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Copyright 2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.rest.core.util;
|
||||
|
||||
/**
|
||||
* Mimics Java 8's Supplier interface to allow deferring a computation.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @since 2.6
|
||||
* @soundtrack KRS-One - Sound Of Da Police (Return Of The Boom Bap)
|
||||
*/
|
||||
public interface Supplier<T> {
|
||||
|
||||
T get();
|
||||
}
|
||||
0
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/AbstractIntegrationTests.java
Normal file → Executable file
0
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/AbstractIntegrationTests.java
Normal file → Executable file
21
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/PathUnitTests.java
Normal file → Executable file
21
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/PathUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -31,50 +30,50 @@ public class PathUnitTests {
|
||||
public void combinesSimplePaths() {
|
||||
|
||||
Path builder = new Path("foo").slash("bar");
|
||||
assertThat(builder.toString(), is("/foo/bar"));
|
||||
assertThat(builder.toString()).isEqualTo("/foo/bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removesLeadingAndTrailingSlashes() {
|
||||
|
||||
Path builder = new Path("foo/").slash("/bar").slash("//foobar///");
|
||||
assertThat(builder.toString(), is("/foo/bar/foobar"));
|
||||
assertThat(builder.toString()).isEqualTo("/foo/bar/foobar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removesWhitespace() {
|
||||
|
||||
Path builder = new Path("foo/ ").slash("/ b a r").slash(" //foobar/// ");
|
||||
assertThat(builder.toString(), is("/foo/bar/foobar"));
|
||||
assertThat(builder.toString()).isEqualTo("/foo/bar/foobar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWithLeadingSlash() {
|
||||
assertThat(new Path("/foobar").matches("/foobar"), is(true));
|
||||
assertThat(new Path("/foobar").matches("/foobar")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWithoutLeadingSlash() {
|
||||
assertThat(new Path("/foobar").matches("foobar"), is(true));
|
||||
assertThat(new Path("/foobar").matches("foobar")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotMatchIfDifferent() {
|
||||
assertThat(new Path("/foobar").matches("barfoo"), is(false));
|
||||
assertThat(new Path("/foobar").matches("barfoo")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotPrefixAbsoluteUris() {
|
||||
assertThat(new Path("http://localhost").toString(), is("http://localhost"));
|
||||
assertThat(new Path("http://localhost").toString()).isEqualTo("http://localhost");
|
||||
}
|
||||
|
||||
@Test // DATAREST-222
|
||||
public void doesNotMatchIfReferenceContainsReservedCharacters() {
|
||||
assertThat(new Path("/foobar").matches("barfoo{?foo}"), is(false));
|
||||
assertThat(new Path("/foobar").matches("barfoo{?foo}")).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-222
|
||||
public void doesNotMatchNullReference() {
|
||||
assertThat(new Path("/foobar").matches(null), is(false));
|
||||
assertThat(new Path("/foobar").matches(null)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
29
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationIntegrationTests.java
Normal file → Executable file
29
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationIntegrationTests.java
Normal file → Executable file
@@ -1,7 +1,21 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.rest.core;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -13,6 +27,7 @@ import org.springframework.data.rest.core.domain.ConfiguredPersonRepository;
|
||||
* Tests to check that {@link ResourceMapping}s are handled correctly.
|
||||
*
|
||||
* @author Jon Brisbin
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public class RepositoryRestConfigurationIntegrationTests extends AbstractIntegrationTests {
|
||||
@@ -21,12 +36,12 @@ public class RepositoryRestConfigurationIntegrationTests extends AbstractIntegra
|
||||
|
||||
@Test
|
||||
public void shouldProvideResourceMappingForConfiguredRepository() throws Exception {
|
||||
|
||||
ResourceMapping mapping = config.getResourceMappingForRepository(ConfiguredPersonRepository.class);
|
||||
|
||||
assertThat(mapping, notNullValue());
|
||||
assertThat(mapping.getRel(), is("people"));
|
||||
assertThat(mapping.getPath(), is("people"));
|
||||
assertThat(mapping.isExported(), is(false));
|
||||
assertThat(mapping).isNotNull();
|
||||
assertThat(mapping.getRel()).isEqualTo("people");
|
||||
assertThat(mapping.getPath()).isEqualTo("people");
|
||||
assertThat(mapping.isExported()).isFalse();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
45
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationUnitTests.java
Normal file → Executable file
45
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Map;
|
||||
@@ -54,22 +53,22 @@ public class RepositoryRestConfigurationUnitTests {
|
||||
@Test // DATAREST-34
|
||||
public void returnsBodiesIfAcceptHeaderPresentByDefault() {
|
||||
|
||||
assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE), is(true));
|
||||
assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE), is(true));
|
||||
assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE)).isTrue();
|
||||
assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-34
|
||||
public void doesNotReturnBodiesIfNoAcceptHeaderPresentByDefault() {
|
||||
|
||||
assertThat(configuration.returnBodyOnCreate(null), is(false));
|
||||
assertThat(configuration.returnBodyOnUpdate(null), is(false));
|
||||
assertThat(configuration.returnBodyOnCreate(null)).isFalse();
|
||||
assertThat(configuration.returnBodyOnUpdate(null)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-34
|
||||
public void doesNotReturnBodiesIfEmptyAcceptHeaderPresentByDefault() {
|
||||
|
||||
assertThat(configuration.returnBodyOnCreate(""), is(false));
|
||||
assertThat(configuration.returnBodyOnUpdate(""), is(false));
|
||||
assertThat(configuration.returnBodyOnCreate("")).isFalse();
|
||||
assertThat(configuration.returnBodyOnUpdate("")).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-34
|
||||
@@ -77,9 +76,9 @@ public class RepositoryRestConfigurationUnitTests {
|
||||
|
||||
configuration.setReturnBodyOnUpdate(false);
|
||||
|
||||
assertThat(configuration.returnBodyOnUpdate(null), is(false));
|
||||
assertThat(configuration.returnBodyOnUpdate(""), is(false));
|
||||
assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE), is(false));
|
||||
assertThat(configuration.returnBodyOnUpdate(null)).isFalse();
|
||||
assertThat(configuration.returnBodyOnUpdate("")).isFalse();
|
||||
assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-34
|
||||
@@ -87,9 +86,9 @@ public class RepositoryRestConfigurationUnitTests {
|
||||
|
||||
configuration.setReturnBodyOnCreate(false);
|
||||
|
||||
assertThat(configuration.returnBodyOnCreate(null), is(false));
|
||||
assertThat(configuration.returnBodyOnCreate(""), is(false));
|
||||
assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE), is(false));
|
||||
assertThat(configuration.returnBodyOnCreate(null)).isFalse();
|
||||
assertThat(configuration.returnBodyOnCreate("")).isFalse();
|
||||
assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-34
|
||||
@@ -97,9 +96,9 @@ public class RepositoryRestConfigurationUnitTests {
|
||||
|
||||
configuration.setReturnBodyOnUpdate(true);
|
||||
|
||||
assertThat(configuration.returnBodyOnUpdate(null), is(true));
|
||||
assertThat(configuration.returnBodyOnUpdate(""), is(true));
|
||||
assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE), is(true));
|
||||
assertThat(configuration.returnBodyOnUpdate(null)).isTrue();
|
||||
assertThat(configuration.returnBodyOnUpdate("")).isTrue();
|
||||
assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-34
|
||||
@@ -107,9 +106,9 @@ public class RepositoryRestConfigurationUnitTests {
|
||||
|
||||
configuration.setReturnBodyOnCreate(true);
|
||||
|
||||
assertThat(configuration.returnBodyOnCreate(null), is(true));
|
||||
assertThat(configuration.returnBodyOnCreate(""), is(true));
|
||||
assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE), is(true));
|
||||
assertThat(configuration.returnBodyOnCreate(null)).isTrue();
|
||||
assertThat(configuration.returnBodyOnCreate("")).isTrue();
|
||||
assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-776
|
||||
@@ -117,7 +116,7 @@ public class RepositoryRestConfigurationUnitTests {
|
||||
|
||||
configuration.withEntityLookup().forLookupRepository(ProfileRepository.class);
|
||||
|
||||
assertThat(configuration.isLookupType(Profile.class), is(true));
|
||||
assertThat(configuration.isLookupType(Profile.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-573
|
||||
@@ -127,9 +126,9 @@ public class RepositoryRestConfigurationUnitTests {
|
||||
registry.addMapping("/hello").maxAge(1234);
|
||||
|
||||
Map<String, CorsConfiguration> corsConfigurations = registry.getCorsConfigurations();
|
||||
assertThat(corsConfigurations, hasKey("/hello"));
|
||||
assertThat(corsConfigurations).containsKey("/hello");
|
||||
|
||||
CorsConfiguration corsConfiguration = corsConfigurations.get("/hello");
|
||||
assertThat(corsConfiguration.getMaxAge(), is(1234L));
|
||||
assertThat(corsConfiguration.getMaxAge()).isEqualTo(1234L);
|
||||
}
|
||||
}
|
||||
|
||||
32
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/UriToEntityConverterUnitTests.java
Normal file → Executable file
32
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/UriToEntityConverterUnitTests.java
Normal file → Executable file
@@ -15,20 +15,20 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.core.convert.ConversionFailedException;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.converter.GenericConverter.ConvertiblePair;
|
||||
@@ -40,6 +40,7 @@ import org.springframework.data.repository.support.Repositories;
|
||||
import org.springframework.data.repository.support.RepositoryInvoker;
|
||||
import org.springframework.data.repository.support.RepositoryInvokerFactory;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.Streamable;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link UriToEntityConverter}.
|
||||
@@ -56,14 +57,13 @@ public class UriToEntityConverterUnitTests {
|
||||
@Mock Repositories repositories;
|
||||
@Mock RepositoryInvokerFactory invokerFactory;
|
||||
|
||||
KeyValueMappingContext context;
|
||||
KeyValueMappingContext<?, ?> context;
|
||||
UriToEntityConverter converter;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setUp() {
|
||||
|
||||
this.context = new KeyValueMappingContext();
|
||||
this.context = new KeyValueMappingContext<>();
|
||||
this.context.setInitialEntitySet(new HashSet<Class<?>>(Arrays.asList(Entity.class, NonEntity.class)));
|
||||
this.context.afterPropertiesSet();
|
||||
|
||||
@@ -76,26 +76,27 @@ public class UriToEntityConverterUnitTests {
|
||||
|
||||
Set<ConvertiblePair> result = converter.getConvertibleTypes();
|
||||
|
||||
assertThat(result, hasItem(new ConvertiblePair(URI.class, Entity.class)));
|
||||
assertThat(result, not(hasItem(new ConvertiblePair(URI.class, NonEntity.class))));
|
||||
assertThat(result).contains(new ConvertiblePair(URI.class, Entity.class));
|
||||
assertThat(result).doesNotContain(new ConvertiblePair(URI.class, NonEntity.class));
|
||||
}
|
||||
|
||||
@Test // DATAREST-427
|
||||
public void cannotConvertEntityWithIdPropertyIfStringConversionMissing() {
|
||||
assertThat(converter.matches(URI_TYPE, ENTITY_TYPE), is(false));
|
||||
assertThat(converter.matches(URI_TYPE, ENTITY_TYPE)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-427
|
||||
public void canConvertEntityWithIdPropertyAndFromStringConversionPossible() {
|
||||
|
||||
doReturn(mock(RepositoryInformation.class)).when(repositories).getRepositoryInformationFor(ENTITY_TYPE.getType());
|
||||
doReturn(Optional.of(mock(RepositoryInformation.class))).when(repositories)
|
||||
.getRepositoryInformationFor(ENTITY_TYPE.getType());
|
||||
|
||||
assertThat(converter.matches(URI_TYPE, ENTITY_TYPE), is(true));
|
||||
assertThat(converter.matches(URI_TYPE, ENTITY_TYPE)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-427
|
||||
public void cannotConvertEntityWithoutIdentifier() {
|
||||
assertThat(converter.matches(URI_TYPE, TypeDescriptor.valueOf(NonEntity.class)), is(false));
|
||||
assertThat(converter.matches(URI_TYPE, TypeDescriptor.valueOf(NonEntity.class))).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-427
|
||||
@@ -104,10 +105,10 @@ public class UriToEntityConverterUnitTests {
|
||||
Entity reference = new Entity();
|
||||
|
||||
RepositoryInvoker invoker = mock(RepositoryInvoker.class);
|
||||
doReturn(reference).when(invoker).invokeFindOne("1");
|
||||
doReturn(Optional.of(reference)).when(invoker).invokeFindOne("1");
|
||||
doReturn(invoker).when(invokerFactory).getInvokerFor(ENTITY_TYPE.getType());
|
||||
|
||||
assertThat(converter.convert(URI.create("/foo/bar/1"), URI_TYPE, ENTITY_TYPE), is((Object) reference));
|
||||
assertThat(converter.convert(URI.create("/foo/bar/1"), URI_TYPE, ENTITY_TYPE)).isEqualTo((Object) reference);
|
||||
}
|
||||
|
||||
@Test(expected = ConversionFailedException.class) // DATAREST-427
|
||||
@@ -139,11 +140,10 @@ public class UriToEntityConverterUnitTests {
|
||||
* @see DATAREST-1018
|
||||
*/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void doesNotRegisterTypeWithUnmanagedRawType() {
|
||||
|
||||
PersistentEntities entities = mock(PersistentEntities.class);
|
||||
doReturn(Arrays.asList(ClassTypeInformation.OBJECT)).when(entities).getManagedTypes();
|
||||
doReturn(Streamable.of(ClassTypeInformation.OBJECT)).when(entities).getManagedTypes();
|
||||
|
||||
new UriToEntityConverter(entities, invokerFactory, repositories);
|
||||
}
|
||||
|
||||
11
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/ValidationErrorsUnitTests.java
Normal file → Executable file
11
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/ValidationErrorsUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@@ -41,7 +40,7 @@ public class ValidationErrorsUnitTests {
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
KeyValueMappingContext context = new KeyValueMappingContext();
|
||||
KeyValueMappingContext<?, ?> context = new KeyValueMappingContext<>();
|
||||
context.getPersistentEntity(Foo.class);
|
||||
|
||||
this.entities = new PersistentEntities(Arrays.asList(context));
|
||||
@@ -56,7 +55,7 @@ public class ValidationErrorsUnitTests {
|
||||
errors.rejectValue("field", "asdf");
|
||||
errors.popNestedPath();
|
||||
|
||||
assertThat(errors.getFieldError().getField(), is("bars[0].field"));
|
||||
assertThat(errors.getFieldError().getField()).isEqualTo("bars[0].field");
|
||||
}
|
||||
|
||||
@Test // DATAREST-801
|
||||
@@ -66,7 +65,7 @@ public class ValidationErrorsUnitTests {
|
||||
|
||||
private static void expectedErrorBehavior(Errors errors) {
|
||||
|
||||
assertThat(errors.getFieldValue("bars"), is(notNullValue()));
|
||||
assertThat(errors.getFieldValue("bars")).isNotNull();
|
||||
|
||||
errors.pushNestedPath("bars[0]");
|
||||
|
||||
@@ -75,7 +74,7 @@ public class ValidationErrorsUnitTests {
|
||||
fail("Expected NotReadablePropertyException!");
|
||||
} catch (NotReadablePropertyException e) {}
|
||||
|
||||
assertThat(errors.getFieldValue("field"), is((Object) "Hello"));
|
||||
assertThat(errors.getFieldValue("field")).isEqualTo((Object) "Hello");
|
||||
}
|
||||
|
||||
static class Foo {
|
||||
|
||||
38
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ProjectionDefinitionConfigurationUnitTests.java
Normal file → Executable file
38
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ProjectionDefinitionConfigurationUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@@ -28,7 +27,6 @@ import org.springframework.data.rest.core.config.ProjectionDefinitionConfigurati
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class ProjectionDefinitionConfigurationUnitTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) // DATAREST-221
|
||||
@@ -67,7 +65,7 @@ public class ProjectionDefinitionConfigurationUnitTests {
|
||||
ProjectionDefinitionConfiguration configuration = new ProjectionDefinitionConfiguration();
|
||||
configuration.addProjection(Integer.class, "name", String.class);
|
||||
|
||||
assertThat(configuration.getProjectionType(String.class, "name"), is(equalTo((Class) Integer.class)));
|
||||
assertThat(configuration.getProjectionType(String.class, "name")).isEqualTo(Integer.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-221
|
||||
@@ -76,7 +74,7 @@ public class ProjectionDefinitionConfigurationUnitTests {
|
||||
ProjectionDefinitionConfiguration configuration = new ProjectionDefinitionConfiguration();
|
||||
configuration.addProjection(SampleProjection.class);
|
||||
|
||||
assertThat(configuration.getProjectionType(Integer.class, "name"), is(equalTo((Class) SampleProjection.class)));
|
||||
assertThat(configuration.getProjectionType(Integer.class, "name")).isEqualTo(SampleProjection.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-221
|
||||
@@ -85,7 +83,7 @@ public class ProjectionDefinitionConfigurationUnitTests {
|
||||
ProjectionDefinitionConfiguration configuration = new ProjectionDefinitionConfiguration();
|
||||
configuration.addProjection(Default.class);
|
||||
|
||||
assertThat(configuration.getProjectionType(Integer.class, "default"), is(equalTo((Class) Default.class)));
|
||||
assertThat(configuration.getProjectionType(Integer.class, "default")).isEqualTo(Default.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-221
|
||||
@@ -96,17 +94,17 @@ public class ProjectionDefinitionConfigurationUnitTests {
|
||||
ProjectionDefinition stringName = ProjectionDefinition.of(String.class, Object.class, "name");
|
||||
ProjectionDefinition objectOtherNameKey = ProjectionDefinition.of(Object.class, Object.class, "otherName");
|
||||
|
||||
assertThat(objectName, is(objectName));
|
||||
assertThat(objectName, is(sameObjectName));
|
||||
assertThat(sameObjectName, is(objectName));
|
||||
assertThat(objectName).isEqualTo(objectName);
|
||||
assertThat(objectName).isEqualTo(sameObjectName);
|
||||
assertThat(sameObjectName).isEqualTo(objectName);
|
||||
|
||||
assertThat(objectName, is(not(stringName)));
|
||||
assertThat(stringName, is(not(objectName)));
|
||||
assertThat(objectName).isNotEqualTo(stringName);
|
||||
assertThat(stringName).isNotEqualTo(objectName);
|
||||
|
||||
assertThat(objectName, is(not(objectOtherNameKey)));
|
||||
assertThat(objectOtherNameKey, is(not(objectName)));
|
||||
assertThat(objectName).isNotEqualTo(objectOtherNameKey);
|
||||
assertThat(objectOtherNameKey).isNotEqualTo(objectName);
|
||||
|
||||
assertThat(objectName, is(not(new Object())));
|
||||
assertThat(objectName).isNotEqualTo(new Object());
|
||||
}
|
||||
|
||||
@Test // DATAREST-385
|
||||
@@ -115,14 +113,14 @@ public class ProjectionDefinitionConfigurationUnitTests {
|
||||
ProjectionDefinitionConfiguration configuration = new ProjectionDefinitionConfiguration();
|
||||
configuration.addProjection(ParentProjection.class);
|
||||
|
||||
assertThat(configuration.hasProjectionFor(Child.class), is(true));
|
||||
assertThat(configuration.getProjectionsFor(Child.class).values(), hasItem(ParentProjection.class));
|
||||
assertThat(configuration.getProjectionType(Child.class, "summary"), is(typeCompatibleWith(ParentProjection.class)));
|
||||
assertThat(configuration.hasProjectionFor(Child.class)).isTrue();
|
||||
assertThat(configuration.getProjectionsFor(Child.class).values()).contains(ParentProjection.class);
|
||||
assertThat(configuration.getProjectionType(Child.class, "summary")).isAssignableFrom(ParentProjection.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-221
|
||||
public void defaultsParamternameToProjection() {
|
||||
assertThat(new ProjectionDefinitionConfiguration().getParameterName(), is("projection"));
|
||||
assertThat(new ProjectionDefinitionConfiguration().getParameterName()).isEqualTo("projection");
|
||||
}
|
||||
|
||||
@Test // DATAREST-747
|
||||
@@ -134,8 +132,8 @@ public class ProjectionDefinitionConfigurationUnitTests {
|
||||
|
||||
Map<String, Class<?>> projections = configuration.getProjectionsFor(Child.class);
|
||||
|
||||
assertThat(projections.values(), hasSize(1));
|
||||
assertThat(projections.values(), hasItem(ChildProjection.class));
|
||||
assertThat(projections.values()).hasSize(1);
|
||||
assertThat(projections.values()).contains(ChildProjection.class);
|
||||
}
|
||||
|
||||
@Projection(name = "name", types = Integer.class)
|
||||
|
||||
22
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ResourceMappingUnitTests.java
Normal file → Executable file
22
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ResourceMappingUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.config;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.rest.core.support.ResourceMappingUtils.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
@@ -43,16 +42,17 @@ public class ResourceMappingUnitTests {
|
||||
|
||||
@Test
|
||||
public void shouldDetectPathAndRemoveLeadingSlashIfAny() {
|
||||
|
||||
org.springframework.data.rest.core.config.ResourceMapping mapping = new org.springframework.data.rest.core.config.ResourceMapping(
|
||||
findRel(AnnotatedWithLeadingSlashPersonRepository.class),
|
||||
findPath(AnnotatedWithLeadingSlashPersonRepository.class),
|
||||
findExported(AnnotatedWithLeadingSlashPersonRepository.class));
|
||||
|
||||
// The rel attribute defaults to class name
|
||||
assertThat(mapping.getRel(), is("annotatedWithLeadingSlashPerson"));
|
||||
assertThat(mapping.getPath(), is("people"));
|
||||
assertThat(mapping.getRel()).isEqualTo("annotatedWithLeadingSlashPerson");
|
||||
assertThat(mapping.getPath()).isEqualTo("people");
|
||||
// The exported defaults to true
|
||||
assertThat(mapping.isExported(), is(true));
|
||||
assertThat(mapping.isExported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,10 +63,10 @@ public class ResourceMappingUnitTests {
|
||||
findRel(method), findPath(method), findExported(method));
|
||||
|
||||
// The rel attribute defaults to class name
|
||||
assertThat(mapping.getRel(), is("findByFirstName"));
|
||||
assertThat(mapping.getPath(), is("firstname"));
|
||||
assertThat(mapping.getRel()).isEqualTo("findByFirstName");
|
||||
assertThat(mapping.getPath()).isEqualTo("firstname");
|
||||
// The exported defaults to true
|
||||
assertThat(mapping.isExported(), is(true));
|
||||
assertThat(mapping.isExported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -77,11 +77,11 @@ public class ResourceMappingUnitTests {
|
||||
findRel(method), findPath(method), findExported(method));
|
||||
|
||||
// The rel defaults to method name
|
||||
assertThat(mapping.getRel(), is("findByLastName"));
|
||||
assertThat(mapping.getRel()).isEqualTo("findByLastName");
|
||||
// The path contains only a leading slash therefore defaults to method name
|
||||
assertThat(mapping.getPath(), is("findByLastName"));
|
||||
assertThat(mapping.getPath()).isEqualTo("findByLastName");
|
||||
// The exported defaults to true
|
||||
assertThat(mapping.isExported(), is(true));
|
||||
assertThat(mapping.isExported()).isTrue();
|
||||
}
|
||||
|
||||
@RestResource(path = "/people")
|
||||
|
||||
0
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/RepositoryEventIntegrationTests.java
Normal file → Executable file
0
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/RepositoryEventIntegrationTests.java
Normal file → Executable file
2
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/ValidatorIntegrationTests.java
Normal file → Executable file
2
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/ValidatorIntegrationTests.java
Normal file → Executable file
@@ -60,7 +60,7 @@ public class ValidatorIntegrationTests {
|
||||
}
|
||||
|
||||
@Autowired ConfigurableApplicationContext context;
|
||||
@Autowired KeyValueMappingContext mappingContext;
|
||||
@Autowired KeyValueMappingContext<?, ?> mappingContext;
|
||||
|
||||
@Test(expected = RepositoryConstraintViolationException.class)
|
||||
public void shouldValidateLastName() throws Exception {
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.domain;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
@@ -29,12 +30,12 @@ public interface OrderRepository extends CrudRepository<Order, UUID> {
|
||||
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public <S extends Order> S save(S entity);
|
||||
<S extends Order> S save(S entity);
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
|
||||
*/
|
||||
@Override
|
||||
public Order findOne(UUID id);
|
||||
Optional<Order> findOne(UUID id);
|
||||
}
|
||||
|
||||
17
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/event/AnnotatedEventHandlerInvokerUnitTests.java
Normal file → Executable file
17
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/event/AnnotatedEventHandlerInvokerUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.event;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
@@ -51,7 +50,7 @@ public class AnnotatedEventHandlerInvokerUnitTests {
|
||||
MultiValueMap<Class<? extends RepositoryEvent>, EventHandlerMethod> methods = (MultiValueMap<Class<? extends RepositoryEvent>, EventHandlerMethod>) ReflectionTestUtils
|
||||
.getField(invoker, "handlerMethods");
|
||||
|
||||
assertThat(methods.get(BeforeCreateEvent.class), hasSize(1));
|
||||
assertThat(methods.get(BeforeCreateEvent.class)).hasSize(1);
|
||||
}
|
||||
|
||||
@Test // DATAREST-606
|
||||
@@ -64,7 +63,7 @@ public class AnnotatedEventHandlerInvokerUnitTests {
|
||||
|
||||
invoker.onApplicationEvent(new BeforeCreateEvent(new Person("Dave", "Matthews")));
|
||||
|
||||
assertThat(sampleHandler.wasCalled, is(true));
|
||||
assertThat(sampleHandler.wasCalled).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-970
|
||||
@@ -79,10 +78,10 @@ public class AnnotatedEventHandlerInvokerUnitTests {
|
||||
|
||||
invoker.onApplicationEvent(new BeforeCreateEvent(new Person("Dave", "Matthews")));
|
||||
|
||||
assertThat(orderHandler1.wasCalled, is(true));
|
||||
assertThat(orderHandler2.wasCalled, is(true));
|
||||
assertThat(orderHandler1.wasCalled).isTrue();
|
||||
assertThat(orderHandler2.wasCalled).isTrue();
|
||||
|
||||
assertThat(orderHandler1.timestamp, is(greaterThan(orderHandler2.timestamp)));
|
||||
assertThat(orderHandler1.timestamp).isGreaterThan(orderHandler2.timestamp);
|
||||
}
|
||||
|
||||
@Test // DATAREST-983
|
||||
@@ -98,8 +97,8 @@ public class AnnotatedEventHandlerInvokerUnitTests {
|
||||
invoker.onApplicationEvent(new BeforeCreateEvent(new FirstEntity()));
|
||||
invoker.onApplicationEvent(new BeforeCreateEvent(new SecondEntity()));
|
||||
|
||||
assertThat(firstHandler.callCount, is(1));
|
||||
assertThat(secondHandler.callCount, is(1));
|
||||
assertThat(firstHandler.callCount).isEqualTo(1);
|
||||
assertThat(secondHandler.callCount).isEqualTo(1);
|
||||
}
|
||||
|
||||
@RepositoryEventHandler
|
||||
|
||||
36
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethodsUnitTests.java
Normal file → Executable file
36
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethodsUnitTests.java
Normal file → Executable file
@@ -15,17 +15,17 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.rest.core.mapping.ResourceType.*;
|
||||
import static org.springframework.http.HttpMethod.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.data.annotation.ReadOnlyProperty;
|
||||
import org.springframework.data.annotation.Reference;
|
||||
import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity;
|
||||
@@ -88,22 +88,24 @@ public class CrudMethodsSupportedHttpMethodsUnitTests {
|
||||
@Test // DATAREST-523
|
||||
public void exposesMethodsForProperties() {
|
||||
|
||||
KeyValueMappingContext context = new KeyValueMappingContext();
|
||||
KeyValuePersistentEntity<?> entity = context.getPersistentEntity(Entity.class);
|
||||
KeyValueMappingContext<?, ?> context = new KeyValueMappingContext<>();
|
||||
KeyValuePersistentEntity<?, ?> entity = context.getRequiredPersistentEntity(Entity.class);
|
||||
|
||||
SupportedHttpMethods methods = getSupportedHttpMethodsFor(EntityRepository.class);
|
||||
|
||||
assertThat(methods.getMethodsFor(entity.getPersistentProperty("embedded")), is(empty()));
|
||||
assertThat(methods.getMethodsFor(entity.getPersistentProperty("embeddedCollection")), is(empty()));
|
||||
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("embedded"))).isEmpty();
|
||||
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("embeddedCollection"))).isEmpty();
|
||||
|
||||
assertThat(methods.getMethodsFor(entity.getPersistentProperty("related")),
|
||||
allOf(hasItems(GET, DELETE, PATCH, PUT), not(hasItem(POST))));
|
||||
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("related")))//
|
||||
.contains(GET, DELETE, PATCH, PUT)//
|
||||
.doesNotContain(POST);
|
||||
|
||||
assertThat(methods.getMethodsFor(entity.getPersistentProperty("relatedCollection")),
|
||||
hasItems(GET, DELETE, PATCH, PUT, POST));
|
||||
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("relatedCollection")))//
|
||||
.contains(GET, DELETE, PATCH, PUT, POST);
|
||||
|
||||
assertThat(methods.getMethodsFor(entity.getPersistentProperty("readOnlyReference")),
|
||||
allOf(hasItem(GET), not(hasItems(DELETE, PATCH, PUT, POST))));
|
||||
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("readOnlyReference")))//
|
||||
.contains(GET)//
|
||||
.doesNotContain(DELETE, PATCH, PUT, POST);
|
||||
}
|
||||
|
||||
@Test // DATAREST-825
|
||||
@@ -129,10 +131,10 @@ public class CrudMethodsSupportedHttpMethodsUnitTests {
|
||||
|
||||
Set<HttpMethod> result = methods.getMethodsFor(type);
|
||||
|
||||
assertThat(result, supported ? hasItems(httpMethods) : not(hasItems(httpMethods)));
|
||||
|
||||
if (supported) {
|
||||
assertThat(result, hasSize(httpMethods.length));
|
||||
assertThat(result).containsExactlyInAnyOrder(httpMethods);
|
||||
} else {
|
||||
assertThat(result).doesNotContain(httpMethods);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +152,7 @@ public class CrudMethodsSupportedHttpMethodsUnitTests {
|
||||
|
||||
@Override
|
||||
@RestResource(exported = false)
|
||||
Object findOne(Long id);
|
||||
Optional<Object> findOne(Long id);
|
||||
}
|
||||
|
||||
interface NoFindOne extends Repository<Object, Long> {
|
||||
|
||||
23
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/MappingResourceMetadataUnitTests.java
Normal file → Executable file
23
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/MappingResourceMetadataUnitTests.java
Normal file → Executable file
@@ -15,14 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.data.annotation.Reference;
|
||||
import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity;
|
||||
import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty;
|
||||
@@ -38,9 +37,9 @@ import org.springframework.data.rest.core.annotation.RestResource;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MappingResourceMetadataUnitTests {
|
||||
|
||||
KeyValueMappingContext context = new KeyValueMappingContext();
|
||||
KeyValueMappingContext<?, ?> context = new KeyValueMappingContext<>();
|
||||
|
||||
KeyValuePersistentEntity<?> entity = context.getPersistentEntity(Entity.class);
|
||||
KeyValuePersistentEntity<?, ?> entity = context.getRequiredPersistentEntity(Entity.class);
|
||||
ResourceMappings resourceMappings = new PersistentEntitiesResourceMappings(
|
||||
new PersistentEntities(Arrays.asList(context)));
|
||||
MappingResourceMetadata metadata = new MappingResourceMetadata(entity, resourceMappings);
|
||||
@@ -48,27 +47,27 @@ public class MappingResourceMetadataUnitTests {
|
||||
@Test // DATAREST-514
|
||||
public void allowsLookupOfPropertyByMappedName() {
|
||||
|
||||
KeyValuePersistentProperty property = entity.getPersistentProperty("related");
|
||||
KeyValuePersistentProperty<?> property = entity.getRequiredPersistentProperty("related");
|
||||
|
||||
PropertyAwareResourceMapping propertyMapping = metadata.getProperty("foo");
|
||||
|
||||
assertThat(propertyMapping, is(notNullValue()));
|
||||
assertThat(propertyMapping.getProperty(), is((Object) property));
|
||||
assertThat(metadata.getMappingFor(property).getPath().matches("foo"), is(true));
|
||||
assertThat(propertyMapping).isNotNull();
|
||||
assertThat(propertyMapping.getProperty()).isEqualTo((Object) property);
|
||||
assertThat(metadata.getMappingFor(property).getPath().matches("foo")).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-518
|
||||
public void isNotExportedByDefault() {
|
||||
|
||||
assertThat(metadata.isExported(), is(false));
|
||||
assertThat(metadata.isExported()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-518
|
||||
public void isExportedIfExplicitlyAnnotated() {
|
||||
|
||||
MappingResourceMetadata metadata = new MappingResourceMetadata(context.getPersistentEntity(Related.class),
|
||||
MappingResourceMetadata metadata = new MappingResourceMetadata(context.getRequiredPersistentEntity(Related.class),
|
||||
resourceMappings);
|
||||
assertThat(metadata.isExported(), is(true));
|
||||
assertThat(metadata.isExported()).isTrue();
|
||||
}
|
||||
|
||||
static class Entity {
|
||||
|
||||
43
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMappingUnitTests.java
Normal file → Executable file
43
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMappingUnitTests.java
Normal file → Executable file
@@ -15,15 +15,14 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.data.annotation.Reference;
|
||||
import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity;
|
||||
import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty;
|
||||
@@ -41,17 +40,17 @@ import org.springframework.data.rest.core.annotation.RestResource;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PersistentPropertyResourceMappingUnitTests {
|
||||
|
||||
KeyValueMappingContext mappingContext = new KeyValueMappingContext();
|
||||
KeyValueMappingContext<?, ?> mappingContext = new KeyValueMappingContext<>();
|
||||
|
||||
@Test // DATAREST-175
|
||||
public void usesPropertyNameAsDefaultResourceMappingRelAndPath() {
|
||||
|
||||
ResourceMapping mapping = getPropertyMappingFor(Entity.class, "first");
|
||||
|
||||
assertThat(mapping, is(notNullValue()));
|
||||
assertThat(mapping.getPath(), is(new Path("first")));
|
||||
assertThat(mapping.getRel(), is("first"));
|
||||
assertThat(mapping.isExported(), is(false));
|
||||
assertThat(mapping).isNotNull();
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("first"));
|
||||
assertThat(mapping.getRel()).isEqualTo("first");
|
||||
assertThat(mapping.isExported()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-175
|
||||
@@ -59,10 +58,10 @@ public class PersistentPropertyResourceMappingUnitTests {
|
||||
|
||||
ResourceMapping mapping = getPropertyMappingFor(Entity.class, "second");
|
||||
|
||||
assertThat(mapping, is(notNullValue()));
|
||||
assertThat(mapping.getPath(), is(new Path("secPath")));
|
||||
assertThat(mapping.getRel(), is("secRel"));
|
||||
assertThat(mapping.isExported(), is(false));
|
||||
assertThat(mapping).isNotNull();
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("secPath"));
|
||||
assertThat(mapping.getRel()).isEqualTo("secRel");
|
||||
assertThat(mapping.isExported()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-175
|
||||
@@ -70,10 +69,10 @@ public class PersistentPropertyResourceMappingUnitTests {
|
||||
|
||||
ResourceMapping mapping = getPropertyMappingFor(Entity.class, "third");
|
||||
|
||||
assertThat(mapping, is(notNullValue()));
|
||||
assertThat(mapping.getPath(), is(new Path("thirdPath")));
|
||||
assertThat(mapping.getRel(), is("thirdRel"));
|
||||
assertThat(mapping.isExported(), is(false));
|
||||
assertThat(mapping).isNotNull();
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("thirdPath"));
|
||||
assertThat(mapping.getRel()).isEqualTo("thirdRel");
|
||||
assertThat(mapping.isExported()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-233
|
||||
@@ -83,8 +82,8 @@ public class PersistentPropertyResourceMappingUnitTests {
|
||||
|
||||
ResourceDescription description = mapping.getDescription();
|
||||
|
||||
assertThat(description.isDefault(), is(true));
|
||||
assertThat(description.getMessage(), is("rest.description.entity.second"));
|
||||
assertThat(description.isDefault()).isTrue();
|
||||
assertThat(description.getMessage()).isEqualTo("rest.description.entity.second");
|
||||
}
|
||||
|
||||
@Test // DATAREST-233
|
||||
@@ -93,14 +92,14 @@ public class PersistentPropertyResourceMappingUnitTests {
|
||||
ResourceMapping mapping = getPropertyMappingFor(Entity.class, "fourth");
|
||||
|
||||
ResourceDescription description = mapping.getDescription();
|
||||
assertThat(description.isDefault(), is(false));
|
||||
assertThat(description.getMessage(), is("Some description"));
|
||||
assertThat(description.isDefault()).isFalse();
|
||||
assertThat(description.getMessage()).isEqualTo("Some description");
|
||||
}
|
||||
|
||||
private ResourceMapping getPropertyMappingFor(Class<?> entity, String propertyName) {
|
||||
|
||||
KeyValuePersistentEntity<?> persistentEntity = mappingContext.getPersistentEntity(entity);
|
||||
KeyValuePersistentProperty property = persistentEntity.getPersistentProperty(propertyName);
|
||||
KeyValuePersistentEntity<?, ?> persistentEntity = mappingContext.getRequiredPersistentEntity(entity);
|
||||
KeyValuePersistentProperty<?> property = persistentEntity.getRequiredPersistentProperty(propertyName);
|
||||
|
||||
ResourceMappings resourceMappings = new PersistentEntitiesResourceMappings(
|
||||
new PersistentEntities(Arrays.asList(mappingContext)));
|
||||
|
||||
37
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryCollectionResourceMappingUnitTests.java
Normal file → Executable file
37
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryCollectionResourceMappingUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Page;
|
||||
@@ -41,10 +40,10 @@ public class RepositoryCollectionResourceMappingUnitTests {
|
||||
|
||||
CollectionResourceMapping mapping = getResourceMappingFor(PersonRepository.class);
|
||||
|
||||
assertThat(mapping.getPath(), is(new Path("persons")));
|
||||
assertThat(mapping.getRel(), is("persons"));
|
||||
assertThat(mapping.getItemResourceRel(), is("person"));
|
||||
assertThat(mapping.isExported(), is(true));
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("persons"));
|
||||
assertThat(mapping.getRel()).isEqualTo("persons");
|
||||
assertThat(mapping.getItemResourceRel()).isEqualTo("person");
|
||||
assertThat(mapping.isExported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -52,10 +51,10 @@ public class RepositoryCollectionResourceMappingUnitTests {
|
||||
|
||||
CollectionResourceMapping mapping = getResourceMappingFor(AnnotatedPersonRepository.class);
|
||||
|
||||
assertThat(mapping.getPath(), is(new Path("bar")));
|
||||
assertThat(mapping.getRel(), is("foo"));
|
||||
assertThat(mapping.getItemResourceRel(), is("annotatedPerson"));
|
||||
assertThat(mapping.isExported(), is(false));
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("bar"));
|
||||
assertThat(mapping.getRel()).isEqualTo("foo");
|
||||
assertThat(mapping.getItemResourceRel()).isEqualTo("annotatedPerson");
|
||||
assertThat(mapping.isExported()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,30 +62,30 @@ public class RepositoryCollectionResourceMappingUnitTests {
|
||||
|
||||
CollectionResourceMapping mapping = getResourceMappingFor(AnnotatedAnnotatedPersonRepository.class);
|
||||
|
||||
assertThat(mapping.getPath(), is(new Path("/trumpsAll")));
|
||||
assertThat(mapping.getRel(), is("foo"));
|
||||
assertThat(mapping.getItemResourceRel(), is("annotatedPerson"));
|
||||
assertThat(mapping.isExported(), is(true));
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("/trumpsAll"));
|
||||
assertThat(mapping.getRel()).isEqualTo("foo");
|
||||
assertThat(mapping.getItemResourceRel()).isEqualTo("annotatedPerson");
|
||||
assertThat(mapping.isExported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotExposeRepositoryForPublicDomainTypeIfRepoIsPackageProtected() {
|
||||
|
||||
ResourceMapping mapping = getResourceMappingFor(PackageProtectedRepository.class);
|
||||
assertThat(mapping.isExported(), is(false));
|
||||
assertThat(mapping.isExported()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-229
|
||||
public void detectsPagingRepository() {
|
||||
assertThat(getResourceMappingFor(PersonRepository.class).isPagingResource(), is(true));
|
||||
assertThat(getResourceMappingFor(PersonRepository.class).isPagingResource()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void discoversCustomizationsUsingRestRepositoryResource() {
|
||||
|
||||
CollectionResourceMapping mapping = getResourceMappingFor(RepositoryAnnotatedRepository.class);
|
||||
assertThat(mapping.getRel(), is("foo"));
|
||||
assertThat(mapping.getItemResourceRel(), is("bar"));
|
||||
assertThat(mapping.getRel()).isEqualTo("foo");
|
||||
assertThat(mapping.getItemResourceRel()).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test // DATAREST-445
|
||||
@@ -103,7 +102,7 @@ public class RepositoryCollectionResourceMappingUnitTests {
|
||||
RepositoryCollectionResourceMapping mapping = new RepositoryCollectionResourceMapping(metadata,
|
||||
RepositoryDetectionStrategies.DEFAULT);
|
||||
|
||||
assertThat(mapping.getPath(), is(new Path("/objects")));
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("/objects"));
|
||||
}
|
||||
|
||||
private static CollectionResourceMapping getResourceMappingFor(Class<?> repositoryInterface) {
|
||||
|
||||
5
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryDetectionStrategiesUnitTests.java
Normal file → Executable file
5
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryDetectionStrategiesUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.rest.core.mapping.RepositoryDetectionStrategy.RepositoryDetectionStrategies.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -93,7 +92,7 @@ public class RepositoryDetectionStrategiesUnitTests {
|
||||
private static void assertExposures(RepositoryDetectionStrategy strategy, Map<Class<?>, Boolean> expected) {
|
||||
|
||||
for (Entry<Class<?>, Boolean> entry : expected.entrySet()) {
|
||||
assertThat(strategy.isExported(new DefaultRepositoryMetadata(entry.getKey())), is(entry.getValue()));
|
||||
assertThat(strategy.isExported(new DefaultRepositoryMetadata(entry.getKey()))).isEqualTo(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
27
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryMethodResourceMappingUnitTests.java
Normal file → Executable file
27
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryMethodResourceMappingUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
@@ -49,7 +48,7 @@ public class RepositoryMethodResourceMappingUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByLastname", String.class);
|
||||
ResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.getPath(), is(new Path("findByLastname")));
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("findByLastname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -58,16 +57,16 @@ public class RepositoryMethodResourceMappingUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByFirstname", String.class);
|
||||
ResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.getPath(), is(new Path("bar")));
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("bar"));
|
||||
}
|
||||
|
||||
@Test // DATAREST-31
|
||||
public void doesNotDiscoverAnyParametersIfNotAnnotated() throws Exception {
|
||||
public void discoversParametersIfCompiledWithCorrespondingFlag() throws Exception {
|
||||
|
||||
Method method = PersonRepository.class.getMethod("findByLastname", String.class);
|
||||
MethodResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.getParametersMetadata().getParameterNames(), is(emptyIterable()));
|
||||
assertThat(mapping.getParametersMetadata().getParameterNames()).contains("lastname");
|
||||
}
|
||||
|
||||
@Test // DATAREST-31
|
||||
@@ -76,8 +75,8 @@ public class RepositoryMethodResourceMappingUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByFirstname", String.class);
|
||||
MethodResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.getParametersMetadata().getParameterNames(), hasSize(1));
|
||||
assertThat(mapping.getParametersMetadata().getParameterNames(), hasItem("firstname"));
|
||||
assertThat(mapping.getParametersMetadata().getParameterNames()).hasSize(1);
|
||||
assertThat(mapping.getParametersMetadata().getParameterNames()).contains("firstname");
|
||||
}
|
||||
|
||||
@Test // DATAREST-229
|
||||
@@ -86,7 +85,7 @@ public class RepositoryMethodResourceMappingUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByEmailAddress", String.class, Pageable.class);
|
||||
MethodResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.isPagingResource(), is(true));
|
||||
assertThat(mapping.isPagingResource()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -95,7 +94,7 @@ public class RepositoryMethodResourceMappingUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByEmailAddress", String.class, Pageable.class);
|
||||
MethodResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.getRel(), is("findByEmailAddress"));
|
||||
assertThat(mapping.getRel()).isEqualTo("findByEmailAddress");
|
||||
}
|
||||
|
||||
@Test // DATAREST-384
|
||||
@@ -104,12 +103,12 @@ public class RepositoryMethodResourceMappingUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByEmailAddress", String.class, Sort.class);
|
||||
RepositoryMethodResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.isSortableResource(), is(true));
|
||||
assertThat(mapping.isSortableResource()).isTrue();
|
||||
|
||||
method = PersonRepository.class.getMethod("findByEmailAddress", String.class, Pageable.class);
|
||||
mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.isSortableResource(), is(false));
|
||||
assertThat(mapping.isSortableResource()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-467
|
||||
@@ -119,7 +118,7 @@ public class RepositoryMethodResourceMappingUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByLastname", String.class);
|
||||
MethodResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.getReturnedDomainType(), is(equalTo((Class) Person.class)));
|
||||
assertThat(mapping.getReturnedDomainType()).isEqualTo((Class) Person.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-699
|
||||
@@ -128,7 +127,7 @@ public class RepositoryMethodResourceMappingUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByLastname", String.class, Pageable.class);
|
||||
RepositoryMethodResourceMapping mapping = getMappingFor(method);
|
||||
|
||||
assertThat(mapping.getParametersMetadata().getParameterNames(), not(hasItem("pageable")));
|
||||
assertThat(mapping.getParametersMetadata().getParameterNames()).doesNotContain("pageable");
|
||||
}
|
||||
|
||||
private RepositoryMethodResourceMapping getMappingFor(Method method) {
|
||||
|
||||
57
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappingsIntegrationTests.java
Normal file → Executable file
57
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappingsIntegrationTests.java
Normal file → Executable file
@@ -15,14 +15,12 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -38,6 +36,7 @@ import org.springframework.data.rest.core.domain.Author;
|
||||
import org.springframework.data.rest.core.domain.CreditCard;
|
||||
import org.springframework.data.rest.core.domain.JpaRepositoryConfig;
|
||||
import org.springframework.data.rest.core.domain.Person;
|
||||
import org.springframework.data.rest.core.domain.Profile;
|
||||
import org.springframework.data.rest.core.mapping.RepositoryDetectionStrategy.RepositoryDetectionStrategies;
|
||||
import org.springframework.hateoas.core.EvoInflectorRelProvider;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
@@ -54,13 +53,15 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
public class RepositoryResourceMappingsIntegrationTests {
|
||||
|
||||
@Autowired ListableBeanFactory factory;
|
||||
@Autowired KeyValueMappingContext mappingContext;
|
||||
@Autowired KeyValueMappingContext<?, ?> mappingContext;
|
||||
|
||||
ResourceMappings mappings;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
mappingContext.getPersistentEntity(Profile.class);
|
||||
|
||||
Repositories repositories = new Repositories(factory);
|
||||
this.mappings = new RepositoryResourceMappings(repositories, new PersistentEntities(Arrays.asList(mappingContext)),
|
||||
new EvoInflectorRelProvider(), RepositoryDetectionStrategies.DEFAULT);
|
||||
@@ -68,7 +69,7 @@ public class RepositoryResourceMappingsIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void detectsAllMappings() {
|
||||
assertThat(mappings, is(Matchers.<ResourceMetadata> iterableWithSize(5)));
|
||||
assertThat(mappings).hasSize(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -76,8 +77,8 @@ public class RepositoryResourceMappingsIntegrationTests {
|
||||
|
||||
ResourceMetadata personMappings = mappings.getMetadataFor(Person.class);
|
||||
|
||||
assertThat(personMappings.isExported(), is(true));
|
||||
assertThat(personMappings.getSearchResourceMappings().isExported(), is(true));
|
||||
assertThat(personMappings.isExported()).isTrue();
|
||||
assertThat(personMappings.getSearchResourceMappings().isExported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -85,8 +86,8 @@ public class RepositoryResourceMappingsIntegrationTests {
|
||||
|
||||
ResourceMetadata creditCardMapping = mappings.getMetadataFor(CreditCard.class);
|
||||
|
||||
assertThat(creditCardMapping.isExported(), is(false));
|
||||
assertThat(creditCardMapping.getSearchResourceMappings().isExported(), is(false));
|
||||
assertThat(creditCardMapping.isExported()).isFalse();
|
||||
assertThat(creditCardMapping.getSearchResourceMappings().isExported()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-112
|
||||
@@ -94,27 +95,27 @@ public class RepositoryResourceMappingsIntegrationTests {
|
||||
|
||||
Repositories repositories = new Repositories(factory);
|
||||
PersistentEntity<?, ?> entity = repositories.getPersistentEntity(Person.class);
|
||||
PersistentProperty<?> property = entity.getPersistentProperty("siblings");
|
||||
PersistentProperty<?> property = entity.getRequiredPersistentProperty("siblings");
|
||||
|
||||
ResourceMetadata metadata = mappings.getMetadataFor(Person.class);
|
||||
ResourceMapping mapping = metadata.getMappingFor(property);
|
||||
|
||||
assertThat(mapping.getRel(), is("siblings"));
|
||||
assertThat(mapping.getPath(), is(new Path("siblings")));
|
||||
assertThat(mapping.isExported(), is(true));
|
||||
assertThat(mapping.getRel()).isEqualTo("siblings");
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("siblings"));
|
||||
assertThat(mapping.isExported()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-111
|
||||
public void exposesResourceByPath() {
|
||||
|
||||
assertThat(mappings.exportsTopLevelResourceFor("people"), is(true));
|
||||
assertThat(mappings.exportsTopLevelResourceFor("orders"), is(true));
|
||||
assertThat(mappings.exportsTopLevelResourceFor("people")).isTrue();
|
||||
assertThat(mappings.exportsTopLevelResourceFor("orders")).isTrue();
|
||||
|
||||
ResourceMetadata creditCardMapping = mappings.getMetadataFor(CreditCard.class);
|
||||
assertThat(creditCardMapping, is(notNullValue()));
|
||||
assertThat(creditCardMapping.getPath(), is(new Path("creditCards")));
|
||||
assertThat(creditCardMapping.isExported(), is(false));
|
||||
assertThat(mappings.exportsTopLevelResourceFor("creditCards"), is(false));
|
||||
assertThat(creditCardMapping).isNotNull();
|
||||
assertThat(creditCardMapping.getPath()).isEqualTo(new Path("creditCards"));
|
||||
assertThat(creditCardMapping.isExported()).isFalse();
|
||||
assertThat(mappings.exportsTopLevelResourceFor("creditCards")).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATAREST-107
|
||||
@@ -123,7 +124,7 @@ public class RepositoryResourceMappingsIntegrationTests {
|
||||
ResourceMetadata creditCardMetadata = mappings.getMetadataFor(CreditCard.class);
|
||||
SearchResourceMappings searchResourceMappings = creditCardMetadata.getSearchResourceMappings();
|
||||
|
||||
assertThat(searchResourceMappings, is(Matchers.<MethodResourceMapping> iterableWithSize(0)));
|
||||
assertThat(searchResourceMappings).isEmpty();
|
||||
|
||||
ResourceMetadata personMetadata = mappings.getMetadataFor(Person.class);
|
||||
List<String> methodNames = new ArrayList<String>();
|
||||
@@ -132,25 +133,25 @@ public class RepositoryResourceMappingsIntegrationTests {
|
||||
methodNames.add(method.getMethod().getName());
|
||||
}
|
||||
|
||||
assertThat(methodNames, hasSize(2));
|
||||
assertThat(methodNames, hasItems("findByFirstName", "findByCreatedGreaterThan"));
|
||||
assertThat(methodNames).hasSize(2);
|
||||
assertThat(methodNames).contains("findByFirstName", "findByCreatedGreaterThan");
|
||||
}
|
||||
|
||||
@Test // DATAREST-325
|
||||
public void exposesMethodResourceMappingInPackageProtectedButExportedRepo() {
|
||||
|
||||
ResourceMetadata metadata = mappings.getMetadataFor(Author.class);
|
||||
assertThat(metadata.isExported(), is(true));
|
||||
assertThat(metadata.isExported()).isTrue();
|
||||
|
||||
SearchResourceMappings searchMappings = metadata.getSearchResourceMappings();
|
||||
|
||||
assertThat(searchMappings.isExported(), is(true));
|
||||
assertThat(searchMappings.getMappedMethod("findByFirstnameContaining"), is(notNullValue()));
|
||||
assertThat(searchMappings.isExported()).isTrue();
|
||||
assertThat(searchMappings.getMappedMethod("findByFirstnameContaining")).isNotNull();
|
||||
|
||||
for (MethodResourceMapping methodMapping : searchMappings) {
|
||||
|
||||
System.out.println(methodMapping.getMethod().getName());
|
||||
assertThat(methodMapping.isExported(), is(true));
|
||||
assertThat(methodMapping.isExported()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +162,7 @@ public class RepositoryResourceMappingsIntegrationTests {
|
||||
|
||||
PropertyAwareResourceMapping propertyMapping = metadata.getProperty("father-mapped");
|
||||
|
||||
assertThat(propertyMapping.getRel(), is("father"));
|
||||
assertThat(propertyMapping.getPath(), is(new Path("father-mapped")));
|
||||
assertThat(propertyMapping.getRel()).isEqualTo("father");
|
||||
assertThat(propertyMapping.getPath()).isEqualTo(new Path("father-mapped"));
|
||||
}
|
||||
}
|
||||
|
||||
29
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/TypeBasedCollectionResourceMappingUnitTests.java
Normal file → Executable file
29
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/TypeBasedCollectionResourceMappingUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.rest.core.Path;
|
||||
@@ -34,10 +33,10 @@ public class TypeBasedCollectionResourceMappingUnitTests {
|
||||
|
||||
CollectionResourceMapping mapping = new TypeBasedCollectionResourceMapping(Sample.class);
|
||||
|
||||
assertThat(mapping.getPath(), is(new Path("sample")));
|
||||
assertThat(mapping.getRel(), is("samples"));
|
||||
assertThat(mapping.getItemResourceRel(), is("sample"));
|
||||
assertThat(mapping.isExported(), is(true));
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("sample"));
|
||||
assertThat(mapping.getRel()).isEqualTo("samples");
|
||||
assertThat(mapping.getItemResourceRel()).isEqualTo("sample");
|
||||
assertThat(mapping.isExported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -45,10 +44,10 @@ public class TypeBasedCollectionResourceMappingUnitTests {
|
||||
|
||||
CollectionResourceMapping mapping = new TypeBasedCollectionResourceMapping(CustomizedSample.class);
|
||||
|
||||
assertThat(mapping.getPath(), is(new Path("customizedSample")));
|
||||
assertThat(mapping.getRel(), is("myRel"));
|
||||
assertThat(mapping.getItemResourceRel(), is("customizedSample"));
|
||||
assertThat(mapping.isExported(), is(true));
|
||||
assertThat(mapping.getPath()).isEqualTo(new Path("customizedSample"));
|
||||
assertThat(mapping.getRel()).isEqualTo("myRel");
|
||||
assertThat(mapping.getItemResourceRel()).isEqualTo("customizedSample");
|
||||
assertThat(mapping.isExported()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-99
|
||||
@@ -56,7 +55,7 @@ public class TypeBasedCollectionResourceMappingUnitTests {
|
||||
|
||||
CollectionResourceMapping mapping = new TypeBasedCollectionResourceMapping(HiddenSample.class);
|
||||
|
||||
assertThat(mapping.isExported(), is(false));
|
||||
assertThat(mapping.isExported()).isFalse();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,13 +67,13 @@ public class TypeBasedCollectionResourceMappingUnitTests {
|
||||
CollectionResourceMapping mapping = new TypeBasedCollectionResourceMapping(Sample.class);
|
||||
ResourceDescription description = mapping.getDescription();
|
||||
|
||||
assertThat(description.isDefault(), is(true));
|
||||
assertThat(description.getMessage(), is("rest.description.samples"));
|
||||
assertThat(description.isDefault()).isTrue();
|
||||
assertThat(description.getMessage()).isEqualTo("rest.description.samples");
|
||||
|
||||
ResourceDescription itemDescription = mapping.getItemResourceDescription();
|
||||
|
||||
assertThat(itemDescription.isDefault(), is(true));
|
||||
assertThat(itemDescription.getMessage(), is("rest.description.sample"));
|
||||
assertThat(itemDescription.isDefault()).isTrue();
|
||||
assertThat(itemDescription.getMessage()).isEqualTo("rest.description.sample");
|
||||
}
|
||||
|
||||
public interface Sample {}
|
||||
|
||||
22
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DefaultSelfLinkProviderUnitTests.java
Normal file → Executable file
22
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DefaultSelfLinkProviderUnitTests.java
Normal file → Executable file
@@ -16,7 +16,7 @@
|
||||
package org.springframework.data.rest.core.support;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
@@ -31,9 +31,7 @@ import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext;
|
||||
import org.springframework.data.mapping.context.PersistentEntities;
|
||||
import org.springframework.data.rest.core.domain.Profile;
|
||||
@@ -60,19 +58,15 @@ public class DefaultSelfLinkProviderUnitTests {
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
when(entityLinks.linkToSingleResource((Class<?>) any(), any())).then(new Answer<Link>() {
|
||||
when(entityLinks.linkToSingleResource((Class<?>) any(), any())).then(invocation -> {
|
||||
|
||||
@Override
|
||||
public Link answer(InvocationOnMock invocation) throws Throwable {
|
||||
Class<?> type = invocation.getArgument(0);
|
||||
Serializable id = invocation.getArgument(1);
|
||||
|
||||
Class<?> type = invocation.getArgumentAt(0, Class.class);
|
||||
Serializable id = invocation.getArgumentAt(1, Serializable.class);
|
||||
|
||||
return new Link("/".concat(type.getName()).concat("/").concat(id.toString()));
|
||||
}
|
||||
return new Link("/".concat(type.getName()).concat("/").concat(id.toString()));
|
||||
});
|
||||
|
||||
KeyValueMappingContext context = new KeyValueMappingContext();
|
||||
KeyValueMappingContext<?, ?> context = new KeyValueMappingContext<>();
|
||||
context.getPersistentEntity(Profile.class);
|
||||
context.afterPropertiesSet();
|
||||
|
||||
@@ -125,7 +119,7 @@ public class DefaultSelfLinkProviderUnitTests {
|
||||
|
||||
exception.expect(IllegalArgumentException.class);
|
||||
exception.expectMessage(Object.class.getName());
|
||||
exception.expectMessage("No persistent entity found!");
|
||||
exception.expectMessage("Couldn't find PersistentEntity for");
|
||||
|
||||
provider.createSelfLinkFor(new Object());
|
||||
}
|
||||
|
||||
13
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerTests.java
Normal file → Executable file
13
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.support;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.rest.core.support.DomainObjectMerger.NullHandlingPolicy.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
@@ -60,8 +59,8 @@ public class DomainObjectMergerTests {
|
||||
|
||||
merger.merge(incoming, existingDomainObject, APPLY_NULLS);
|
||||
|
||||
assertThat(existingDomainObject.getFirstName(), is(incoming.getFirstName()));
|
||||
assertThat(existingDomainObject.getLastName(), is(incoming.getLastName()));
|
||||
assertThat(existingDomainObject.getFirstName()).isEqualTo(incoming.getFirstName());
|
||||
assertThat(existingDomainObject.getLastName()).isEqualTo(incoming.getLastName());
|
||||
}
|
||||
|
||||
@Test // DATAREST-130
|
||||
@@ -72,8 +71,8 @@ public class DomainObjectMergerTests {
|
||||
|
||||
merger.merge(incoming, existingDomainObject, APPLY_NULLS);
|
||||
|
||||
assertThat(existingDomainObject.getFirstName(), is(incoming.getFirstName()));
|
||||
assertThat(existingDomainObject.getLastName(), is(incoming.getLastName()));
|
||||
assertThat(existingDomainObject.getFirstName()).isEqualTo(incoming.getFirstName());
|
||||
assertThat(existingDomainObject.getLastName()).isEqualTo(incoming.getLastName());
|
||||
}
|
||||
|
||||
@Test // DATAREST-327
|
||||
@@ -86,6 +85,6 @@ public class DomainObjectMergerTests {
|
||||
|
||||
merger.merge(new Person("Sam", null), frodo, IGNORE_NULLS);
|
||||
|
||||
assertThat(frodo.getSiblings(), is(not(emptyIterable())));
|
||||
assertThat(frodo.getSiblings()).isNotEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
22
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerUnitTests.java
Normal file → Executable file
22
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerUnitTests.java
Normal file → Executable file
@@ -15,12 +15,12 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.support;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.rest.core.support.DomainObjectMerger.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -34,16 +34,16 @@ public class DomainObjectMergerUnitTests {
|
||||
@Test // DATAREST-327
|
||||
public void considersEmptyObjectsEmpty() {
|
||||
|
||||
assertThat(isNullOrEmpty(null), is(true));
|
||||
assertThat(isNullOrEmpty(Collections.emptyList()), is(true));
|
||||
assertThat(isNullOrEmpty(new Object[0]), is(true));
|
||||
assertThat(isNullOrEmpty(new String[0]), is(true));
|
||||
assertThat(isNullOrEmpty(new MyIterable()), is(true));
|
||||
assertThat(isNullOrEmpty(Optional.empty())).isTrue();
|
||||
assertThat(isNullOrEmpty(Optional.of(Collections.emptyList()))).isTrue();
|
||||
assertThat(isNullOrEmpty(Optional.of(new Object[0]))).isTrue();
|
||||
assertThat(isNullOrEmpty(Optional.of(new String[0]))).isTrue();
|
||||
assertThat(isNullOrEmpty(Optional.of(new MyIterable()))).isTrue();
|
||||
|
||||
assertThat(isNullOrEmpty(new Object()), is(false));
|
||||
assertThat(isNullOrEmpty(Collections.singleton(new Object())), is(false));
|
||||
assertThat(isNullOrEmpty(new Object[] { "1" }), is(false));
|
||||
assertThat(isNullOrEmpty(new String[] { "1" }), is(false));
|
||||
assertThat(isNullOrEmpty(Optional.of(new Object()))).isFalse();
|
||||
assertThat(isNullOrEmpty(Optional.of(Collections.singleton(new Object())))).isFalse();
|
||||
assertThat(isNullOrEmpty(Optional.of(new Object[] { "1" }))).isFalse();
|
||||
assertThat(isNullOrEmpty(Optional.of(new String[] { "1" }))).isFalse();
|
||||
}
|
||||
|
||||
class MyIterable implements Iterable<Object> {
|
||||
|
||||
30
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/ResourceStringUtilsTests.java
Normal file → Executable file
30
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/ResourceStringUtilsTests.java
Normal file → Executable file
@@ -15,17 +15,15 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.support;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.springframework.data.rest.core.support.ResourceStringUtils;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.runners.Parameterized.Parameters;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
/**
|
||||
* Ensures proper detection and removal of leading slash in strings.
|
||||
@@ -48,23 +46,25 @@ public class ResourceStringUtilsTests {
|
||||
|
||||
@Parameters(name = "{0}")
|
||||
public static Collection<?> parameters() {
|
||||
return Arrays.asList(new Object[][] {
|
||||
{ "empty string has no text and should remain empty", "", "", false },
|
||||
{ "blank string has no text and should remain as is", " ", " ", false },
|
||||
{ "string made of only a leading slash has no text and should be returned empty", "/", "", false },
|
||||
{ "blank string with only slashes has no text and should be returned as is", " / ", " / ", false },
|
||||
{ "normal string has text and should be returned as such", "hello", "hello", true },
|
||||
{ "normal string with leading slash has text and should be returned without leading slash", "/hello", "hello",
|
||||
true }, });
|
||||
return Arrays
|
||||
.asList(
|
||||
new Object[][] { { "empty string has no text and should remain empty", "", "", false },
|
||||
{ "blank string has no text and should remain as is", " ", " ", false },
|
||||
{ "string made of only a leading slash has no text and should be returned empty", "/", "", false },
|
||||
{ "blank string with only slashes has no text and should be returned as is", " / ", " / ",
|
||||
false },
|
||||
{ "normal string has text and should be returned as such", "hello", "hello", true },
|
||||
{ "normal string with leading slash has text and should be returned without leading slash", "/hello",
|
||||
"hello", true }, });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDetectTextPresence() {
|
||||
assertThat(ResourceStringUtils.hasTextExceptSlash(actual), is(hasText));
|
||||
assertThat(ResourceStringUtils.hasTextExceptSlash(actual)).isEqualTo(hasText);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldRemoveLeadingSlashIfAny() {
|
||||
assertThat(ResourceStringUtils.removeLeadingSlash(actual), is(expected));
|
||||
assertThat(ResourceStringUtils.removeLeadingSlash(actual)).isEqualTo(expected);
|
||||
}
|
||||
}
|
||||
|
||||
47
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactoryUnitTests.java
Normal file → Executable file
47
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactoryUnitTests.java
Normal file → Executable file
@@ -15,9 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
@@ -25,8 +23,9 @@ import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.assertj.core.api.AbstractOptionalAssert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -36,7 +35,6 @@ import org.junit.runners.Parameterized.Parameters;
|
||||
import org.springframework.data.repository.support.RepositoryInvoker;
|
||||
import org.springframework.data.repository.support.RepositoryInvokerFactory;
|
||||
import org.springframework.data.rest.core.domain.Profile;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link UnwrappingRepositoryInvokerFactory}.
|
||||
@@ -54,8 +52,8 @@ public class UnwrappingRepositoryInvokerFactoryUnitTests {
|
||||
RepositoryInvokerFactory factory;
|
||||
Method method;
|
||||
|
||||
public @Parameter(value = 0) Object source;
|
||||
public @Parameter(value = 1) Matcher<Object> value;
|
||||
public @Parameter(0) Object source;
|
||||
public @Parameter(1) Consumer<AbstractOptionalAssert<?, Object>> value;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@@ -68,31 +66,23 @@ public class UnwrappingRepositoryInvokerFactoryUnitTests {
|
||||
|
||||
@Parameters
|
||||
public static Collection<Object[]> data() {
|
||||
|
||||
return Arrays.asList(new Object[][] { //
|
||||
{ Optional.empty(), is(nullValue()) }, //
|
||||
{ Optional.of(REFERENCE), is(REFERENCE) }, //
|
||||
{ com.google.common.base.Optional.absent(), is(nullValue()) }, //
|
||||
{ com.google.common.base.Optional.of(REFERENCE), is(REFERENCE) } //
|
||||
{ null, $(it -> it.isEmpty()) }, //
|
||||
{ Optional.empty(), $(it -> it.isEmpty()) }, //
|
||||
{ Optional.of(REFERENCE), $(it -> it.hasValue(REFERENCE)) }, //
|
||||
{ com.google.common.base.Optional.absent(), $(it -> it.isEmpty()) }, //
|
||||
{ com.google.common.base.Optional.of(REFERENCE), $(it -> it.hasValue(REFERENCE)) } //
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATAREST-511
|
||||
public void unwrapsValuesForFindOne() {
|
||||
assertFindOneValueForSource(source, value);
|
||||
}
|
||||
|
||||
@Test // DATAREST-511
|
||||
public void unwrapsValuesForQuery() {
|
||||
assertQueryValueForSource(source, value);
|
||||
}
|
||||
|
||||
@Test // DATAREST-724
|
||||
@SuppressWarnings("unchecked")
|
||||
public void usesRegisteredEntityLookup() {
|
||||
|
||||
EntityLookup<Object> lookup = mock(EntityLookup.class);
|
||||
when(lookup.supports(Profile.class)).thenReturn(true);
|
||||
|
||||
when(lookup.supports(Profile.class)).thenReturn(true);
|
||||
when(delegate.getInvokerFor(Profile.class)).thenReturn(invoker);
|
||||
|
||||
factory = new UnwrappingRepositoryInvokerFactory(delegate, Arrays.asList(lookup));
|
||||
@@ -101,16 +91,7 @@ public class UnwrappingRepositoryInvokerFactoryUnitTests {
|
||||
verify(lookup, times(1)).lookupEntity(eq(1L));
|
||||
}
|
||||
|
||||
private void assertFindOneValueForSource(Object source, Matcher<Object> value) {
|
||||
|
||||
when(invoker.invokeFindOne(1L)).thenReturn(source);
|
||||
assertThat(factory.getInvokerFor(Object.class).invokeFindOne(1L), value);
|
||||
}
|
||||
|
||||
private void assertQueryValueForSource(Object source, Matcher<Object> value) {
|
||||
|
||||
when(invoker.invokeQueryMethod(method, new LinkedMultiValueMap<String, Object>(), null, null)).thenReturn(source);
|
||||
assertThat(factory.getInvokerFor(Object.class).invokeQueryMethod(method, new LinkedMultiValueMap<String, Object>(),
|
||||
null, null), value);
|
||||
private static Consumer<AbstractOptionalAssert<?, Object>> $(Consumer<AbstractOptionalAssert<?, Object>> consumer) {
|
||||
return consumer;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.rest.core.util;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class FunctionTests {
|
||||
|
||||
@Test
|
||||
public void foo() {
|
||||
|
||||
Foo foo = new Foo();
|
||||
|
||||
foo.apply(new Function<String, Integer>() {
|
||||
|
||||
@Override
|
||||
public Integer apply(String input) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static class Foo {
|
||||
|
||||
public Integer apply(Function<String, Integer> function) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
18
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/MethodsUnitTests.java
Normal file → Executable file
18
spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/MethodsUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.core.util;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashSet;
|
||||
@@ -25,7 +24,6 @@ import java.util.Set;
|
||||
import org.junit.Test;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.ReflectionUtils.MethodCallback;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link Methods}.
|
||||
@@ -41,18 +39,12 @@ public class MethodsUnitTests {
|
||||
factory.setTarget(new Sample());
|
||||
factory.setProxyTargetClass(true);
|
||||
|
||||
final Set<Method> methods = new HashSet<Method>();
|
||||
Set<Method> methods = new HashSet<Method>();
|
||||
|
||||
ReflectionUtils.doWithMethods(factory.getProxy().getClass(), new MethodCallback() {
|
||||
ReflectionUtils.doWithMethods(factory.getProxy().getClass(), method -> methods.add(method), Methods.USER_METHODS);
|
||||
|
||||
@Override
|
||||
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
|
||||
methods.add(method);
|
||||
}
|
||||
}, Methods.USER_METHODS);
|
||||
|
||||
assertThat(methods, hasSize(1));
|
||||
assertThat(methods, contains(Sample.class.getMethod("method")));
|
||||
assertThat(methods).hasSize(1);
|
||||
assertThat(methods).contains(Sample.class.getMethod("method"));
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
|
||||
7
spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserIntegrationTests.java
Normal file → Executable file
7
spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserIntegrationTests.java
Normal file → Executable file
@@ -22,9 +22,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
|
||||
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
|
||||
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
|
||||
@@ -58,6 +61,10 @@ public class HalBrowserIntegrationTests {
|
||||
@EnableWebMvc
|
||||
static class TestConfiguration extends RepositoryRestMvcConfiguration {
|
||||
|
||||
public TestConfiguration(ApplicationContext context, ObjectFactory<ConversionService> conversionService) {
|
||||
super(context, conversionService);
|
||||
}
|
||||
|
||||
@Bean
|
||||
RepositoryRestConfigurerAdapter configExtension() {
|
||||
|
||||
|
||||
9
spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserUnitTests.java
Normal file → Executable file
9
spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserUnitTests.java
Normal file → Executable file
@@ -15,8 +15,9 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.halbrowser;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@@ -48,14 +49,14 @@ public class HalBrowserUnitTests {
|
||||
|
||||
View view = new HalBrowser().browser(request);
|
||||
|
||||
assertThat(view, is(instanceOf(RedirectView.class)));
|
||||
assertThat(view).isInstanceOf(RedirectView.class);
|
||||
|
||||
((AbstractView) view).render(Collections.<String, Object> emptyMap(), request, response);
|
||||
|
||||
UriComponents components = UriComponentsBuilder.fromUriString(response.getHeader(HttpHeaders.LOCATION)).build();
|
||||
|
||||
assertThat(components.getPath(), startsWith("/context"));
|
||||
assertThat(components.getFragment(), is("/context"));
|
||||
assertThat(components.getFragment()).isEqualTo("/context");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -69,7 +70,7 @@ public class HalBrowserUnitTests {
|
||||
|
||||
View view = new HalBrowser().browser(request);
|
||||
|
||||
assertThat(view, is(instanceOf(RedirectView.class)));
|
||||
assertThat(view).isInstanceOf(RedirectView.class);
|
||||
|
||||
String url = ((RedirectView) view).getUrl();
|
||||
|
||||
|
||||
@@ -19,9 +19,12 @@ import java.util.Collections;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.repository.support.Repositories;
|
||||
import org.springframework.data.repository.support.RepositoryInvokerFactory;
|
||||
@@ -58,6 +61,10 @@ public abstract class AbstractControllerIntegrationTests {
|
||||
@Configuration
|
||||
public static class TestConfiguration extends RepositoryRestMvcConfiguration {
|
||||
|
||||
public TestConfiguration(ApplicationContext context, ObjectFactory<ConversionService> conversionService) {
|
||||
super(context, conversionService);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistentEntityResourceAssembler persistentEntityResourceAssembler() {
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.springframework.data.rest.tests;
|
||||
/*
|
||||
* Copyright 2013-2016 the original author or authors.
|
||||
* Copyright 2013-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -14,9 +13,11 @@ package org.springframework.data.rest.tests;
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.rest.tests;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@@ -80,18 +81,18 @@ public abstract class AbstractWebIntegrationTests {
|
||||
}
|
||||
|
||||
protected void setupMockMvc() {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(context).//
|
||||
defaultRequest(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE)).build();
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(context)//
|
||||
.defaultRequest(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE)).build();
|
||||
}
|
||||
|
||||
protected MockHttpServletResponse postAndGet(Link link, Object payload, MediaType mediaType) throws Exception {
|
||||
|
||||
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
|
||||
|
||||
MockHttpServletResponse response = mvc.perform(post(href).content(payload.toString()).contentType(mediaType)).//
|
||||
andExpect(status().isCreated()).//
|
||||
andExpect(header().string("Location", is(notNullValue()))).//
|
||||
andReturn().getResponse();
|
||||
MockHttpServletResponse response = mvc.perform(post(href).content(payload.toString()).contentType(mediaType))//
|
||||
.andExpect(status().isCreated())//
|
||||
.andExpect(header().string("Location", is(notNullValue())))//
|
||||
.andReturn().getResponse();
|
||||
|
||||
String content = response.getContentAsString();
|
||||
|
||||
@@ -106,9 +107,9 @@ public abstract class AbstractWebIntegrationTests {
|
||||
|
||||
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
|
||||
|
||||
MockHttpServletResponse response = mvc.perform(put(href).content(payload.toString()).contentType(mediaType)).//
|
||||
andExpect(status().is2xxSuccessful()).//
|
||||
andReturn().getResponse();
|
||||
MockHttpServletResponse response = mvc.perform(put(href).content(payload.toString()).contentType(mediaType))//
|
||||
.andExpect(status().is2xxSuccessful())//
|
||||
.andReturn().getResponse();
|
||||
|
||||
return StringUtils.hasText(response.getContentAsString()) ? response : client.request(link);
|
||||
}
|
||||
@@ -120,9 +121,8 @@ public abstract class AbstractWebIntegrationTests {
|
||||
MockHttpServletResponse response = mvc
|
||||
.perform(MockMvcRequestBuilders.request(HttpMethod.PATCH, href).//
|
||||
content(payload.toString()).contentType(mediaType))
|
||||
.//
|
||||
andExpect(status().is2xxSuccessful()).//
|
||||
andReturn().getResponse();
|
||||
.andExpect(status().is2xxSuccessful())//
|
||||
.andReturn().getResponse();
|
||||
|
||||
return StringUtils.hasText(response.getContentAsString()) ? response : client.request(href);
|
||||
}
|
||||
@@ -131,13 +131,13 @@ public abstract class AbstractWebIntegrationTests {
|
||||
|
||||
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
|
||||
|
||||
mvc.perform(delete(href)).//
|
||||
andExpect(status().isNoContent()).//
|
||||
andReturn().getResponse();
|
||||
mvc.perform(delete(href))//
|
||||
.andExpect(status().isNoContent())//
|
||||
.andReturn().getResponse();
|
||||
|
||||
// Check that the resource is unavailable after a DELETE
|
||||
mvc.perform(get(href)).//
|
||||
andExpect(status().isNotFound());
|
||||
mvc.perform(get(href))//
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
protected Link assertHasContentLinkWithRel(String rel, MockHttpServletResponse response) throws Exception {
|
||||
@@ -157,8 +157,13 @@ public abstract class AbstractWebIntegrationTests {
|
||||
|
||||
String href = JsonPath.<JSONArray> read(content, String.format(CONTENT_LINK_JSONPATH, rel)).get(0).toString();
|
||||
|
||||
assertThat("Expected to find a link with rel" + rel + " in the content section of the response!", href,
|
||||
is(expected ? notNullValue() : nullValue()));
|
||||
String message = "Expected to%s find a link with rel %s in the content section of the response!";
|
||||
|
||||
if (expected) {
|
||||
assertThat(href).as(message, "", rel).isNotNull();
|
||||
} else {
|
||||
assertThat(href).as(message, " not", rel).isNull();
|
||||
}
|
||||
|
||||
return new Link(href, rel);
|
||||
|
||||
@@ -177,7 +182,7 @@ public abstract class AbstractWebIntegrationTests {
|
||||
String content = response.getContentAsString();
|
||||
Link link = client.getDiscoverer(response).findLinkWithRel(rel, content);
|
||||
|
||||
assertThat("Expected not to find link with rel " + rel + " but found " + link + "!", link, is(nullValue()));
|
||||
assertThat(link).as("Expected not to find link with rel %s but found %s!", rel, link).isNull();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -186,12 +191,11 @@ public abstract class AbstractWebIntegrationTests {
|
||||
String content = response.getContentAsString();
|
||||
Object jsonPathResult = JsonPath.read(content, path);
|
||||
|
||||
assertThat(String.format("JSONPath lookup for %s did return null in %s.", path, content), jsonPathResult,
|
||||
is(notNullValue()));
|
||||
assertThat(jsonPathResult).as("JSONPath lookup for %s did return null in %s.", path, content).isNotNull();
|
||||
|
||||
if (jsonPathResult instanceof JSONArray) {
|
||||
JSONArray array = (JSONArray) jsonPathResult;
|
||||
assertThat(array, hasSize(greaterThan(0)));
|
||||
assertThat(array.size()).isGreaterThan(0);
|
||||
}
|
||||
|
||||
return (T) jsonPathResult;
|
||||
@@ -223,7 +227,7 @@ public abstract class AbstractWebIntegrationTests {
|
||||
jsonString = jsonQueryResults != null ? jsonQueryResults.toString() : null;
|
||||
}
|
||||
|
||||
assertThat(jsonString, is(expected));
|
||||
assertThat(jsonString).isEqualTo(expected);
|
||||
return jsonString;
|
||||
}
|
||||
|
||||
@@ -237,8 +241,9 @@ public abstract class AbstractWebIntegrationTests {
|
||||
MockHttpServletResponse response = result.getResponse();
|
||||
String s = response.getContentAsString();
|
||||
|
||||
assertThat("Expected not to find link with rel " + rel + " but found one in " + s, //
|
||||
client.getDiscoverer(response).findLinkWithRel(rel, s), nullValue());
|
||||
assertThat(client.getDiscoverer(response).findLinkWithRel(rel, s))//
|
||||
.as("Expected not to find link with rel %s but found one in %s!", rel, s)//
|
||||
.isNull();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
8
spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/CommonWebTests.java
Normal file → Executable file
8
spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/CommonWebTests.java
Normal file → Executable file
@@ -1,4 +1,3 @@
|
||||
package org.springframework.data.rest.tests;
|
||||
/*
|
||||
* Copyright 2013-2017 the original author or authors.
|
||||
*
|
||||
@@ -14,9 +13,10 @@ package org.springframework.data.rest.tests;
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.rest.tests;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assume.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
@@ -215,8 +215,8 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
|
||||
|
||||
Links links = Links.valueOf(response.getHeader("Link"));
|
||||
|
||||
assertThat(links.hasLink(Link.REL_SELF), is(true));
|
||||
assertThat(links.hasLink("profile"), is(true));
|
||||
assertThat(links.hasLink(Link.REL_SELF)).isTrue();
|
||||
assertThat(links.hasLink("profile")).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,12 +39,12 @@ import org.springframework.data.rest.core.mapping.RepositoryResourceMappings;
|
||||
import org.springframework.data.rest.core.support.DefaultSelfLinkProvider;
|
||||
import org.springframework.data.rest.core.support.EntityLookup;
|
||||
import org.springframework.data.rest.core.support.SelfLinkProvider;
|
||||
import org.springframework.data.rest.core.util.Java8PluginRegistry;
|
||||
import org.springframework.data.rest.webmvc.EmbeddedResourcesAssembler;
|
||||
import org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module;
|
||||
import org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module.LookupObjectSerializer;
|
||||
import org.springframework.data.rest.webmvc.mapping.Associations;
|
||||
import org.springframework.data.rest.webmvc.mapping.LinkCollector;
|
||||
import org.springframework.data.rest.webmvc.spi.BackendIdConverter;
|
||||
import org.springframework.data.rest.webmvc.spi.BackendIdConverter.DefaultIdConverter;
|
||||
import org.springframework.data.rest.webmvc.support.ExcerptProjector;
|
||||
import org.springframework.data.rest.webmvc.support.PagingAndSortingTemplateVariables;
|
||||
@@ -57,7 +57,6 @@ import org.springframework.hateoas.ResourceProcessor;
|
||||
import org.springframework.hateoas.core.EvoInflectorRelProvider;
|
||||
import org.springframework.hateoas.hal.Jackson2HalModule;
|
||||
import org.springframework.hateoas.mvc.ResourceProcessorInvoker;
|
||||
import org.springframework.plugin.core.OrderAwarePluginRegistry;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
@@ -111,7 +110,7 @@ public class RepositoryTestsConfig {
|
||||
config().getRepositoryDetectionStrategy());
|
||||
EntityLinks entityLinks = new RepositoryEntityLinks(repositories(), mappings, config(),
|
||||
mock(PagingAndSortingTemplateVariables.class),
|
||||
OrderAwarePluginRegistry.<Class<?>, BackendIdConverter> create(Arrays.asList(DefaultIdConverter.INSTANCE)));
|
||||
Java8PluginRegistry.of(Arrays.asList(DefaultIdConverter.INSTANCE)));
|
||||
SelfLinkProvider selfLinkProvider = new DefaultSelfLinkProvider(persistentEntities(), entityLinks,
|
||||
Collections.<EntityLookup<?>> emptyList());
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.rest.tests.TestMvcClient.*;
|
||||
|
||||
import org.junit.Test;
|
||||
@@ -50,7 +49,7 @@ public class RepositoryControllerIntegrationTests extends AbstractControllerInte
|
||||
|
||||
@Test // DATAREST-333, DATAREST-330
|
||||
public void headRequestReturnsNoContent() {
|
||||
assertThat(controller.headForRepositories().getStatusCode(), is(HttpStatus.NO_CONTENT));
|
||||
assertThat(controller.headForRepositories().getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Test // DATAREST-160, DATAREST-333, DATAREST-463
|
||||
@@ -58,14 +57,14 @@ public class RepositoryControllerIntegrationTests extends AbstractControllerInte
|
||||
|
||||
RepositoryLinksResource resource = controller.listRepositories().getBody();
|
||||
|
||||
assertThat(resource.getLinks(), hasSize(8));
|
||||
assertThat(resource.getLinks()).hasSize(8);
|
||||
|
||||
assertThat(resource.hasLink("people"), is(true));
|
||||
assertThat(resource.hasLink("orders"), is(true));
|
||||
assertThat(resource.hasLink("addresses"), is(true));
|
||||
assertThat(resource.hasLink("books"), is(true));
|
||||
assertThat(resource.hasLink("authors"), is(true));
|
||||
assertThat(resource.hasLink("receipts"), is(true));
|
||||
assertThat(resource.hasLink("items"), is(true));
|
||||
assertThat(resource.hasLink("people")).isTrue();
|
||||
assertThat(resource.hasLink("orders")).isTrue();
|
||||
assertThat(resource.hasLink("addresses")).isTrue();
|
||||
assertThat(resource.hasLink("books")).isTrue();
|
||||
assertThat(resource.hasLink("authors")).isTrue();
|
||||
assertThat(resource.hasLink("receipts")).isTrue();
|
||||
assertThat(resource.hasLink("items")).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,13 +15,16 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.data.rest.tests.TestMvcClient.*;
|
||||
import static org.springframework.http.HttpMethod.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
@@ -89,7 +92,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
RootResourceInformation information = getResourceInformation(Order.class);
|
||||
|
||||
PersistentEntityResource persistentEntityResource = PersistentEntityResource
|
||||
.build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build();
|
||||
.build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build();
|
||||
|
||||
ResponseEntity<?> entity = controller.putItemResource(information, persistentEntityResource, 1L, assembler,
|
||||
ETag.NO_ETAG, MediaType.APPLICATION_JSON_VALUE);
|
||||
@@ -101,7 +104,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
public void exposesHeadForCollectionResourceIfExported() throws Exception {
|
||||
ResponseEntity<?> entity = controller.headCollectionResource(getResourceInformation(Person.class),
|
||||
new DefaultedPageable(null, false));
|
||||
assertThat(entity.getStatusCode(), is(HttpStatus.NO_CONTENT));
|
||||
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Test(expected = ResourceNotFoundException.class) // DATAREST-330
|
||||
@@ -117,7 +120,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
ResponseEntity<?> entity = controller.headForItemResource(getResourceInformation(Address.class), address.id,
|
||||
assembler);
|
||||
|
||||
assertThat(entity.getStatusCode(), is(HttpStatus.NO_CONTENT));
|
||||
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Test(expected = ResourceNotFoundException.class) // DATAREST-330
|
||||
@@ -153,7 +156,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
|
||||
List<String> value = entity.getHeaders().get("Accept-Patch");
|
||||
|
||||
assertThat(value, hasSize(3));
|
||||
assertThat(value).hasSize(3);
|
||||
assertThat(value,
|
||||
hasItems(//
|
||||
RestMediaTypes.JSON_PATCH_JSON.toString(), //
|
||||
@@ -168,7 +171,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
Order order = request.getInvoker().invokeSave(new Order(new Person()));
|
||||
|
||||
PersistentEntityResource persistentEntityResource = PersistentEntityResource
|
||||
.build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build();
|
||||
.build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build();
|
||||
|
||||
assertThat(controller.putItemResource(request, persistentEntityResource, order.getId(), assembler, ETag.NO_ETAG,
|
||||
MediaType.APPLICATION_JSON_VALUE).hasBody(), is(true));
|
||||
@@ -179,7 +182,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
|
||||
RootResourceInformation request = getResourceInformation(Order.class);
|
||||
PersistentEntityResource persistentEntityResource = PersistentEntityResource
|
||||
.build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build();
|
||||
.build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build();
|
||||
|
||||
assertThat(controller.putItemResource(request, persistentEntityResource, 1L, assembler, ETag.NO_ETAG,
|
||||
MediaType.APPLICATION_JSON_VALUE).hasBody(), is(true));
|
||||
@@ -190,7 +193,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
|
||||
RootResourceInformation request = getResourceInformation(Order.class);
|
||||
PersistentEntityResource persistentEntityResource = PersistentEntityResource
|
||||
.build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build();
|
||||
.build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build();
|
||||
|
||||
assertThat(controller
|
||||
.postCollectionResource(request, persistentEntityResource, assembler, MediaType.APPLICATION_JSON_VALUE)
|
||||
@@ -202,7 +205,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
|
||||
RootResourceInformation request = getResourceInformation(Order.class);
|
||||
PersistentEntityResource persistentEntityResource = PersistentEntityResource
|
||||
.build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build();
|
||||
.build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build();
|
||||
|
||||
assertThat(controller.postCollectionResource(request, persistentEntityResource, assembler, null).hasBody(),
|
||||
is(false));
|
||||
@@ -220,32 +223,32 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll
|
||||
.createProjection(AddressProjection.class);
|
||||
|
||||
PersistentEntityResource resource = PersistentEntityResource
|
||||
.build(addressProjection, entities.getPersistentEntity(Address.class)).build();
|
||||
.build(addressProjection, entities.getRequiredPersistentEntity(Address.class)).build();
|
||||
|
||||
Mockito.when(assembler.toFullResource(Mockito.any(Object.class))).thenReturn(resource);
|
||||
|
||||
ResponseEntity<Resource<?>> entity = controller.getItemResource(getResourceInformation(Address.class), address.id,
|
||||
assembler, new HttpHeaders());
|
||||
|
||||
assertThat(entity.getHeaders().getETag(), is(notNullValue()));
|
||||
assertThat(entity.getHeaders().getETag()).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-724
|
||||
public void deletesEntityWithCustomLookupCorrectly() throws Exception {
|
||||
|
||||
Address address = repository.save(new Address());
|
||||
assertThat(repository.findOne(address.id), is(notNullValue()));
|
||||
assertThat(repository.findOne(address.id)).isNotNull();
|
||||
|
||||
RootResourceInformation resourceInformation = getResourceInformation(Address.class);
|
||||
RepositoryInvoker invoker = spy(resourceInformation.getInvoker());
|
||||
doReturn(address).when(invoker).invokeFindOne("foo");
|
||||
doReturn(Optional.of(address)).when(invoker).invokeFindOne("foo");
|
||||
|
||||
RootResourceInformation informationSpy = Mockito.spy(resourceInformation);
|
||||
doReturn(invoker).when(informationSpy).getInvoker();
|
||||
|
||||
controller.deleteItemResource(informationSpy, "foo", ETag.from("0"));
|
||||
|
||||
assertThat(repository.findOne(address.id), is(nullValue()));
|
||||
assertThat(repository.findOne(address.id)).isEmpty();
|
||||
}
|
||||
|
||||
interface AddressProjection {}
|
||||
|
||||
@@ -15,14 +15,14 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.rest.tests.TestMvcClient.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.rest.core.mapping.ResourceMetadata;
|
||||
import org.springframework.data.rest.tests.AbstractControllerIntegrationTests;
|
||||
import org.springframework.data.rest.tests.ResourceTester;
|
||||
@@ -56,7 +56,7 @@ import org.springframework.util.MultiValueMap;
|
||||
@Transactional
|
||||
public class RepositorySearchControllerIntegrationTests extends AbstractControllerIntegrationTests {
|
||||
|
||||
static final DefaultedPageable PAGEABLE = new DefaultedPageable(new PageRequest(0, 10), true);
|
||||
static final DefaultedPageable PAGEABLE = new DefaultedPageable(PageRequest.of(0, 10), true);
|
||||
|
||||
@Autowired TestDataPopulator loader;
|
||||
@Autowired RepositorySearchController controller;
|
||||
@@ -101,12 +101,12 @@ public class RepositorySearchControllerIntegrationTests extends AbstractControll
|
||||
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(1);
|
||||
parameters.add("firstname", "John");
|
||||
|
||||
ResponseEntity<?> response = controller.executeSearch(resourceInformation, parameters, "firstname", PAGEABLE, null,
|
||||
assembler, new HttpHeaders());
|
||||
ResponseEntity<?> response = controller.executeSearch(resourceInformation, parameters, "firstname", PAGEABLE,
|
||||
Sort.unsorted(), assembler, new HttpHeaders());
|
||||
|
||||
ResourceTester tester = ResourceTester.of(response.getBody());
|
||||
PagedResources<Object> pagedResources = tester.assertIsPage();
|
||||
assertThat(pagedResources.getContent().size(), is(1));
|
||||
assertThat(pagedResources.getContent()).hasSize(1);
|
||||
|
||||
ResourceMetadata metadata = getMetadata(Person.class);
|
||||
tester.withContentResource(new HasSelfLink(BASE.slash(metadata.getPath()).slash("{id}")));
|
||||
@@ -165,9 +165,9 @@ public class RepositorySearchControllerIntegrationTests extends AbstractControll
|
||||
RootResourceInformation resourceInformation = getResourceInformation(Book.class);
|
||||
|
||||
ResponseEntity<?> result = controller.executeSearch(resourceInformation, parameters, "findByAuthorsContains",
|
||||
PAGEABLE, null, assembler, new HttpHeaders());
|
||||
PAGEABLE, Sort.unsorted(), assembler, new HttpHeaders());
|
||||
|
||||
assertThat(result.getBody(), is(instanceOf(Resources.class)));
|
||||
assertThat(result.getBody()).isInstanceOf(Resources.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-515
|
||||
@@ -175,6 +175,6 @@ public class RepositorySearchControllerIntegrationTests extends AbstractControll
|
||||
|
||||
RepositorySearchesResource searches = controller.listSearches(getResourceInformation(Person.class));
|
||||
|
||||
assertThat(searches.getDomainType(), is(typeCompatibleWith(Person.class)));
|
||||
assertThat(searches.getDomainType()).isAssignableFrom(Person.class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.rest.core.mapping.ResourceType.*;
|
||||
import static org.springframework.http.HttpMethod.*;
|
||||
|
||||
@@ -44,13 +43,13 @@ public class RootResourceInformationIntegrationTests extends AbstractControllerI
|
||||
public void getIsNotSupportedIfFindAllIsNotExported() {
|
||||
|
||||
SupportedHttpMethods supportedMethods = getResourceInformation(Address.class).getSupportedMethods();
|
||||
assertThat(supportedMethods.getMethodsFor(COLLECTION), not(hasItem(GET)));
|
||||
assertThat(supportedMethods.getMethodsFor(COLLECTION)).doesNotContain(GET);
|
||||
}
|
||||
|
||||
@Test // DATAREST-217
|
||||
public void postIsNotSupportedIfSaveIsNotExported() {
|
||||
|
||||
SupportedHttpMethods supportedMethods = getResourceInformation(Address.class).getSupportedMethods();
|
||||
assertThat(supportedMethods.getMethodsFor(COLLECTION), not(hasItem(POST)));
|
||||
assertThat(supportedMethods.getMethodsFor(COLLECTION)).doesNotContain(POST);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.alps;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
import net.minidev.json.JSONArray;
|
||||
@@ -135,7 +137,7 @@ public class AlpsControllerIntegrationTests extends AbstractControllerIntegratio
|
||||
Link profileLink = client.discoverUnique("profile");
|
||||
Link itemsLink = client.discoverUnique(profileLink, "items", MediaType.ALL);
|
||||
|
||||
assertThat(itemsLink, is(notNullValue()));
|
||||
assertThat(itemsLink).isNotNull();
|
||||
|
||||
String result = client.follow(itemsLink, RestMediaTypes.ALPS_JSON).andReturn().getResponse().getContentAsString();
|
||||
String href = JsonPath.<JSONArray> read(result, "$.alps.descriptors[?(@.id == 'item-representation')].href").get(0)
|
||||
@@ -158,7 +160,7 @@ public class AlpsControllerIntegrationTests extends AbstractControllerIntegratio
|
||||
String result = client.follow(usersLink, RestMediaTypes.ALPS_JSON).andReturn().getResponse().getContentAsString();
|
||||
String rt = JsonPath.<JSONArray> read(result, jsonPath).get(0).toString();
|
||||
|
||||
assertThat(rt, allOf(containsString(ProfileController.PROFILE_ROOT_MAPPING), endsWith("-representation")));
|
||||
assertThat(rt).contains(ProfileController.PROFILE_ROOT_MAPPING).endsWith("-representation");
|
||||
}
|
||||
|
||||
@Test // DATAREST-630
|
||||
@@ -187,7 +189,7 @@ public class AlpsControllerIntegrationTests extends AbstractControllerIntegratio
|
||||
"$.alps.descriptors[?(@.id == 'person-representation')].descriptors[?(@.name == 'gender')].doc.value")
|
||||
.get(0).toString();
|
||||
|
||||
assertThat(value, is("Male, Female, Undefined"));
|
||||
assertThat(value).isEqualTo("Male, Female, Undefined");
|
||||
}
|
||||
|
||||
@Test // DATAREST-753
|
||||
@@ -203,6 +205,6 @@ public class AlpsControllerIntegrationTests extends AbstractControllerIntegratio
|
||||
"$.alps.descriptors[?(@.id == 'simulatedGroovyDomainClass-representation')].descriptors[0].name")
|
||||
.get(0).toString();
|
||||
|
||||
assertThat(name, is("name"));
|
||||
assertThat(name).isEqualTo("name");
|
||||
}
|
||||
}
|
||||
|
||||
13
spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest262Tests.java
Normal file → Executable file
13
spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest262Tests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.jpa;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
import javax.persistence.Embedded;
|
||||
@@ -84,7 +83,7 @@ public class DataRest262Tests {
|
||||
String payload = "{\"orgOrDstFlightPart\":{\"airport\":\"/api/airports/" + airport.id + "\"}}";
|
||||
|
||||
AircraftMovement result = mapper.readValue(payload, AircraftMovement.class);
|
||||
assertThat(result.orgOrDstFlightPart.airport.id, is(airport.id));
|
||||
assertThat(result.orgOrDstFlightPart.airport.id).isEqualTo(airport.id);
|
||||
}
|
||||
|
||||
@Test // DATAREST-262
|
||||
@@ -105,7 +104,7 @@ public class DataRest262Tests {
|
||||
movement.originOrDestinationAirport = first;
|
||||
movement.orgOrDstFlightPart = part;
|
||||
|
||||
JpaPersistentEntity<?> persistentEntity = mappingContext.getPersistentEntity(AircraftMovement.class);
|
||||
JpaPersistentEntity<?> persistentEntity = mappingContext.getRequiredPersistentEntity(AircraftMovement.class);
|
||||
|
||||
Resource<Object> resource = PersistentEntityResource.build(movement, persistentEntity).//
|
||||
withLink(new Link("/api/airports/" + movement.id)).//
|
||||
@@ -113,9 +112,9 @@ public class DataRest262Tests {
|
||||
|
||||
String result = mapper.writeValueAsString(resource);
|
||||
|
||||
assertThat(JsonPath.read(result, "$_links.self"), is(notNullValue()));
|
||||
assertThat(JsonPath.read(result, "$_links.airport"), is(notNullValue()));
|
||||
assertThat(JsonPath.read(result, "$_links.originOrDestinationAirport"), is(notNullValue()));
|
||||
assertThat(JsonPath.<Object> read(result, "$_links.self")).isNotNull();
|
||||
assertThat(JsonPath.<Object> read(result, "$_links.airport")).isNotNull();
|
||||
assertThat(JsonPath.<Object> read(result, "$_links.originOrDestinationAirport")).isNotNull();
|
||||
}
|
||||
|
||||
public interface AircraftMovementRepository extends CrudRepository<AircraftMovement, Long> {
|
||||
|
||||
0
spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest363Tests.java
Normal file → Executable file
0
spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest363Tests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.jpa;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@@ -96,8 +95,8 @@ public class JpaDefaultPageableWebTests extends AbstractWebIntegrationTests {
|
||||
Link findBySortedLink = client.discoverUnique("books", "search", "find-spring-books-sorted");
|
||||
|
||||
// Assert sort options advertised
|
||||
assertThat(findBySortedLink.isTemplated(), is(true));
|
||||
assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection"));
|
||||
assertThat(findBySortedLink.isTemplated()).isTrue();
|
||||
assertThat(findBySortedLink.getVariableNames()).contains("sort", "projection");
|
||||
|
||||
// Assert results returned as specified
|
||||
client.follow(findBySortedLink.expand()).//
|
||||
|
||||
58
spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java
Normal file → Executable file
58
spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java
Normal file → Executable file
@@ -15,8 +15,10 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.jpa;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.springframework.data.rest.webmvc.util.TestUtils.*;
|
||||
import static org.springframework.http.HttpHeaders.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
@@ -149,7 +151,7 @@ public class JpaWebTests extends CommonWebTests {
|
||||
MockHttpServletResponse orders = client.request(ordersLink);
|
||||
Link creatorLink = assertHasContentLinkWithRel("creator", orders);
|
||||
|
||||
assertThat(client.request(creatorLink), is(notNullValue()));
|
||||
assertThat(client.request(creatorLink)).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-200
|
||||
@@ -201,18 +203,18 @@ public class JpaWebTests extends CommonWebTests {
|
||||
|
||||
Link bilboLink = client.assertHasLinkWithRel("self", bilbo);
|
||||
|
||||
assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.firstName"), is("Bilbo"));
|
||||
assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.lastName"), is("Baggins"));
|
||||
assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.firstName")).isEqualTo("Bilbo");
|
||||
assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.lastName")).isEqualTo("Baggins");
|
||||
|
||||
MockHttpServletResponse frodo = patchAndGet(bilboLink, "{ \"firstName\" : \"Frodo\" }", MediaType.APPLICATION_JSON);
|
||||
|
||||
assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName"), is("Frodo"));
|
||||
assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName"), is("Baggins"));
|
||||
assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName")).isEqualTo("Frodo");
|
||||
assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName")).isEqualTo("Baggins");
|
||||
|
||||
frodo = patchAndGet(bilboLink, "{ \"firstName\" : null }", MediaType.APPLICATION_JSON);
|
||||
|
||||
assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName"), is(nullValue()));
|
||||
assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName"), is("Baggins"));
|
||||
assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName")).isNull();
|
||||
assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName")).isEqualTo("Baggins");
|
||||
}
|
||||
|
||||
@Test // DATAREST-150
|
||||
@@ -411,17 +413,17 @@ public class JpaWebTests extends CommonWebTests {
|
||||
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(orderLink.getHref());
|
||||
String uri = builder.queryParam("projection", "summary").build().toUriString();
|
||||
|
||||
response = mvc.perform(get(uri)). //
|
||||
andExpect(status().isOk()). //
|
||||
andExpect(jsonPath("$.price", is(2.5))).//
|
||||
andReturn().getResponse();
|
||||
response = mvc.perform(get(uri))//
|
||||
.andExpect(status().isOk())//
|
||||
.andExpect(jsonPath("$.price", is(2.5)))//
|
||||
.andReturn().getResponse();
|
||||
|
||||
assertJsonPathDoesntExist("$.lineItems", response);
|
||||
}
|
||||
|
||||
@Test // DATAREST-261
|
||||
public void relProviderDetectsCustomizedMapping() {
|
||||
assertThat(relProvider.getCollectionResourceRelFor(Person.class), is("people"));
|
||||
assertThat(relProvider.getCollectionResourceRelFor(Person.class)).isEqualTo("people");
|
||||
}
|
||||
|
||||
@Test // DATAREST-311
|
||||
@@ -445,9 +447,9 @@ public class JpaWebTests extends CommonWebTests {
|
||||
|
||||
JSONArray personLinks = JsonPath.<JSONArray> read(responseBody, "$.links[?(@.rel=='person')].href");
|
||||
|
||||
assertThat(personLinks, hasSize(1));
|
||||
assertThat(personLinks.get(0), is((Object) daenerysLink.getHref()));
|
||||
assertThat(JsonPath.<JSONArray> read(responseBody, "$.content"), hasSize(0));
|
||||
assertThat(personLinks).hasSize(1);
|
||||
assertThat(personLinks.get(0)).isEqualTo((Object) daenerysLink.getHref());
|
||||
assertThat(JsonPath.<JSONArray> read(responseBody, "$.content")).hasSize(0);
|
||||
}
|
||||
|
||||
@Test // DATAREST-317
|
||||
@@ -490,8 +492,8 @@ public class JpaWebTests extends CommonWebTests {
|
||||
Link findBySortedLink = client.discoverUnique(searchLink, "find-by-sorted");
|
||||
|
||||
// Assert sort options advertised
|
||||
assertThat(findBySortedLink.isTemplated(), is(true));
|
||||
assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection"));
|
||||
assertThat(findBySortedLink.isTemplated()).isTrue();
|
||||
assertThat(findBySortedLink.getVariableNames()).contains("sort", "projection");
|
||||
|
||||
// Assert results returned as specified
|
||||
client.follow(findBySortedLink.expand("title,desc")).//
|
||||
@@ -575,8 +577,8 @@ public class JpaWebTests extends CommonWebTests {
|
||||
.andReturn().getResponse();
|
||||
|
||||
Links links = Links.valueOf(response.getHeader("Link"));
|
||||
assertThat(links.hasLink("self"), is(true));
|
||||
assertThat(links.hasLink("person"), is(true));
|
||||
assertThat(links.hasLink("self")).isTrue();
|
||||
assertThat(links.hasLink("person")).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATAREST-883
|
||||
@@ -585,8 +587,8 @@ public class JpaWebTests extends CommonWebTests {
|
||||
Link findBySortedLink = client.discoverUnique("books", "search", "find-by-sorted");
|
||||
|
||||
// Assert sort options advertised
|
||||
assertThat(findBySortedLink.isTemplated(), is(true));
|
||||
assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection"));
|
||||
assertThat(findBySortedLink.isTemplated()).isTrue();
|
||||
assertThat(findBySortedLink.getVariableNames()).contains("sort", "projection");
|
||||
|
||||
// Assert results returned as specified
|
||||
client.follow(findBySortedLink.expand("sales,desc")).//
|
||||
@@ -606,7 +608,7 @@ public class JpaWebTests extends CommonWebTests {
|
||||
Link findByLink = client.discoverUnique("books", "search", "find-spring-books-sorted");
|
||||
|
||||
// Assert sort options advertised
|
||||
assertThat(findByLink.isTemplated(), is(true));
|
||||
assertThat(findByLink.isTemplated()).isTrue();
|
||||
|
||||
// Assert results returned as specified
|
||||
client.follow(findByLink.expand("0", "10", "sales,desc")).//
|
||||
@@ -635,8 +637,8 @@ public class JpaWebTests extends CommonWebTests {
|
||||
Link findBySortedLink = client.discoverUnique(searchLink, "find-by-sorted");
|
||||
|
||||
// Assert sort options advertised
|
||||
assertThat(findBySortedLink.isTemplated(), is(true));
|
||||
assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection"));
|
||||
assertThat(findBySortedLink.isTemplated()).isTrue();
|
||||
assertThat(findBySortedLink.getVariableNames()).contains("sort", "projection");
|
||||
|
||||
// Assert results returned as specified
|
||||
client.follow(findBySortedLink.expand("offer.price,desc")).//
|
||||
@@ -682,8 +684,8 @@ public class JpaWebTests extends CommonWebTests {
|
||||
String responseBody = client.request(link).getContentAsString();
|
||||
List<String> persons = JsonPath.read(responseBody, "$._embedded.people[*].firstName");
|
||||
|
||||
assertThat(persons, hasSize(siblingNames.length));
|
||||
assertThat(persons, hasItems(siblingNames));
|
||||
assertThat(persons).hasSize(siblingNames.length);
|
||||
assertThat(persons).contains(siblingNames);
|
||||
}
|
||||
|
||||
private void assertPersonWithNameAndSiblingLink(String name) throws Exception {
|
||||
@@ -694,8 +696,8 @@ public class JpaWebTests extends CommonWebTests {
|
||||
|
||||
// Assert content inlined
|
||||
Object john = JsonPath.<JSONArray> read(response.getContentAsString(), jsonPath).get(0);
|
||||
assertThat(john, is(notNullValue()));
|
||||
assertThat(JsonPath.read(john, "$.firstName"), is(notNullValue()));
|
||||
assertThat(john).isNotNull();
|
||||
assertThat(JsonPath.<String> read(john, "$.firstName")).isNotNull();
|
||||
|
||||
// Assert sibling link exposed in resource pointed to
|
||||
Link selfLink = new Link(JsonPath.<String> read(john, "$._links.self.href"));
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.jpa;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
import org.junit.Before;
|
||||
@@ -81,19 +81,19 @@ public class ProfileIntegrationTests extends AbstractControllerIntegrationTests
|
||||
.andExpect(jsonPath("$._links.profile.href", endsWith(ProfileController.PROFILE_ROOT_MAPPING)));
|
||||
}
|
||||
|
||||
@Test // DATAREST-230, DATAREST-638
|
||||
@Test // DATAREST-230, DATAREST-638
|
||||
public void profileRootLinkContainsMetadataForEachRepo() throws Exception {
|
||||
|
||||
Link profileLink = client.discoverUnique(new Link(ROOT_URI), ProfileResourceProcessor.PROFILE_REL);
|
||||
|
||||
assertThat(client.discoverUnique(profileLink, "self", MediaType.ALL), is(notNullValue()));
|
||||
assertThat(client.discoverUnique(profileLink, "people", MediaType.ALL), is(notNullValue()));
|
||||
assertThat(client.discoverUnique(profileLink, "items", MediaType.ALL), is(notNullValue()));
|
||||
assertThat(client.discoverUnique(profileLink, "authors", MediaType.ALL), is(notNullValue()));
|
||||
assertThat(client.discoverUnique(profileLink, "books", MediaType.ALL), is(notNullValue()));
|
||||
assertThat(client.discoverUnique(profileLink, "orders", MediaType.ALL), is(notNullValue()));
|
||||
assertThat(client.discoverUnique(profileLink, "receipts", MediaType.ALL), is(notNullValue()));
|
||||
assertThat(client.discoverUnique(profileLink, "addresses", MediaType.ALL), is(notNullValue()));
|
||||
assertThat(client.discoverUnique(profileLink, "self", MediaType.ALL)).isNotNull();
|
||||
assertThat(client.discoverUnique(profileLink, "people", MediaType.ALL)).isNotNull();
|
||||
assertThat(client.discoverUnique(profileLink, "items", MediaType.ALL)).isNotNull();
|
||||
assertThat(client.discoverUnique(profileLink, "authors", MediaType.ALL)).isNotNull();
|
||||
assertThat(client.discoverUnique(profileLink, "books", MediaType.ALL)).isNotNull();
|
||||
assertThat(client.discoverUnique(profileLink, "orders", MediaType.ALL)).isNotNull();
|
||||
assertThat(client.discoverUnique(profileLink, "receipts", MediaType.ALL)).isNotNull();
|
||||
assertThat(client.discoverUnique(profileLink, "addresses", MediaType.ALL)).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-638
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.json;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
@@ -70,12 +69,12 @@ public class Jackson2DatatypeHelperIntegrationTests {
|
||||
}
|
||||
|
||||
@Test // DATAREST-500
|
||||
public void configuresHIbernate4ModuleToLoadLazyLoadingProxies() throws Exception {
|
||||
public void configuresHibernate4ModuleToLoadLazyLoadingProxies() throws Exception {
|
||||
|
||||
PersistentEntity<?, ?> entity = entities.getPersistentEntity(Order.class);
|
||||
PersistentProperty<?> property = entity.getPersistentProperty("creator");
|
||||
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(orders.findOne(this.order.getId()));
|
||||
PersistentEntity<?, ?> entity = entities.getRequiredPersistentEntity(Order.class);
|
||||
PersistentProperty<?> property = entity.getRequiredPersistentProperty("creator");
|
||||
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(orders.findOne(this.order.getId()).orElse(null));
|
||||
|
||||
assertThat(objectMapper.writeValueAsString(accessor.getProperty(property)), is(not("null")));
|
||||
assertThat(objectMapper.writeValueAsString(accessor.getProperty(property))).isNotEqualTo("null");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.json;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -121,9 +122,9 @@ public class PersistentEntitySerializationTests {
|
||||
|
||||
Person p = mapper.readValue(PERSON_JSON_IN, Person.class);
|
||||
|
||||
assertThat(p.getFirstName(), is("John"));
|
||||
assertThat(p.getLastName(), is("Doe"));
|
||||
assertThat(p.getSiblings(), is(Collections.EMPTY_LIST));
|
||||
assertThat(p.getFirstName()).isEqualTo("John");
|
||||
assertThat(p.getLastName()).isEqualTo("Doe");
|
||||
assertThat(p.getSiblings()).isEqualTo(Collections.EMPTY_LIST);
|
||||
}
|
||||
|
||||
@Test // DATAREST-238
|
||||
@@ -170,7 +171,7 @@ public class PersistentEntitySerializationTests {
|
||||
String child = String.format("{ \"firstName\" : \"Bilbo\", \"father\" : \"/persons/%s\"}", father.getId());
|
||||
Person result = mapper.readValue(child, Person.class);
|
||||
|
||||
assertThat(result.getFather(), is(father));
|
||||
assertThat(result.getFather()).isEqualTo(father);
|
||||
}
|
||||
|
||||
@Test // DATAREST-248
|
||||
@@ -183,7 +184,7 @@ public class PersistentEntitySerializationTests {
|
||||
firstSibling.getId(), secondSibling.getId());
|
||||
Person result = mapper.readValue(child, Person.class);
|
||||
|
||||
assertThat(result.getSiblings(), hasItems(firstSibling, secondSibling));
|
||||
assertThat(result.getSiblings()).contains(firstSibling, secondSibling);
|
||||
}
|
||||
|
||||
@Test // DATAREST-248
|
||||
@@ -192,7 +193,7 @@ public class PersistentEntitySerializationTests {
|
||||
String content = TestUtils.readFileFromClasspath("order.json");
|
||||
|
||||
Order order = mapper.readValue(content, Order.class);
|
||||
assertThat(order.getLineItems(), hasSize(2));
|
||||
assertThat(order.getLineItems()).hasSize(2);
|
||||
}
|
||||
|
||||
@Test // DATAREST-250
|
||||
@@ -214,7 +215,7 @@ public class PersistentEntitySerializationTests {
|
||||
|
||||
String result = mapper.writeValueAsString(persistentEntityResource);
|
||||
|
||||
assertThat(JsonPath.read(result, "$._embedded.orders[*].lineItems"), is(notNullValue()));
|
||||
assertThat(JsonPath.<Object> read(result, "$._embedded.orders[*].lineItems")).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-521
|
||||
@@ -237,7 +238,7 @@ public class PersistentEntitySerializationTests {
|
||||
|
||||
String result = mapper.writeValueAsString(resource);
|
||||
|
||||
assertThat(JsonPath.read(result, "$._embedded.father[*]._links.self"), is(notNullValue()));
|
||||
assertThat(JsonPath.<Object> read(result, "$._embedded.father[*]._links.self")).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-521
|
||||
@@ -253,7 +254,7 @@ public class PersistentEntitySerializationTests {
|
||||
|
||||
String result = mapper.writeValueAsString(resource);
|
||||
|
||||
assertThat(JsonPath.read(result, "$._links.processed"), is(notNullValue()));
|
||||
assertThat(JsonPath.<Object> read(result, "$._links.processed")).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-697
|
||||
@@ -267,7 +268,7 @@ public class PersistentEntitySerializationTests {
|
||||
|
||||
String result = mapper.writeValueAsString(new Resource<PersonSummary>(projection));
|
||||
|
||||
assertThat(JsonPath.read(result, "$._links.self"), is(notNullValue()));
|
||||
assertThat(JsonPath.<Object> read(result, "$._links.self")).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-880
|
||||
@@ -275,7 +276,7 @@ public class PersistentEntitySerializationTests {
|
||||
|
||||
CreditCard creditCard = new CreditCard(new CreditCard.CCN("1234123412341234"));
|
||||
|
||||
assertThat(JsonPath.read(mapper.writeValueAsString(creditCard), "$.ccn"), is("1234123412341234"));
|
||||
assertThat(JsonPath.<Object> read(mapper.writeValueAsString(creditCard), "$.ccn")).isEqualTo("1234123412341234");
|
||||
}
|
||||
|
||||
@Test // DATAREST-872
|
||||
@@ -292,12 +293,12 @@ public class PersistentEntitySerializationTests {
|
||||
guest.addMeal(dinner);
|
||||
|
||||
PersistentEntityResource resource = PersistentEntityResource//
|
||||
.build(guest, context.getPersistentEntity(Guest.class))//
|
||||
.build(guest, context.getRequiredPersistentEntity(Guest.class))//
|
||||
.withLink(new Link("/guests/1")).build();
|
||||
|
||||
String result = mapper.writeValueAsString(resource);
|
||||
|
||||
assertThat(JsonPath.read(result, "$.room.type"), equalTo("suite"));
|
||||
assertThat(JsonPath.read(result, "$.meals[0].type"), equalTo("dinner"));
|
||||
assertThat(JsonPath.<Object> read(result, "$.room.type")).isEqualTo("suite");
|
||||
assertThat(JsonPath.<Object> read(result, "$.meals[0].type")).isEqualTo("dinner");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,13 +39,13 @@ import org.springframework.data.rest.core.mapping.RepositoryResourceMappings;
|
||||
import org.springframework.data.rest.core.support.DefaultSelfLinkProvider;
|
||||
import org.springframework.data.rest.core.support.EntityLookup;
|
||||
import org.springframework.data.rest.core.support.SelfLinkProvider;
|
||||
import org.springframework.data.rest.core.util.Java8PluginRegistry;
|
||||
import org.springframework.data.rest.webmvc.EmbeddedResourcesAssembler;
|
||||
import org.springframework.data.rest.webmvc.jpa.Person;
|
||||
import org.springframework.data.rest.webmvc.jpa.PersonRepository;
|
||||
import org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module.LookupObjectSerializer;
|
||||
import org.springframework.data.rest.webmvc.mapping.Associations;
|
||||
import org.springframework.data.rest.webmvc.mapping.LinkCollector;
|
||||
import org.springframework.data.rest.webmvc.spi.BackendIdConverter;
|
||||
import org.springframework.data.rest.webmvc.spi.BackendIdConverter.DefaultIdConverter;
|
||||
import org.springframework.data.rest.webmvc.support.ExcerptProjector;
|
||||
import org.springframework.data.rest.webmvc.support.PagingAndSortingTemplateVariables;
|
||||
@@ -58,7 +58,6 @@ import org.springframework.hateoas.ResourceProcessor;
|
||||
import org.springframework.hateoas.core.EvoInflectorRelProvider;
|
||||
import org.springframework.hateoas.hal.Jackson2HalModule;
|
||||
import org.springframework.hateoas.mvc.ResourceProcessorInvoker;
|
||||
import org.springframework.plugin.core.OrderAwarePluginRegistry;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
@@ -119,7 +118,7 @@ public class RepositoryTestsConfig {
|
||||
config().getRepositoryDetectionStrategy());
|
||||
EntityLinks entityLinks = new RepositoryEntityLinks(repositories(), mappings, config(),
|
||||
mock(PagingAndSortingTemplateVariables.class),
|
||||
OrderAwarePluginRegistry.<Class<?>, BackendIdConverter> create(Arrays.asList(DefaultIdConverter.INSTANCE)));
|
||||
Java8PluginRegistry.of(Arrays.asList(DefaultIdConverter.INSTANCE)));
|
||||
SelfLinkProvider selfLinkProvider = new DefaultSelfLinkProvider(persistentEntities(), entityLinks,
|
||||
Collections.<EntityLookup<?>> emptyList());
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Method;
|
||||
@@ -53,7 +52,7 @@ public class BackendIdConverterHandlerMethodArgumentResolverIntegrationTests
|
||||
|
||||
Object resolvedId = resolver.resolveArgument(parameter, null, request, null);
|
||||
|
||||
assertThat(resolvedId, is((Object) 5L));
|
||||
assertThat(resolvedId).isEqualTo(5L);
|
||||
}
|
||||
|
||||
static class SampleController {
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.support;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.Matchers.allOf;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -51,7 +53,7 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt
|
||||
Link link = entityLinks.linkToSingleResource(Person.class, 1);
|
||||
|
||||
assertThat(link.getHref(), endsWith("/people/1{?projection}"));
|
||||
assertThat(link.getRel(), is("person"));
|
||||
assertThat(link.getRel()).isEqualTo("person");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -59,9 +61,9 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt
|
||||
|
||||
Link link = entityLinks.linkToCollectionResource(Person.class);
|
||||
|
||||
assertThat(link.isTemplated(), is(true));
|
||||
assertThat(link.getVariableNames(), hasItems("page", "size", "sort"));
|
||||
assertThat(link.getRel(), is("people"));
|
||||
assertThat(link.isTemplated()).isTrue();
|
||||
assertThat(link.getVariableNames()).contains("page", "size", "sort");
|
||||
assertThat(link.getRel()).isEqualTo("people");
|
||||
}
|
||||
|
||||
@Test // DATAREST-221
|
||||
@@ -69,8 +71,8 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt
|
||||
|
||||
Link link = entityLinks.linkToSingleResource(Order.class, 1);
|
||||
|
||||
assertThat(link.isTemplated(), is(true));
|
||||
assertThat(link.getVariableNames(), hasItem(configuration.getProjectionConfiguration().getParameterName()));
|
||||
assertThat(link.isTemplated()).isTrue();
|
||||
assertThat(link.getVariableNames()).contains(configuration.getProjectionConfiguration().getParameterName());
|
||||
}
|
||||
|
||||
@Test // DATAREST-155
|
||||
@@ -83,11 +85,11 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt
|
||||
@Test // DATAREST-317
|
||||
public void adaptsToExistingPageable() {
|
||||
|
||||
Link link = entityLinks.linkToPagedResource(Person.class, new PageRequest(0, 10));
|
||||
Link link = entityLinks.linkToPagedResource(Person.class, PageRequest.of(0, 10));
|
||||
|
||||
assertThat(link.isTemplated(), is(true));
|
||||
assertThat(link.getVariableNames(), hasSize(2));
|
||||
assertThat(link.getVariableNames(), hasItems("sort", "projection"));
|
||||
assertThat(link.isTemplated()).isTrue();
|
||||
assertThat(link.getVariableNames()).hasSize(2);
|
||||
assertThat(link.getVariableNames()).contains("sort", "projection");
|
||||
}
|
||||
|
||||
@Test // DATAREST-467
|
||||
@@ -95,11 +97,11 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt
|
||||
|
||||
Links links = entityLinks.linksToSearchResources(Person.class);
|
||||
|
||||
assertThat(links.hasLink("firstname"), is(true));
|
||||
assertThat(links.hasLink("firstname")).isTrue();
|
||||
|
||||
Link firstnameLink = links.getLink("firstname");
|
||||
assertThat(firstnameLink.isTemplated(), is(true));
|
||||
assertThat(firstnameLink.getVariableNames(), hasItems("page", "size"));
|
||||
assertThat(firstnameLink.isTemplated()).isTrue();
|
||||
assertThat(firstnameLink.getVariableNames()).contains("page", "size");
|
||||
}
|
||||
|
||||
@Test // DATAREST-467
|
||||
@@ -107,20 +109,20 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt
|
||||
|
||||
Link link = entityLinks.linkToSearchResource(Person.class, "firstname");
|
||||
|
||||
assertThat(link, is(notNullValue()));
|
||||
assertThat(link.isTemplated(), is(true));
|
||||
assertThat(link.getVariableNames(), hasItems("firstname", "page", "size"));
|
||||
assertThat(link).isNotNull();
|
||||
assertThat(link.isTemplated()).isTrue();
|
||||
assertThat(link.getVariableNames()).contains("firstname", "page", "size");
|
||||
}
|
||||
|
||||
@Test // DATAREST-467, DATAREST-519
|
||||
public void prepopulatesPaginationInformationForSearchResourceLink() {
|
||||
|
||||
Link link = entityLinks.linkToSearchResource(Person.class, "firstname", new PageRequest(0, 10));
|
||||
Link link = entityLinks.linkToSearchResource(Person.class, "firstname", PageRequest.of(0, 10));
|
||||
|
||||
assertThat(link, is(notNullValue()));
|
||||
assertThat(link.isTemplated(), is(true));
|
||||
assertThat(link.getVariableNames(), hasItem("firstname"));
|
||||
assertThat(link.getVariableNames(), not(hasItems("page", "size")));
|
||||
assertThat(link).isNotNull();
|
||||
assertThat(link.isTemplated()).isTrue();
|
||||
assertThat(link.getVariableNames()).contains("firstname");
|
||||
assertThat(link.getVariableNames()).doesNotContain("page", "size");
|
||||
|
||||
UriComponents components = UriComponentsBuilder.fromUriString(link.getHref()).build();
|
||||
assertThat(components.getQueryParams(), allOf(hasKey("page"), hasKey("size")));
|
||||
@@ -131,19 +133,19 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt
|
||||
|
||||
Link link = entityLinks.linkToSearchResource(Person.class, "lastname");
|
||||
|
||||
assertThat(link.isTemplated(), is(true));
|
||||
assertThat(link.getVariableNames(), hasItems("lastname", "sort"));
|
||||
assertThat(link.isTemplated()).isTrue();
|
||||
assertThat(link.getVariableNames()).contains("lastname", "sort");
|
||||
}
|
||||
|
||||
@Test // DATAREST-467, DATAREST-519
|
||||
public void prepopulatesSortInformationForSearchResourceLink() {
|
||||
|
||||
Link link = entityLinks.linkToSearchResource(Person.class, "lastname", new Sort("firstname"));
|
||||
Link link = entityLinks.linkToSearchResource(Person.class, "lastname", Sort.by("firstname"));
|
||||
|
||||
assertThat(link, is(notNullValue()));
|
||||
assertThat(link.isTemplated(), is(true));
|
||||
assertThat(link.getVariableNames(), hasItem("lastname"));
|
||||
assertThat(link.getVariableNames(), not(hasItems("sort")));
|
||||
assertThat(link).isNotNull();
|
||||
assertThat(link.isTemplated()).isTrue();
|
||||
assertThat(link.getVariableNames()).contains("lastname");
|
||||
assertThat(link.getVariableNames()).doesNotContain("sort");
|
||||
|
||||
UriComponents components = UriComponentsBuilder.fromUriString(link.getHref()).build();
|
||||
assertThat(components.getQueryParams(), hasKey("sort"));
|
||||
@@ -153,7 +155,7 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt
|
||||
public void addsProjectVariableToSearchResourceIfAvailable() {
|
||||
|
||||
for (Link link : entityLinks.linksToSearchResources(Book.class)) {
|
||||
assertThat(link.getVariableNames(), hasItem("projection"));
|
||||
assertThat(link.getVariableNames()).contains("projection");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,14 +18,14 @@ package org.springframework.data.rest.tests.mongodb;
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
|
||||
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface UserRepository extends CrudRepository<User, BigInteger>, QueryDslPredicateExecutor<User> {
|
||||
public interface UserRepository extends CrudRepository<User, BigInteger>, QuerydslPredicateExecutor<User> {
|
||||
|
||||
List<User> findByFirstname(String firstname);
|
||||
|
||||
|
||||
22
spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/tests/mongodb/MongoWebTests.java
Normal file → Executable file
22
spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/tests/mongodb/MongoWebTests.java
Normal file → Executable file
@@ -15,8 +15,8 @@
|
||||
*/
|
||||
package org.springframework.data.rest.tests.mongodb;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.http.HttpHeaders.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
@@ -25,6 +25,7 @@ import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
import org.assertj.core.api.Condition;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -133,11 +134,11 @@ public class MongoWebTests extends CommonWebTests {
|
||||
Link profileSearches = client.discoverUnique(profiles, "search");
|
||||
Link countByTypeLink = client.discoverUnique(profileSearches, "countByType");
|
||||
|
||||
assertThat(countByTypeLink.isTemplated(), is(true));
|
||||
assertThat(countByTypeLink.getVariableNames(), hasItem("type"));
|
||||
assertThat(countByTypeLink.isTemplated()).isTrue();
|
||||
assertThat(countByTypeLink.getVariableNames()).contains("type");
|
||||
|
||||
MockHttpServletResponse response = client.request(countByTypeLink.expand("Twitter"));
|
||||
assertThat(response.getContentAsString(), is("1"));
|
||||
assertThat(response.getContentAsString()).isEqualTo("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -147,10 +148,11 @@ public class MongoWebTests extends CommonWebTests {
|
||||
Link userLink = assertHasContentLinkWithRel("self", client.request(usersLink));
|
||||
|
||||
MockHttpServletResponse response = patchAndGet(userLink,
|
||||
"{\"lastname\" : null, \"address\" : { \"zipCode\" : \"ZIP\"}}", MediaType.APPLICATION_JSON);
|
||||
"{\"lastname\" : null, \"address\" : { \"zipCode\" : \"ZIP\"}}",
|
||||
org.springframework.http.MediaType.APPLICATION_JSON);
|
||||
|
||||
assertThat(JsonPath.read(response.getContentAsString(), "$.lastname"), is(nullValue()));
|
||||
assertThat(JsonPath.read(response.getContentAsString(), "$.address.zipCode"), is((Object) "ZIP"));
|
||||
assertThat(JsonPath.<String> read(response.getContentAsString(), "$.lastname")).isNull();
|
||||
assertThat(JsonPath.<String> read(response.getContentAsString(), "$.address.zipCode")).isEqualTo("ZIP");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -165,8 +167,8 @@ public class MongoWebTests extends CommonWebTests {
|
||||
+ "{ \"op\": \"remove\", \"path\": \"/lastname\" }]", //
|
||||
RestMediaTypes.JSON_PATCH_JSON);
|
||||
|
||||
assertThat(JsonPath.read(response.getContentAsString(), "$.lastname"), is(nullValue()));
|
||||
assertThat(JsonPath.read(response.getContentAsString(), "$.address.zipCode"), is((Object) "ZIP"));
|
||||
assertThat(JsonPath.<String> read(response.getContentAsString(), "$.lastname")).isNull();
|
||||
assertThat(JsonPath.<String> read(response.getContentAsString(), "$.address.zipCode")).isEqualTo("ZIP");
|
||||
}
|
||||
|
||||
@Test // DATAREST-160
|
||||
@@ -204,7 +206,7 @@ public class MongoWebTests extends CommonWebTests {
|
||||
String header = mvc.perform(get("/profiles/{id}", profile.getId())).//
|
||||
andReturn().getResponse().getHeader("Last-Modified");
|
||||
|
||||
assertThat(header, not(isEmptyOrNullString()));
|
||||
assertThat(header).isNot(new Condition<String>(it -> it == null || it.isEmpty(), "Foo"));
|
||||
}
|
||||
|
||||
@Test // DATAREST-482
|
||||
|
||||
@@ -15,15 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Collections;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
import org.mockito.internal.stubbing.answers.ReturnsArgumentAt;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -38,7 +36,6 @@ import org.springframework.data.rest.tests.mongodb.User;
|
||||
import org.springframework.data.rest.webmvc.mapping.Associations;
|
||||
import org.springframework.data.rest.webmvc.support.Projector;
|
||||
import org.springframework.hateoas.EntityLinks;
|
||||
import org.springframework.hateoas.Link;
|
||||
import org.springframework.hateoas.Links;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
|
||||
@@ -62,7 +59,7 @@ public class PersistentEntityResourceAssemblerIntegrationTests extends AbstractC
|
||||
|
||||
Projector projector = mock(Projector.class);
|
||||
|
||||
when(projector.projectExcerpt(anyObject())).thenAnswer(new ReturnsArgumentAt(0));
|
||||
when(projector.projectExcerpt(any())).thenAnswer(new ReturnsArgumentAt(0));
|
||||
|
||||
PersistentEntityResourceAssembler assembler = new PersistentEntityResourceAssembler(entities, projector,
|
||||
associations, new DefaultSelfLinkProvider(entities, entityLinks, Collections.<EntityLookup<?>> emptyList()));
|
||||
@@ -74,8 +71,8 @@ public class PersistentEntityResourceAssemblerIntegrationTests extends AbstractC
|
||||
|
||||
Links links = new Links(resource.getLinks());
|
||||
|
||||
assertThat(links, is(Matchers.<Link> iterableWithSize(2)));
|
||||
assertThat(links.getLink("self").getVariables(), is(Matchers.empty()));
|
||||
assertThat(links.getLink("user").getVariableNames(), is(hasItem("projection")));
|
||||
assertThat(links).hasSize(2);
|
||||
assertThat(links.getLink("self").getVariables()).isEmpty();
|
||||
assertThat(links.getLink("user").getVariableNames()).contains("projection");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -47,13 +46,13 @@ public class RepositoryRestHandlerMappingIntegrationTests extends AbstractContro
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(mockRequest);
|
||||
|
||||
assertThat(chain, is(notNullValue()));
|
||||
assertThat(chain).isNotNull();
|
||||
|
||||
Object handler = chain.getHandler();
|
||||
assertThat(handler, is(instanceOf(HandlerMethod.class)));
|
||||
assertThat(handler).isInstanceOf(HandlerMethod.class);
|
||||
|
||||
HandlerMethod method = (HandlerMethod) handler;
|
||||
assertThat(method.getMethod().getDeclaringClass(), is(typeCompatibleWith(RepositoryEntityController.class)));
|
||||
assertThat(method.getMethod().getName(), is("getCollectionResource"));
|
||||
assertThat(method.getMethod().getDeclaringClass()).isAssignableFrom(RepositoryEntityController.class);
|
||||
assertThat(method.getMethod().getName()).isEqualTo("getCollectionResource");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.data.rest.tests.mongodb.TestUtils.*;
|
||||
|
||||
@@ -29,7 +28,7 @@ import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.data.mapping.context.PersistentEntities;
|
||||
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
|
||||
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
|
||||
@@ -87,8 +86,8 @@ public class JsonPatchHandlerUnitTests {
|
||||
|
||||
User result = handler.applyPatch(asStream(input), user);
|
||||
|
||||
assertThat(result.lastname, is(nullValue()));
|
||||
assertThat(result.address.zipCode, is("ZIP"));
|
||||
assertThat(result.lastname).isNull();
|
||||
assertThat(result.address.zipCode).isEqualTo("ZIP");
|
||||
}
|
||||
|
||||
@Test // DATAREST-348
|
||||
@@ -98,8 +97,8 @@ public class JsonPatchHandlerUnitTests {
|
||||
|
||||
User result = handler.applyMergePatch(asStream(input), user);
|
||||
|
||||
assertThat(result.lastname, is(nullValue()));
|
||||
assertThat(result.address.zipCode, is("ZIP"));
|
||||
assertThat(result.lastname).isNull();
|
||||
assertThat(result.address.zipCode).isEqualTo("ZIP");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -120,8 +119,8 @@ public class JsonPatchHandlerUnitTests {
|
||||
|
||||
handler.applyPatch(asStream(input), user);
|
||||
|
||||
assertThat(user.colleagues, hasSize(1));
|
||||
assertThat(user.colleagues.get(0).firstname, is(christoph.firstname));
|
||||
assertThat(user.colleagues).hasSize(1);
|
||||
assertThat(user.colleagues.get(0).firstname).isEqualTo(christoph.firstname);
|
||||
}
|
||||
|
||||
@Test // DATAREST-609
|
||||
|
||||
@@ -15,22 +15,22 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
|
||||
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
|
||||
import org.springframework.data.querydsl.QuerydslRepositoryInvokerAdapter;
|
||||
import org.springframework.data.querydsl.SimpleEntityPathResolver;
|
||||
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
|
||||
@@ -70,7 +70,7 @@ public class QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUn
|
||||
public void setUp() {
|
||||
|
||||
QuerydslBindingsFactory factory = new QuerydslBindingsFactory(SimpleEntityPathResolver.INSTANCE);
|
||||
ReflectionTestUtils.setField(factory, "repositories", repositories);
|
||||
ReflectionTestUtils.setField(factory, "repositories", Optional.of(repositories));
|
||||
QuerydslPredicateBuilder builder = new QuerydslPredicateBuilder(new DefaultConversionService(),
|
||||
factory.getEntityPathResolver());
|
||||
|
||||
@@ -84,39 +84,38 @@ public class QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUn
|
||||
public void returnsInvokerIfRepositoryIsNotQuerydslAware() {
|
||||
|
||||
ReceiptRepository repository = mock(ReceiptRepository.class);
|
||||
when(repositories.getRepositoryFor(Receipt.class)).thenReturn(repository);
|
||||
when(repositories.getRepositoryFor(Receipt.class)).thenReturn(Optional.of(repository));
|
||||
|
||||
RepositoryInvoker result = resolver.postProcess(parameter, invoker, Receipt.class, NO_PARAMETERS);
|
||||
|
||||
assertThat(result, is(invoker));
|
||||
assertThat(result).isEqualTo(invoker);
|
||||
}
|
||||
|
||||
@Test // DATAREST-616
|
||||
public void wrapsInvokerInQuerydslAdapter() {
|
||||
|
||||
Object repository = mock(QuerydslUserRepository.class);
|
||||
when(repositories.getRepositoryFor(User.class)).thenReturn(repository);
|
||||
when(repositories.getRepositoryFor(User.class)).thenReturn(Optional.of(repository));
|
||||
|
||||
RepositoryInvoker result = resolver.postProcess(parameter, invoker, User.class, NO_PARAMETERS);
|
||||
|
||||
assertThat(result, is(instanceOf(QuerydslRepositoryInvokerAdapter.class)));
|
||||
assertThat(result).isInstanceOf(QuerydslRepositoryInvokerAdapter.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-616
|
||||
public void invokesCustomizationOnRepositoryIfItImplementsCustomizer() {
|
||||
|
||||
QuerydslCustomizingUserRepository repository = mock(QuerydslCustomizingUserRepository.class);
|
||||
when(repositories.hasRepositoryFor(User.class)).thenReturn(true);
|
||||
when(repositories.getRepositoryFor(User.class)).thenReturn(repository);
|
||||
when(repositories.getRepositoryFor(User.class)).thenReturn(Optional.of(repository));
|
||||
|
||||
RepositoryInvoker result = resolver.postProcess(parameter, invoker, User.class, NO_PARAMETERS);
|
||||
|
||||
assertThat(result, is(instanceOf(QuerydslRepositoryInvokerAdapter.class)));
|
||||
assertThat(result).isInstanceOf(QuerydslRepositoryInvokerAdapter.class);
|
||||
verify(repository, times(1)).customize(Mockito.any(QuerydslBindings.class), Mockito.any(QUser.class));
|
||||
}
|
||||
|
||||
interface QuerydslUserRepository extends QueryDslPredicateExecutor<User> {}
|
||||
interface QuerydslUserRepository extends QuerydslPredicateExecutor<User> {}
|
||||
|
||||
interface QuerydslCustomizingUserRepository
|
||||
extends QueryDslPredicateExecutor<User>, QuerydslBinderCustomizer<QUser> {}
|
||||
extends QuerydslPredicateExecutor<User>, QuerydslBinderCustomizer<QUser> {}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.json;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
@@ -113,12 +114,12 @@ public class PersistentEntitySerializationTests {
|
||||
|
||||
String result = mapper.writeValueAsString(persistentEntityResource);
|
||||
|
||||
assertThat(JsonPath.read(result, "$._embedded.users[*].address"), is(notNullValue()));
|
||||
assertThat(JsonPath.<Object> read(result, "$._embedded.users[*].address")).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-654
|
||||
public void deserializesTranslatedEnumProperty() throws Exception {
|
||||
assertThat(mapper.readValue("{ \"gender\" : \"Male\" }", User.class).gender, is(Gender.MALE));
|
||||
assertThat(mapper.readValue("{ \"gender\" : \"Male\" }", User.class).gender).isEqualTo(Gender.MALE);
|
||||
}
|
||||
|
||||
@Test // DATAREST-864
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.json;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -179,7 +180,7 @@ public class PersistentEntityToJsonSchemaConverterUnitTests {
|
||||
try {
|
||||
assertThat(constraint.description, JsonPath.read(writeSchemaFor, constraint.selector), constraint.matcher);
|
||||
} catch (PathNotFoundException e) {
|
||||
assertThat(constraint.matcher.matches(null), is(true));
|
||||
assertThat(constraint.matcher.matches(null)).isTrue();
|
||||
} catch (RuntimeException e) {
|
||||
assertThat(e, constraint.matcher);
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.rest.webmvc.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@@ -61,6 +60,6 @@ public class RepositoryLinkBuildUnitTests {
|
||||
new BaseUri(baseUri));
|
||||
Link link = builder.withSelfRel();
|
||||
|
||||
assertThat(link.getHref(), is(expectedUri));
|
||||
assertThat(link.getHref()).isEqualTo(expectedUri);
|
||||
}
|
||||
}
|
||||
|
||||
0
spring-data-rest-tests/spring-data-rest-tests-solr/src/test/java/org/springframework/data/rest/webmvc/solr/SolrWebTests.java
Normal file → Executable file
0
spring-data-rest-tests/spring-data-rest-tests-solr/src/test/java/org/springframework/data/rest/webmvc/solr/SolrWebTests.java
Normal file → Executable file
@@ -4,8 +4,7 @@
|
||||
<fieldType name="string" class="solr.StrField" />
|
||||
</types>
|
||||
<fields>
|
||||
<field name="id" type="string" indexed="true" stored="true"
|
||||
required="true" />
|
||||
<field name="id" type="string" indexed="true" stored="true" required="true" />
|
||||
<field name="name" type="string" indexed="true" stored="true" />
|
||||
<field name="cat" type="string" indexed="true" stored="true" multiValued="true" />
|
||||
</fields>
|
||||
|
||||
@@ -16,12 +16,14 @@
|
||||
package org.springframework.data.rest.webmvc;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.hateoas.Resource;
|
||||
import org.springframework.hateoas.ResourceSupport;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
@@ -31,6 +33,18 @@ public class ControllerUtils {
|
||||
|
||||
public static final Iterable<Resource<?>> EMPTY_RESOURCE_LIST = Collections.emptyList();
|
||||
|
||||
public static <R extends ResourceSupport> ResponseEntity<ResourceSupport> toResponseEntity(HttpStatus status,
|
||||
HttpHeaders headers, Optional<R> resource) {
|
||||
|
||||
HttpHeaders hdrs = new HttpHeaders();
|
||||
|
||||
if (headers != null) {
|
||||
hdrs.putAll(headers);
|
||||
}
|
||||
|
||||
return new ResponseEntity<ResourceSupport>(resource.orElse(null), hdrs, status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a resource as a {@link ResourceEntity} and attach given headers and status.
|
||||
*
|
||||
@@ -43,13 +57,11 @@ public class ControllerUtils {
|
||||
public static <R extends ResourceSupport> ResponseEntity<ResourceSupport> toResponseEntity(HttpStatus status,
|
||||
HttpHeaders headers, R resource) {
|
||||
|
||||
HttpHeaders hdrs = new HttpHeaders();
|
||||
Assert.notNull(status, "Http status must not be null!");
|
||||
Assert.notNull(headers, "Http headers must not be null!");
|
||||
Assert.notNull(resource, "Payload must not be null!");
|
||||
|
||||
if (headers != null) {
|
||||
hdrs.putAll(headers);
|
||||
}
|
||||
|
||||
return new ResponseEntity<ResourceSupport>(resource, hdrs, status);
|
||||
return toResponseEntity(status, headers, Optional.of(resource));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,7 +71,7 @@ public class ControllerUtils {
|
||||
* @return
|
||||
*/
|
||||
public static ResponseEntity<ResourceSupport> toEmptyResponse(HttpStatus status) {
|
||||
return toEmptyResponse(status, null);
|
||||
return toEmptyResponse(status, new HttpHeaders());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -70,6 +82,6 @@ public class ControllerUtils {
|
||||
* @return
|
||||
*/
|
||||
public static ResponseEntity<ResourceSupport> toEmptyResponse(HttpStatus status, HttpHeaders headers) {
|
||||
return toResponseEntity(status, headers, null);
|
||||
return toResponseEntity(status, headers, Optional.empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2016 the original author or authors.
|
||||
* Copyright 2016-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -22,7 +22,6 @@ import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.mapping.Association;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.PersistentPropertyAccessor;
|
||||
@@ -57,42 +56,31 @@ public class EmbeddedResourcesAssembler {
|
||||
|
||||
Assert.notNull(instance, "Entity instance must not be null!");
|
||||
|
||||
PersistentEntity<?, ?> entity = entities.getPersistentEntity(instance.getClass());
|
||||
PersistentEntity<?, ?> entity = entities.getRequiredPersistentEntity(instance.getClass());
|
||||
|
||||
final List<EmbeddedWrapper> associationProjections = new ArrayList<EmbeddedWrapper>();
|
||||
final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(instance);
|
||||
final ResourceMetadata metadata = associations.getMetadataFor(entity.getType());
|
||||
|
||||
entity.doWithAssociations(new SimpleAssociationHandler() {
|
||||
entity.doWithAssociations((SimpleAssociationHandler) association -> {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mapping.SimpleAssociationHandler#doWithAssociation(org.springframework.data.mapping.Association)
|
||||
*/
|
||||
@Override
|
||||
public void doWithAssociation(Association<? extends PersistentProperty<?>> association) {
|
||||
PersistentProperty<?> property = association.getInverse();
|
||||
|
||||
PersistentProperty<?> property = association.getInverse();
|
||||
if (!associations.isLinkableAssociation(property)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!associations.isLinkableAssociation(property)) {
|
||||
return;
|
||||
}
|
||||
if (!projector.hasExcerptProjection(property.getActualType())) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!projector.hasExcerptProjection(property.getActualType())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object value = accessor.getProperty(association.getInverse());
|
||||
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
accessor.getProperty(association.getInverse()).ifPresent(it -> {
|
||||
|
||||
String rel = metadata.getMappingFor(property).getRel();
|
||||
|
||||
if (value instanceof Collection) {
|
||||
if (it instanceof Collection) {
|
||||
|
||||
Collection<?> collection = (Collection<?>) value;
|
||||
Collection<?> collection = (Collection<?>) it;
|
||||
|
||||
if (collection.isEmpty()) {
|
||||
return;
|
||||
@@ -109,9 +97,9 @@ public class EmbeddedResourcesAssembler {
|
||||
associationProjections.add(wrappers.wrap(nestedCollection, rel));
|
||||
|
||||
} else {
|
||||
associationProjections.add(wrappers.wrap(projector.projectExcerpt(value), rel));
|
||||
associationProjections.add(wrappers.wrap(projector.projectExcerpt(it), rel));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return associationProjections;
|
||||
|
||||
@@ -18,10 +18,15 @@ package org.springframework.data.rest.webmvc;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.core.convert.support.ConfigurableConversionService;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
import org.springframework.data.auditing.AuditableBeanWrapper;
|
||||
import org.springframework.data.auditing.AuditableBeanWrapperFactory;
|
||||
import org.springframework.data.convert.Jsr310Converters;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.rest.webmvc.support.ETag;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
@@ -38,6 +43,11 @@ import org.springframework.util.Assert;
|
||||
public class HttpHeadersPreparer {
|
||||
|
||||
private final @NonNull AuditableBeanWrapperFactory auditableBeanWrapperFactory;
|
||||
private final ConfigurableConversionService conversionService = new DefaultConversionService();
|
||||
|
||||
{
|
||||
Jsr310Converters.getConvertersToRegister().forEach(conversionService::addConverter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default headers to be returned for the given {@link PersistentEntityResource}. Will set {@link ETag}
|
||||
@@ -46,8 +56,11 @@ public class HttpHeadersPreparer {
|
||||
* @param resource can be {@literal null}.
|
||||
* @return
|
||||
*/
|
||||
public HttpHeaders prepareHeaders(PersistentEntityResource resource) {
|
||||
return resource == null ? new HttpHeaders() : prepareHeaders(resource.getPersistentEntity(), resource.getContent());
|
||||
public HttpHeaders prepareHeaders(Optional<PersistentEntityResource> resource) {
|
||||
|
||||
return resource//
|
||||
.map(it -> prepareHeaders(it.getPersistentEntity(), it.getContent()))//
|
||||
.orElseGet(() -> new HttpHeaders());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,17 +77,7 @@ public class HttpHeadersPreparer {
|
||||
HttpHeaders headers = ETag.from(entity, value).addTo(new HttpHeaders());
|
||||
|
||||
// Add Last-Modified
|
||||
AuditableBeanWrapper wrapper = getAuditableBeanWrapper(value);
|
||||
|
||||
if (wrapper == null) {
|
||||
return headers;
|
||||
}
|
||||
|
||||
Calendar lastModifiedDate = wrapper.getLastModifiedDate();
|
||||
|
||||
if (lastModifiedDate != null) {
|
||||
headers.setLastModified(lastModifiedDate.getTimeInMillis());
|
||||
}
|
||||
getLastModifiedInMilliseconds(value).ifPresent(it -> headers.setLastModified(it));
|
||||
|
||||
return headers;
|
||||
}
|
||||
@@ -95,10 +98,9 @@ public class HttpHeadersPreparer {
|
||||
return false;
|
||||
}
|
||||
|
||||
AuditableBeanWrapper wrapper = auditableBeanWrapperFactory.getBeanWrapperFor(source);
|
||||
long current = wrapper.getLastModifiedDate().getTimeInMillis() / 1000 * 1000;
|
||||
|
||||
return current <= headers.getIfModifiedSince();
|
||||
return getLastModifiedInMilliseconds(source)//
|
||||
.map(it -> it / 1000 * 1000 <= headers.getIfModifiedSince())//
|
||||
.orElse(true);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -107,7 +109,16 @@ public class HttpHeadersPreparer {
|
||||
* @param source can be {@literal null}.
|
||||
* @return
|
||||
*/
|
||||
private AuditableBeanWrapper getAuditableBeanWrapper(Object source) {
|
||||
private Optional<AuditableBeanWrapper> getAuditableBeanWrapper(Object source) {
|
||||
return auditableBeanWrapperFactory.getBeanWrapperFor(source);
|
||||
}
|
||||
|
||||
private Optional<Long> getLastModifiedInMilliseconds(Object object) {
|
||||
|
||||
return getAuditableBeanWrapper(object)//
|
||||
.flatMap(it -> it.getLastModifiedDate())//
|
||||
.map(it -> conversionService.convert(it, Date.class))//
|
||||
.map(it -> conversionService.convert(it, Instant.class))//
|
||||
.map(it -> it.toEpochMilli());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ public class PersistentEntityResourceAssembler implements ResourceAssembler<Obje
|
||||
|
||||
private Builder wrap(Object instance, Object source) {
|
||||
|
||||
PersistentEntity<?, ?> entity = entities.getPersistentEntity(source.getClass());
|
||||
PersistentEntity<?, ?> entity = entities.getRequiredPersistentEntity(source.getClass());
|
||||
|
||||
return PersistentEntityResource.build(instance, entity).//
|
||||
withEmbedded(getEmbeddedResources(source)).//
|
||||
|
||||
@@ -22,6 +22,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
@@ -44,7 +45,6 @@ import org.springframework.data.rest.core.mapping.ResourceMetadata;
|
||||
import org.springframework.data.rest.core.mapping.ResourceType;
|
||||
import org.springframework.data.rest.core.mapping.SearchResourceMappings;
|
||||
import org.springframework.data.rest.core.mapping.SupportedHttpMethods;
|
||||
import org.springframework.data.rest.core.util.Supplier;
|
||||
import org.springframework.data.rest.webmvc.support.BackendId;
|
||||
import org.springframework.data.rest.webmvc.support.DefaultedPageable;
|
||||
import org.springframework.data.rest.webmvc.support.ETag;
|
||||
@@ -305,18 +305,16 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem
|
||||
public ResponseEntity<?> headForItemResource(RootResourceInformation resourceInformation, @BackendId Serializable id,
|
||||
PersistentEntityResourceAssembler assembler) throws HttpRequestMethodNotSupportedException {
|
||||
|
||||
Object domainObject = getItemResource(resourceInformation, id);
|
||||
return getItemResource(resourceInformation, id).map(it -> {
|
||||
|
||||
if (domainObject == null) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
Links links = new Links(assembler.toResource(it).getLinks());
|
||||
|
||||
Links links = new Links(assembler.toResource(domainObject).getLinks());
|
||||
HttpHeaders headers = headersPreparer.prepareHeaders(resourceInformation.getPersistentEntity(), it);
|
||||
headers.add(LINK_HEADER, links.toString());
|
||||
|
||||
HttpHeaders headers = headersPreparer.prepareHeaders(resourceInformation.getPersistentEntity(), domainObject);
|
||||
headers.add(LINK_HEADER, links.toString());
|
||||
return new ResponseEntity<Object>(headers, HttpStatus.NO_CONTENT);
|
||||
|
||||
return new ResponseEntity<Object>(headers, HttpStatus.NO_CONTENT);
|
||||
}).orElseThrow(() -> new ResourceNotFoundException());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -332,21 +330,14 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem
|
||||
@BackendId Serializable id, final PersistentEntityResourceAssembler assembler, @RequestHeader HttpHeaders headers)
|
||||
throws HttpRequestMethodNotSupportedException {
|
||||
|
||||
final Object domainObj = getItemResource(resourceInformation, id);
|
||||
return getItemResource(resourceInformation, id).map(it -> {
|
||||
|
||||
if (domainObj == null) {
|
||||
return new ResponseEntity<Resource<?>>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
|
||||
|
||||
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
|
||||
return resourceStatus.getStatusAndHeaders(headers, it, entity).toResponseEntity(//
|
||||
() -> assembler.toFullResource(it));
|
||||
|
||||
return resourceStatus.getStatusAndHeaders(headers, domainObj, entity).toResponseEntity(//
|
||||
new Supplier<PersistentEntityResource>() {
|
||||
@Override
|
||||
public PersistentEntityResource get() {
|
||||
return assembler.toFullResource(domainObj);
|
||||
}
|
||||
});
|
||||
}).orElseGet(() -> new ResponseEntity<Resource<?>>(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -425,21 +416,21 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem
|
||||
resourceInformation.verifySupportedMethod(HttpMethod.DELETE, ResourceType.ITEM);
|
||||
|
||||
RepositoryInvoker invoker = resourceInformation.getInvoker();
|
||||
Object domainObj = invoker.invokeFindOne(id);
|
||||
Optional<Object> domainObj = invoker.invokeFindOne(id);
|
||||
|
||||
if (domainObj == null) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
return domainObj.map(it -> {
|
||||
|
||||
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
|
||||
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
|
||||
|
||||
eTag.verify(entity, domainObj);
|
||||
eTag.verify(entity, it);
|
||||
|
||||
publisher.publishEvent(new BeforeDeleteEvent(domainObj));
|
||||
invoker.invokeDelete((Serializable) entity.getIdentifierAccessor(domainObj).getIdentifier());
|
||||
publisher.publishEvent(new AfterDeleteEvent(domainObj));
|
||||
publisher.publishEvent(new BeforeDeleteEvent(it));
|
||||
invoker.invokeDelete((Serializable) entity.getIdentifierAccessor(it).getIdentifier().orElse(null));
|
||||
publisher.publishEvent(new AfterDeleteEvent(it));
|
||||
|
||||
return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
|
||||
return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
|
||||
|
||||
}).orElseThrow(() -> new ResourceNotFoundException());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -458,7 +449,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem
|
||||
publisher.publishEvent(new AfterSaveEvent(obj));
|
||||
|
||||
PersistentEntityResource resource = assembler.toFullResource(obj);
|
||||
HttpHeaders headers = headersPreparer.prepareHeaders(resource);
|
||||
HttpHeaders headers = headersPreparer.prepareHeaders(Optional.of(resource));
|
||||
|
||||
if (PUT.equals(httpMethod)) {
|
||||
addLocationHeader(headers, assembler, obj);
|
||||
@@ -485,7 +476,8 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem
|
||||
Object savedObject = invoker.invokeSave(domainObject);
|
||||
publisher.publishEvent(new AfterCreateEvent(savedObject));
|
||||
|
||||
PersistentEntityResource resource = returnBody ? assembler.toFullResource(savedObject) : null;
|
||||
Optional<PersistentEntityResource> resource = Optional
|
||||
.ofNullable(returnBody ? assembler.toFullResource(savedObject) : null);
|
||||
|
||||
HttpHeaders headers = headersPreparer.prepareHeaders(resource);
|
||||
addLocationHeader(headers, assembler, savedObject);
|
||||
@@ -516,7 +508,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem
|
||||
* @throws HttpRequestMethodNotSupportedException
|
||||
* @throws {@link ResourceNotFoundException}
|
||||
*/
|
||||
private Object getItemResource(RootResourceInformation resourceInformation, Serializable id)
|
||||
private Optional<Object> getItemResource(RootResourceInformation resourceInformation, Serializable id)
|
||||
throws HttpRequestMethodNotSupportedException, ResourceNotFoundException {
|
||||
|
||||
resourceInformation.verifySupportedMethod(HttpMethod.GET, ResourceType.ITEM);
|
||||
|
||||
@@ -20,6 +20,9 @@ import static org.springframework.data.rest.webmvc.RestMediaTypes.*;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.*;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -30,6 +33,8 @@ import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
@@ -49,7 +54,6 @@ import org.springframework.data.rest.core.event.BeforeLinkSaveEvent;
|
||||
import org.springframework.data.rest.core.mapping.PropertyAwareResourceMapping;
|
||||
import org.springframework.data.rest.core.mapping.ResourceMapping;
|
||||
import org.springframework.data.rest.core.mapping.ResourceMetadata;
|
||||
import org.springframework.data.rest.core.util.Function;
|
||||
import org.springframework.data.rest.webmvc.support.BackendId;
|
||||
import org.springframework.data.web.PagedResourcesAssembler;
|
||||
import org.springframework.hateoas.Link;
|
||||
@@ -62,7 +66,7 @@ import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -111,72 +115,55 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
|
||||
Function<ReferencedProperty, ResourceSupport> handler = new Function<ReferencedProperty, ResourceSupport>() {
|
||||
Function<ReferencedProperty, ResourceSupport> handler = prop -> prop.propertyValue.map(it -> {
|
||||
|
||||
@Override
|
||||
public ResourceSupport apply(ReferencedProperty prop) {
|
||||
if (prop.property.isCollectionLike()) {
|
||||
|
||||
if (null == prop.propertyValue) {
|
||||
throw new ResourceNotFoundException();
|
||||
return toResources((Iterable<?>) it, assembler, prop.propertyType, null);
|
||||
|
||||
} else if (prop.property.isMap()) {
|
||||
|
||||
Map<Object, Resource<?>> resources = new HashMap<Object, Resource<?>>();
|
||||
|
||||
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) it).entrySet()) {
|
||||
resources.put(entry.getKey(), assembler.toResource(entry.getValue()));
|
||||
}
|
||||
|
||||
if (prop.property.isCollectionLike()) {
|
||||
return new Resource<Object>(resources);
|
||||
|
||||
return toResources((Iterable<?>) prop.propertyValue, assembler, prop.propertyType, null);
|
||||
} else {
|
||||
|
||||
} else if (prop.property.isMap()) {
|
||||
|
||||
Map<Object, Resource<?>> resources = new HashMap<Object, Resource<?>>();
|
||||
|
||||
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) prop.propertyValue).entrySet()) {
|
||||
resources.put(entry.getKey(), assembler.toResource(entry.getValue()));
|
||||
}
|
||||
|
||||
return new Resource<Object>(resources);
|
||||
|
||||
} else {
|
||||
|
||||
PersistentEntityResource resource = assembler.toResource(prop.propertyValue);
|
||||
headers.set("Content-Location", resource.getId().getHref());
|
||||
return resource;
|
||||
}
|
||||
PersistentEntityResource resource = assembler.toResource(it);
|
||||
headers.set("Content-Location", resource.getId().getHref());
|
||||
return resource;
|
||||
}
|
||||
};
|
||||
|
||||
ResourceSupport responseResource = doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET);
|
||||
return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, responseResource);
|
||||
}).orElseThrow(() -> new ResourceNotFoundException());
|
||||
|
||||
return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, //
|
||||
doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET));
|
||||
}
|
||||
|
||||
@RequestMapping(value = BASE_MAPPING, method = DELETE)
|
||||
public ResponseEntity<? extends ResourceSupport> deletePropertyReference(final RootResourceInformation repoRequest,
|
||||
@BackendId Serializable id, @PathVariable String property) throws Exception {
|
||||
|
||||
final RepositoryInvoker repoMethodInvoker = repoRequest.getInvoker();
|
||||
Function<ReferencedProperty, ResourceSupport> handler = prop -> prop.propertyValue.map(it -> {
|
||||
|
||||
Function<ReferencedProperty, ResourceSupport> handler = new Function<ReferencedProperty, ResourceSupport>() {
|
||||
|
||||
@Override
|
||||
public Resource<?> apply(ReferencedProperty prop) throws HttpRequestMethodNotSupportedException {
|
||||
|
||||
if (null == prop.propertyValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (prop.property.isCollectionLike()) {
|
||||
throw new HttpRequestMethodNotSupportedException("DELETE");
|
||||
} else if (prop.property.isMap()) {
|
||||
throw new HttpRequestMethodNotSupportedException("DELETE");
|
||||
} else {
|
||||
prop.accessor.setProperty(prop.property, null);
|
||||
}
|
||||
|
||||
publisher.publishEvent(new BeforeLinkDeleteEvent(prop.accessor.getBean(), prop.propertyValue));
|
||||
Object result = repoMethodInvoker.invokeSave(prop.accessor.getBean());
|
||||
publisher.publishEvent(new AfterLinkDeleteEvent(result, prop.propertyValue));
|
||||
|
||||
return null;
|
||||
if (prop.property.isCollectionLike() || prop.property.isMap()) {
|
||||
throw HttpRequestMethodNotSupportedException.forRejectedMethod(HttpMethod.DELETE)
|
||||
.withAllowedMethods(HttpMethod.GET, HttpMethod.HEAD);
|
||||
} else {
|
||||
prop.wipeValue();
|
||||
}
|
||||
};
|
||||
|
||||
publisher.publishEvent(new BeforeLinkDeleteEvent(prop.accessor.getBean(), prop.propertyValue));
|
||||
Object result = repoRequest.getInvoker().invokeSave(prop.accessor.getBean());
|
||||
publisher.publishEvent(new AfterLinkDeleteEvent(result, prop.propertyValue));
|
||||
|
||||
return (ResourceSupport) null;
|
||||
|
||||
}).orElse(null);
|
||||
|
||||
doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.DELETE);
|
||||
|
||||
@@ -190,53 +177,51 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
|
||||
Function<ReferencedProperty, ResourceSupport> handler = new Function<ReferencedProperty, ResourceSupport>() {
|
||||
Function<ReferencedProperty, ResourceSupport> handler = prop -> prop.propertyValue.map(it -> {
|
||||
|
||||
@Override
|
||||
public ResourceSupport apply(ReferencedProperty prop) {
|
||||
if (prop.property.isCollectionLike()) {
|
||||
|
||||
if (null == prop.propertyValue) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
if (prop.property.isCollectionLike()) {
|
||||
for (Object obj : (Iterable<?>) prop.propertyValue) {
|
||||
for (Object obj : (Iterable<?>) it) {
|
||||
|
||||
IdentifierAccessor accessor = prop.entity.getIdentifierAccessor(obj);
|
||||
if (propertyId.equals(accessor.getIdentifier().toString())) {
|
||||
IdentifierAccessor accessor1 = prop.entity.getIdentifierAccessor(obj);
|
||||
if (propertyId.equals(accessor1.getIdentifier().toString())) {
|
||||
|
||||
PersistentEntityResource resource = assembler.toResource(obj);
|
||||
headers.set("Content-Location", resource.getId().getHref());
|
||||
return resource;
|
||||
}
|
||||
PersistentEntityResource resource1 = assembler.toResource(obj);
|
||||
headers.set("Content-Location", resource1.getId().getHref());
|
||||
return resource1;
|
||||
}
|
||||
} else if (prop.property.isMap()) {
|
||||
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) prop.propertyValue).entrySet()) {
|
||||
|
||||
IdentifierAccessor accessor = prop.entity.getIdentifierAccessor(entry.getValue());
|
||||
if (propertyId.equals(accessor.getIdentifier().toString())) {
|
||||
|
||||
PersistentEntityResource resource = assembler.toResource(entry.getValue());
|
||||
headers.set("Content-Location", resource.getId().getHref());
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return new Resource<Object>(prop.propertyValue);
|
||||
}
|
||||
|
||||
throw new ResourceNotFoundException();
|
||||
} else if (prop.property.isMap()) {
|
||||
|
||||
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) it).entrySet()) {
|
||||
|
||||
IdentifierAccessor accessor2 = prop.entity.getIdentifierAccessor(entry.getValue());
|
||||
if (propertyId.equals(accessor2.getIdentifier().toString())) {
|
||||
|
||||
PersistentEntityResource resource2 = assembler.toResource(entry.getValue());
|
||||
headers.set("Content-Location", resource2.getId().getHref());
|
||||
return resource2;
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
return new Resource<Object>(prop.propertyValue);
|
||||
}
|
||||
};
|
||||
|
||||
ResourceSupport responseResource = doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET);
|
||||
return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, responseResource);
|
||||
throw new ResourceNotFoundException();
|
||||
|
||||
}).orElseThrow(() -> new ResourceNotFoundException());
|
||||
|
||||
return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, //
|
||||
doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET));
|
||||
}
|
||||
|
||||
@RequestMapping(value = BASE_MAPPING, method = GET,
|
||||
produces = { SPRING_DATA_COMPACT_JSON_VALUE, TEXT_URI_LIST_VALUE })
|
||||
public ResponseEntity<ResourceSupport> followPropertyReferenceCompact(RootResourceInformation repoRequest,
|
||||
@BackendId Serializable id, @PathVariable String property, PersistentEntityResourceAssembler assembler)
|
||||
throws Exception {
|
||||
throws Exception {
|
||||
|
||||
ResponseEntity<ResourceSupport> response = followPropertyReference(repoRequest, id, property, assembler);
|
||||
|
||||
@@ -245,7 +230,7 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
}
|
||||
|
||||
ResourceMetadata repoMapping = repoRequest.getResourceMetadata();
|
||||
PersistentProperty<?> persistentProp = repoRequest.getPersistentEntity().getPersistentProperty(property);
|
||||
PersistentProperty<?> persistentProp = repoRequest.getPersistentEntity().getRequiredPersistentProperty(property);
|
||||
ResourceMapping propertyMapping = repoMapping.getMappingFor(persistentProp);
|
||||
|
||||
ResourceSupport resource = response.getBody();
|
||||
@@ -291,60 +276,59 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
final Resources<Object> source = incoming == null ? new Resources<Object>(Collections.emptyList()) : incoming;
|
||||
final RepositoryInvoker invoker = resourceInformation.getInvoker();
|
||||
|
||||
Function<ReferencedProperty, ResourceSupport> handler = new Function<ReferencedProperty, ResourceSupport>() {
|
||||
Function<ReferencedProperty, ResourceSupport> handler = prop -> {
|
||||
|
||||
@Override
|
||||
public ResourceSupport apply(ReferencedProperty prop) throws HttpRequestMethodNotSupportedException {
|
||||
Class<?> propertyType = prop.property.getType();
|
||||
|
||||
Class<?> propertyType = prop.property.getType();
|
||||
if (prop.property.isCollectionLike()) {
|
||||
|
||||
if (prop.property.isCollectionLike()) {
|
||||
Collection<Object> collection = AUGMENTING_METHODS.contains(requestMethod)
|
||||
? (Collection<Object>) prop.propertyValue.orElse(null)
|
||||
: CollectionFactory.createCollection(propertyType, 0);
|
||||
|
||||
Collection<Object> collection = AUGMENTING_METHODS.contains(requestMethod)
|
||||
? (Collection<Object>) prop.propertyValue : CollectionFactory.createCollection(propertyType, 0);
|
||||
|
||||
// Add to the existing collection
|
||||
for (Link l : source.getLinks()) {
|
||||
collection.add(loadPropertyValue(prop.propertyType, l));
|
||||
}
|
||||
|
||||
prop.accessor.setProperty(prop.property, collection);
|
||||
|
||||
} else if (prop.property.isMap()) {
|
||||
|
||||
Map<String, Object> map = AUGMENTING_METHODS.contains(requestMethod)
|
||||
? (Map<String, Object>) prop.propertyValue
|
||||
: CollectionFactory.<String, Object> createMap(propertyType, 0);
|
||||
|
||||
// Add to the existing collection
|
||||
for (Link l : source.getLinks()) {
|
||||
map.put(l.getRel(), loadPropertyValue(prop.propertyType, l));
|
||||
}
|
||||
|
||||
prop.accessor.setProperty(prop.property, map);
|
||||
|
||||
} else {
|
||||
|
||||
if (HttpMethod.PATCH.equals(requestMethod)) {
|
||||
throw new HttpRequestMethodNotSupportedException(HttpMethod.PATCH.name(), new String[] { "PATCH" },
|
||||
"Cannot PATCH a reference to this singular property since the property type is not a List or a Map.");
|
||||
}
|
||||
|
||||
if (source.getLinks().size() != 1) {
|
||||
throw new IllegalArgumentException(
|
||||
"Must send only 1 link to update a property reference that isn't a List or a Map.");
|
||||
}
|
||||
|
||||
Object propVal = loadPropertyValue(prop.propertyType, source.getLinks().get(0));
|
||||
prop.accessor.setProperty(prop.property, propVal);
|
||||
// Add to the existing collection
|
||||
for (Link l1 : source.getLinks()) {
|
||||
collection.add(loadPropertyValue(prop.propertyType, l1).orElse(null));
|
||||
}
|
||||
|
||||
publisher.publishEvent(new BeforeLinkSaveEvent(prop.accessor.getBean(), prop.propertyValue));
|
||||
Object result = invoker.invokeSave(prop.accessor.getBean());
|
||||
publisher.publishEvent(new AfterLinkSaveEvent(result, prop.propertyValue));
|
||||
prop.accessor.setProperty(prop.property, Optional.of(collection));
|
||||
|
||||
return null;
|
||||
} else if (prop.property.isMap()) {
|
||||
|
||||
Map<String, Object> map = AUGMENTING_METHODS.contains(requestMethod)
|
||||
? (Map<String, Object>) prop.propertyValue.orElse(null)
|
||||
: CollectionFactory.<String, Object> createMap(propertyType, 0);
|
||||
|
||||
// Add to the existing collection
|
||||
for (Link l2 : source.getLinks()) {
|
||||
map.put(l2.getRel(), loadPropertyValue(prop.propertyType, l2).orElse(null));
|
||||
}
|
||||
|
||||
prop.accessor.setProperty(prop.property, Optional.of(map));
|
||||
|
||||
} else {
|
||||
|
||||
if (HttpMethod.PATCH.equals(requestMethod)) {
|
||||
throw HttpRequestMethodNotSupportedException.forRejectedMethod(HttpMethod.PATCH)//
|
||||
.withAllowedMethods(HttpMethod.PATCH)//
|
||||
.withMessage(
|
||||
"Cannot PATCH a reference to this singular property since the property type is not a List or a Map.");
|
||||
}
|
||||
|
||||
if (source.getLinks().size() != 1) {
|
||||
throw new IllegalArgumentException(
|
||||
"Must send only 1 link to update a property reference that isn't a List or a Map.");
|
||||
}
|
||||
|
||||
Optional<Object> propVal = loadPropertyValue(prop.propertyType, source.getLinks().get(0));
|
||||
prop.accessor.setProperty(prop.property, propVal);
|
||||
}
|
||||
|
||||
publisher.publishEvent(new BeforeLinkSaveEvent(prop.accessor.getBean(), prop.propertyValue));
|
||||
Object result = invoker.invokeSave(prop.accessor.getBean());
|
||||
publisher.publishEvent(new AfterLinkSaveEvent(result, prop.propertyValue));
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
doWithReferencedProperty(resourceInformation, id, property, handler, requestMethod);
|
||||
@@ -354,68 +338,59 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
|
||||
@RequestMapping(value = BASE_MAPPING + "/{propertyId}", method = DELETE)
|
||||
public ResponseEntity<ResourceSupport> deletePropertyReferenceId(final RootResourceInformation repoRequest,
|
||||
@BackendId Serializable id, @PathVariable String property, final @PathVariable String propertyId)
|
||||
throws Exception {
|
||||
@BackendId Serializable backendId, @PathVariable String property, final @PathVariable String propertyId)
|
||||
throws Exception {
|
||||
|
||||
final RepositoryInvoker invoker = repoRequest.getInvoker();
|
||||
Function<ReferencedProperty, ResourceSupport> handler = prop -> prop.propertyValue.map(it -> {
|
||||
|
||||
Function<ReferencedProperty, ResourceSupport> handler = new Function<ReferencedProperty, ResourceSupport>() {
|
||||
if (prop.property.isCollectionLike()) {
|
||||
|
||||
@Override
|
||||
public ResourceSupport apply(ReferencedProperty prop) {
|
||||
Collection<Object> coll = (Collection<Object>) it;
|
||||
Iterator<Object> iterator = coll.iterator();
|
||||
|
||||
if (null == prop.propertyValue) {
|
||||
return null;
|
||||
while (iterator.hasNext()) {
|
||||
|
||||
Object obj = iterator.next();
|
||||
|
||||
prop.entity.getIdentifierAccessor(obj).getIdentifier()//
|
||||
.map(Object::toString)//
|
||||
.filter(id -> propertyId.equals(id))//
|
||||
.ifPresent(__ -> iterator.remove());
|
||||
}
|
||||
|
||||
if (prop.property.isCollectionLike()) {
|
||||
Collection<Object> coll = (Collection<Object>) prop.propertyValue;
|
||||
Iterator<Object> itr = coll.iterator();
|
||||
while (itr.hasNext()) {
|
||||
Object obj = itr.next();
|
||||
} else if (prop.property.isMap()) {
|
||||
|
||||
IdentifierAccessor accessor = prop.entity.getIdentifierAccessor(obj);
|
||||
String s = accessor.getIdentifier().toString();
|
||||
Map<Object, Object> m = (Map<Object, Object>) it;
|
||||
Iterator<Entry<Object, Object>> iterator = m.entrySet().iterator();
|
||||
|
||||
if (propertyId.equals(s)) {
|
||||
itr.remove();
|
||||
}
|
||||
}
|
||||
} else if (prop.property.isMap()) {
|
||||
while (iterator.hasNext()) {
|
||||
|
||||
Map<Object, Object> m = (Map<Object, Object>) prop.propertyValue;
|
||||
Iterator<Entry<Object, Object>> itr = m.entrySet().iterator();
|
||||
Object key = iterator.next().getKey();
|
||||
|
||||
while (itr.hasNext()) {
|
||||
|
||||
Object key = itr.next().getKey();
|
||||
|
||||
IdentifierAccessor accessor = prop.entity.getIdentifierAccessor(m.get(key));
|
||||
String s = accessor.getIdentifier().toString();
|
||||
|
||||
if (propertyId.equals(s)) {
|
||||
itr.remove();
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
prop.accessor.setProperty(prop.property, null);
|
||||
prop.entity.getIdentifierAccessor(m.get(key)).getIdentifier()//
|
||||
.map(Object::toString)//
|
||||
.filter(id -> propertyId.equals(id))//
|
||||
.ifPresent(__ -> iterator.remove());
|
||||
}
|
||||
|
||||
publisher.publishEvent(new BeforeLinkDeleteEvent(prop.accessor.getBean(), prop.propertyValue));
|
||||
Object result = invoker.invokeSave(prop.accessor.getBean());
|
||||
publisher.publishEvent(new AfterLinkDeleteEvent(result, prop.propertyValue));
|
||||
|
||||
return null;
|
||||
} else {
|
||||
prop.wipeValue();
|
||||
}
|
||||
};
|
||||
|
||||
doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.DELETE);
|
||||
publisher.publishEvent(new BeforeLinkDeleteEvent(prop.accessor.getBean(), it));
|
||||
Object result = repoRequest.getInvoker().invokeSave(prop.accessor.getBean());
|
||||
publisher.publishEvent(new AfterLinkDeleteEvent(result, it));
|
||||
|
||||
return (ResourceSupport) null;
|
||||
|
||||
}).orElse(null);
|
||||
|
||||
doWithReferencedProperty(repoRequest, backendId, property, handler, HttpMethod.DELETE);
|
||||
|
||||
return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
private Object loadPropertyValue(Class<?> type, Link link) {
|
||||
private Optional<Object> loadPropertyValue(Class<?> type, Link link) {
|
||||
|
||||
String href = link.expand().getHref();
|
||||
String id = href.substring(href.lastIndexOf('/') + 1);
|
||||
@@ -425,8 +400,9 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
return invoker.invokeFindOne(id);
|
||||
}
|
||||
|
||||
private ResourceSupport doWithReferencedProperty(RootResourceInformation resourceInformation, Serializable id,
|
||||
String propertyPath, Function<ReferencedProperty, ResourceSupport> handler, HttpMethod method) throws Exception {
|
||||
private Optional<ResourceSupport> doWithReferencedProperty(RootResourceInformation resourceInformation,
|
||||
Serializable id, String propertyPath, Function<ReferencedProperty, ResourceSupport> handler, HttpMethod method)
|
||||
throws Exception {
|
||||
|
||||
ResourceMetadata metadata = resourceInformation.getResourceMetadata();
|
||||
PropertyAwareResourceMapping mapping = metadata.getProperty(propertyPath);
|
||||
@@ -439,14 +415,15 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
resourceInformation.verifySupportedMethod(method, property);
|
||||
|
||||
RepositoryInvoker invoker = resourceInformation.getInvoker();
|
||||
Object domainObj = invoker.invokeFindOne(id);
|
||||
Optional<Object> domainObj = invoker.invokeFindOne(id);
|
||||
|
||||
if (null == domainObj) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
domainObj.orElseThrow(() -> new ResourceNotFoundException());
|
||||
|
||||
PersistentPropertyAccessor accessor = property.getOwner().getPropertyAccessor(domainObj);
|
||||
return handler.apply(new ReferencedProperty(property, accessor.getProperty(property), accessor));
|
||||
return domainObj.map(it -> {
|
||||
|
||||
PersistentPropertyAccessor accessor = property.getOwner().getPropertyAccessor(it);
|
||||
return handler.apply(new ReferencedProperty(property, accessor.getProperty(property), accessor));
|
||||
});
|
||||
}
|
||||
|
||||
private class ReferencedProperty {
|
||||
@@ -454,10 +431,10 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
final PersistentEntity<?, ?> entity;
|
||||
final PersistentProperty<?> property;
|
||||
final Class<?> propertyType;
|
||||
final Object propertyValue;
|
||||
final Optional<Object> propertyValue;
|
||||
final PersistentPropertyAccessor accessor;
|
||||
|
||||
private ReferencedProperty(PersistentProperty<?> property, Object propertyValue,
|
||||
private ReferencedProperty(PersistentProperty<?> property, Optional<Object> propertyValue,
|
||||
PersistentPropertyAccessor wrapper) {
|
||||
|
||||
this.property = property;
|
||||
@@ -466,5 +443,54 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro
|
||||
this.propertyType = property.getActualType();
|
||||
this.entity = repositories.getPersistentEntity(propertyType);
|
||||
}
|
||||
|
||||
public void writeValue() {
|
||||
accessor.setProperty(property, propertyValue);
|
||||
}
|
||||
|
||||
public void wipeValue() {
|
||||
accessor.setProperty(property, Optional.empty());
|
||||
}
|
||||
}
|
||||
|
||||
@ExceptionHandler
|
||||
public ResponseEntity<Void> handle(HttpRequestMethodNotSupportedException exception) {
|
||||
return exception.toResponse();
|
||||
}
|
||||
|
||||
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
static class HttpRequestMethodNotSupportedException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 3704212056962845475L;
|
||||
|
||||
private final HttpMethod rejectedMethod;
|
||||
private final HttpMethod[] allowedMethods;
|
||||
private final String message;
|
||||
|
||||
public static HttpRequestMethodNotSupportedException forRejectedMethod(HttpMethod method) {
|
||||
return new HttpRequestMethodNotSupportedException(method, new HttpMethod[0], null);
|
||||
}
|
||||
|
||||
public HttpRequestMethodNotSupportedException withAllowedMethods(HttpMethod... methods) {
|
||||
return new HttpRequestMethodNotSupportedException(this.rejectedMethod, methods.clone(), null);
|
||||
}
|
||||
|
||||
public HttpRequestMethodNotSupportedException withMessage(String message, Object... parameters) {
|
||||
return new HttpRequestMethodNotSupportedException(this.rejectedMethod, this.allowedMethods,
|
||||
String.format(message, parameters));
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Throwable#getMessage()
|
||||
*/
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public ResponseEntity<Void> toResponse() {
|
||||
return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).allow(allowedMethods).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
@@ -63,7 +64,7 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
|
||||
|
||||
private final ResourceMappings mappings;
|
||||
private final RepositoryRestConfiguration configuration;
|
||||
private final Repositories repositories;
|
||||
private final Optional<Repositories> repositories;
|
||||
|
||||
private RepositoryCorsConfigurationAccessor corsConfigurationAccessor;
|
||||
private JpaHelper jpaHelper;
|
||||
@@ -76,7 +77,7 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
|
||||
* @param config must not be {@literal null}.
|
||||
*/
|
||||
public RepositoryRestHandlerMapping(ResourceMappings mappings, RepositoryRestConfiguration config) {
|
||||
this(mappings, config, null);
|
||||
this(mappings, config, Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,15 +86,22 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
|
||||
*
|
||||
* @param mappings must not be {@literal null}.
|
||||
* @param config must not be {@literal null}.
|
||||
* @param repositories can be {@literal null} if {@link CrossOrigin} resolution is not required.
|
||||
* @param repositories must not be {@literal null}.
|
||||
*/
|
||||
public RepositoryRestHandlerMapping(ResourceMappings mappings, RepositoryRestConfiguration config,
|
||||
Repositories repositories) {
|
||||
|
||||
this(mappings, config, Optional.of(repositories));
|
||||
}
|
||||
|
||||
private RepositoryRestHandlerMapping(ResourceMappings mappings, RepositoryRestConfiguration config,
|
||||
Optional<Repositories> repositories) {
|
||||
|
||||
super(config);
|
||||
|
||||
Assert.notNull(mappings, "ResourceMappings must not be null!");
|
||||
Assert.notNull(config, "RepositoryRestConfiguration must not be null!");
|
||||
Assert.notNull(repositories, "Repositories must not be null!");
|
||||
|
||||
this.mappings = mappings;
|
||||
this.configuration = config;
|
||||
@@ -201,19 +209,14 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
|
||||
@Override
|
||||
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
|
||||
|
||||
CorsConfiguration corsConfiguration = super.getCorsConfiguration(handler, request);
|
||||
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
|
||||
|
||||
String repositoryLookupPath = new BaseUri(configuration.getBaseUri()).getRepositoryLookupPath(lookupPath);
|
||||
CorsConfiguration corsConfiguration = super.getCorsConfiguration(handler, request);
|
||||
|
||||
if (!StringUtils.hasText(repositoryLookupPath) || repositories == null) {
|
||||
return corsConfiguration;
|
||||
}
|
||||
|
||||
CorsConfiguration repositoryCorsConfiguration = corsConfigurationAccessor.findCorsConfiguration(lookupPath);
|
||||
|
||||
return corsConfiguration == null ? repositoryCorsConfiguration
|
||||
: corsConfiguration.combine(repositoryCorsConfiguration);
|
||||
return repositories.filter(it -> StringUtils.hasText(repositoryLookupPath))//
|
||||
.flatMap(it -> corsConfigurationAccessor.findCorsConfiguration(lookupPath))
|
||||
.map(it -> it.combine(corsConfiguration))//
|
||||
.orElse(corsConfiguration);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -262,28 +265,25 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
|
||||
|
||||
private final @NonNull ResourceMappings mappings;
|
||||
private final @NonNull StringValueResolver embeddedValueResolver;
|
||||
private final Repositories repositories;
|
||||
private final @NonNull Optional<Repositories> repositories;
|
||||
|
||||
CorsConfiguration findCorsConfiguration(String lookupPath) {
|
||||
Optional<CorsConfiguration> findCorsConfiguration(String lookupPath) {
|
||||
|
||||
ResourceMetadata resource = getResourceMetadata(getRepositoryBasePath(lookupPath));
|
||||
|
||||
return resource != null && repositories != null ? createConfiguration(
|
||||
repositories.getRepositoryInformationFor(resource.getDomainType()).getRepositoryInterface()) : null;
|
||||
return getResourceMetadata(getRepositoryBasePath(lookupPath))//
|
||||
.flatMap(it -> repositories.flatMap(foo -> foo.getRepositoryInformationFor(it.getDomainType())))//
|
||||
.map(it -> it.getRepositoryInterface())//
|
||||
.map(it -> createConfiguration(it));
|
||||
}
|
||||
|
||||
private ResourceMetadata getResourceMetadata(String basePath) {
|
||||
private Optional<ResourceMetadata> getResourceMetadata(String basePath) {
|
||||
|
||||
if (mappings.exportsTopLevelResourceFor(basePath)) {
|
||||
|
||||
for (ResourceMetadata metadata : mappings) {
|
||||
if (metadata.getPath().matches(basePath) && metadata.isExported()) {
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
if (!mappings.exportsTopLevelResourceFor(basePath)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return null;
|
||||
return mappings.stream()//
|
||||
.filter(it -> it.getPath().matches(basePath) && it.isExported())//
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -24,6 +24,7 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.MethodParameter;
|
||||
@@ -35,7 +36,6 @@ import org.springframework.data.rest.core.mapping.MethodResourceMapping;
|
||||
import org.springframework.data.rest.core.mapping.ResourceMappings;
|
||||
import org.springframework.data.rest.core.mapping.ResourceMetadata;
|
||||
import org.springframework.data.rest.core.mapping.SearchResourceMappings;
|
||||
import org.springframework.data.rest.core.util.Supplier;
|
||||
import org.springframework.data.rest.webmvc.support.DefaultedPageable;
|
||||
import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
@@ -180,7 +180,8 @@ class RepositorySearchController extends AbstractRepositoryRestController {
|
||||
Sort sort, PersistentEntityResourceAssembler assembler, @RequestHeader HttpHeaders headers) {
|
||||
|
||||
Method method = checkExecutability(resourceInformation, search);
|
||||
Object result = executeQueryMethod(resourceInformation.getInvoker(), parameters, method, pageable, sort, assembler);
|
||||
Optional<Object> result = executeQueryMethod(resourceInformation.getInvoker(), parameters, method, pageable, sort,
|
||||
assembler);
|
||||
|
||||
SearchResourceMappings searchMappings = resourceInformation.getSearchMappings();
|
||||
MethodResourceMapping methodMapping = searchMappings.getExportedMethodMappingForPath(search);
|
||||
@@ -199,27 +200,23 @@ class RepositorySearchController extends AbstractRepositoryRestController {
|
||||
* @param baseLink can be {@literal null}.
|
||||
* @return
|
||||
*/
|
||||
protected ResponseEntity<?> toResource(final Object source, final PersistentEntityResourceAssembler assembler,
|
||||
protected ResponseEntity<?> toResource(Optional<Object> source, final PersistentEntityResourceAssembler assembler,
|
||||
Class<?> domainType, Link baseLink, HttpHeaders headers, RootResourceInformation information) {
|
||||
|
||||
if (source instanceof Iterable) {
|
||||
return ResponseEntity.ok(toResources((Iterable<?>) source, assembler, domainType, baseLink));
|
||||
} else if (source == null) {
|
||||
throw new ResourceNotFoundException();
|
||||
} else if (ClassUtils.isPrimitiveOrWrapper(source.getClass())) {
|
||||
return ResponseEntity.ok(source);
|
||||
}
|
||||
return source.map(it -> {
|
||||
|
||||
PersistentEntity<?, ?> entity = information.getPersistentEntity();
|
||||
if (it instanceof Iterable) {
|
||||
return ResponseEntity.ok(toResources((Iterable<?>) it, assembler, domainType, baseLink));
|
||||
} else if (ClassUtils.isPrimitiveOrWrapper(it.getClass())) {
|
||||
return ResponseEntity.ok(it);
|
||||
}
|
||||
|
||||
return resourceStatus.getStatusAndHeaders(headers, source, entity).toResponseEntity(//
|
||||
new Supplier<PersistentEntityResource>() {
|
||||
PersistentEntity<?, ?> entity = information.getPersistentEntity();
|
||||
|
||||
@Override
|
||||
public PersistentEntityResource get() {
|
||||
return assembler.toFullResource(source);
|
||||
}
|
||||
});
|
||||
return resourceStatus.getStatusAndHeaders(headers, it, entity).toResponseEntity(//
|
||||
() -> assembler.toFullResource(it));
|
||||
|
||||
}).orElseThrow(() -> new ResourceNotFoundException());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -243,7 +240,8 @@ class RepositorySearchController extends AbstractRepositoryRestController {
|
||||
PersistentEntityResourceAssembler assembler) {
|
||||
|
||||
Method method = checkExecutability(resourceInformation, search);
|
||||
Object result = executeQueryMethod(resourceInformation.getInvoker(), parameters, method, pageable, sort, assembler);
|
||||
Optional<Object> result = executeQueryMethod(resourceInformation.getInvoker(), parameters, method, pageable, sort,
|
||||
assembler);
|
||||
ResourceMetadata metadata = resourceInformation.getResourceMetadata();
|
||||
ResponseEntity<?> entity = toResource(result, assembler, metadata.getDomainType(), null, headers,
|
||||
resourceInformation);
|
||||
@@ -331,7 +329,7 @@ class RepositorySearchController extends AbstractRepositoryRestController {
|
||||
* @param pageable
|
||||
* @return
|
||||
*/
|
||||
private Object executeQueryMethod(final RepositoryInvoker invoker,
|
||||
private Optional<Object> executeQueryMethod(final RepositoryInvoker invoker,
|
||||
@RequestParam MultiValueMap<String, Object> parameters, Method method, DefaultedPageable pageable, Sort sort,
|
||||
PersistentEntityResourceAssembler assembler) {
|
||||
|
||||
|
||||
@@ -21,9 +21,9 @@ import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.rest.core.util.Supplier;
|
||||
import org.springframework.data.rest.webmvc.support.ETag;
|
||||
import org.springframework.hateoas.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
|
||||
@@ -256,7 +256,7 @@ public class RootResourceInformationToAlpsDescriptorConverter {
|
||||
*/
|
||||
private List<Descriptor> getPaginationDescriptors(Class<?> type, HttpMethod method) {
|
||||
|
||||
RepositoryInformation information = repositories.getRepositoryInformationFor(type);
|
||||
RepositoryInformation information = repositories.getRequiredRepositoryInformation(type);
|
||||
|
||||
if (!information.isPagingRepository() || !getType(method).equals(Type.SAFE)) {
|
||||
return Collections.emptyList();
|
||||
@@ -290,7 +290,7 @@ public class RootResourceInformationToAlpsDescriptorConverter {
|
||||
|
||||
private List<Descriptor> buildPropertyDescriptors(final Class<?> type, String baseRel) {
|
||||
|
||||
final PersistentEntity<?, ?> entity = persistentEntities.getPersistentEntity(type);
|
||||
final PersistentEntity<?, ?> entity = persistentEntities.getRequiredPersistentEntity(type);
|
||||
final List<Descriptor> propertyDescriptors = new ArrayList<Descriptor>();
|
||||
final JacksonMetadata jackson = new JacksonMetadata(mapper, type);
|
||||
final ResourceMetadata metadata = associations.getMetadataFor(entity.getType());
|
||||
@@ -311,10 +311,10 @@ public class RootResourceInformationToAlpsDescriptorConverter {
|
||||
|
||||
propertyDescriptors.add(//
|
||||
descriptor(). //
|
||||
type(Type.SEMANTIC).//
|
||||
name(propertyDefinition.getName()).//
|
||||
doc(getDocFor(propertyMapping.getDescription(), property)).//
|
||||
build());
|
||||
type(Type.SEMANTIC).//
|
||||
name(propertyDefinition.getName()).//
|
||||
doc(getDocFor(propertyMapping.getDescription(), property)).//
|
||||
build());
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -333,7 +333,7 @@ public class RootResourceInformationToAlpsDescriptorConverter {
|
||||
ResourceMapping mapping = metadata.getMappingFor(property);
|
||||
|
||||
DescriptorBuilder builder = descriptor().//
|
||||
name(mapping.getRel()).doc(getDocFor(mapping.getDescription()));
|
||||
name(mapping.getRel()).doc(getDocFor(mapping.getDescription()));
|
||||
|
||||
ResourceMetadata targetTypeMetadata = associations.getMetadataFor(property.getActualType());
|
||||
|
||||
@@ -343,8 +343,8 @@ public class RootResourceInformationToAlpsDescriptorConverter {
|
||||
Link link = new Link(href).withSelfRel();
|
||||
|
||||
builder.//
|
||||
type(Type.SAFE).//
|
||||
rt(link.getHref());
|
||||
type(Type.SAFE).//
|
||||
rt(link.getHref());
|
||||
|
||||
propertyDescriptors.add(builder.build());
|
||||
}
|
||||
@@ -386,6 +386,7 @@ public class RootResourceInformationToAlpsDescriptorConverter {
|
||||
return getDocFor(description, null);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Doc getDocFor(ResourceDescription description, PersistentProperty<?> property) {
|
||||
|
||||
if (description == null) {
|
||||
|
||||
@@ -18,12 +18,12 @@ package org.springframework.data.rest.webmvc.config;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.repository.support.RepositoryInvoker;
|
||||
import org.springframework.data.rest.webmvc.IncomingRequest;
|
||||
import org.springframework.data.rest.webmvc.PersistentEntityResource;
|
||||
import org.springframework.data.rest.webmvc.PersistentEntityResource.Builder;
|
||||
@@ -124,16 +124,7 @@ public class PersistentEntityResourceHandlerMethodArgumentResolver implements Ha
|
||||
}
|
||||
|
||||
Serializable id = idResolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
|
||||
Object objectToUpdate = getObjectToUpdate(id, resourceInformation);
|
||||
|
||||
boolean forUpdate = false;
|
||||
Object entityIdentifier = null;
|
||||
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
|
||||
|
||||
if (objectToUpdate != null) {
|
||||
forUpdate = true;
|
||||
entityIdentifier = entity.getIdentifierAccessor(objectToUpdate).getIdentifier();
|
||||
}
|
||||
Optional<Object> objectToUpdate = getObjectToUpdate(id, resourceInformation);
|
||||
|
||||
Object obj = read(resourceInformation, incoming, converter, objectToUpdate);
|
||||
|
||||
@@ -141,8 +132,13 @@ public class PersistentEntityResourceHandlerMethodArgumentResolver implements Ha
|
||||
throw new HttpMessageNotReadableException(String.format(ERROR_MESSAGE, domainType));
|
||||
}
|
||||
|
||||
if (entityIdentifier != null) {
|
||||
entity.getPropertyAccessor(obj).setProperty(entity.getIdProperty(), entityIdentifier);
|
||||
PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();
|
||||
boolean forUpdate = objectToUpdate.isPresent();
|
||||
Optional<Object> entityIdentifier = objectToUpdate
|
||||
.flatMap(it -> entity.getIdentifierAccessor(it).getIdentifier());
|
||||
|
||||
if (entityIdentifier.isPresent()) {
|
||||
entity.getPropertyAccessor(obj).setProperty(entity.getRequiredIdProperty(), entityIdentifier);
|
||||
}
|
||||
|
||||
Builder build = PersistentEntityResource.build(obj, entity);
|
||||
@@ -163,27 +159,25 @@ public class PersistentEntityResourceHandlerMethodArgumentResolver implements Ha
|
||||
* @return
|
||||
*/
|
||||
private Object read(RootResourceInformation information, IncomingRequest request,
|
||||
HttpMessageConverter<Object> converter, Object objectToUpdate) {
|
||||
HttpMessageConverter<Object> converter, Optional<Object> objectToUpdate) {
|
||||
|
||||
// JSON + PATCH request
|
||||
if (request.isPatchRequest() && converter instanceof MappingJackson2HttpMessageConverter) {
|
||||
|
||||
if (objectToUpdate == null) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
return objectToUpdate.map(it -> {
|
||||
|
||||
ObjectMapper mapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
|
||||
Object result = readPatch(request, mapper, objectToUpdate);
|
||||
ObjectMapper mapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
|
||||
return readPatch(request, mapper, it);
|
||||
|
||||
return result;
|
||||
}).orElseThrow(() -> new ResourceNotFoundException());
|
||||
|
||||
// JSON + PUT request
|
||||
} else if (converter instanceof MappingJackson2HttpMessageConverter) {
|
||||
|
||||
ObjectMapper mapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
|
||||
|
||||
return objectToUpdate == null ? read(request, converter, information)
|
||||
: readPutForUpdate(request, mapper, objectToUpdate);
|
||||
return objectToUpdate.map(it -> readPutForUpdate(request, mapper, it))//
|
||||
.orElseGet(() -> read(request, converter, information));
|
||||
}
|
||||
|
||||
// Catch all
|
||||
@@ -238,13 +232,12 @@ public class PersistentEntityResourceHandlerMethodArgumentResolver implements Ha
|
||||
* @param information must not be {@literal null}.
|
||||
* @return
|
||||
*/
|
||||
private static Object getObjectToUpdate(Serializable id, RootResourceInformation information) {
|
||||
private static Optional<Object> getObjectToUpdate(Serializable id, RootResourceInformation information) {
|
||||
|
||||
if (id == null) {
|
||||
return null;
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
RepositoryInvoker invoker = information.getInvoker();
|
||||
return invoker.invokeFindOne(id);
|
||||
return information.getInvoker().invokeFindOne(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2015 the original author or authors.
|
||||
* Copyright 2015-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,7 +20,7 @@ import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
|
||||
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
|
||||
import org.springframework.data.querydsl.QuerydslRepositoryInvokerAdapter;
|
||||
import org.springframework.data.querydsl.binding.QuerydslBindings;
|
||||
import org.springframework.data.querydsl.binding.QuerydslBindingsFactory;
|
||||
@@ -76,22 +76,26 @@ class QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
protected RepositoryInvoker postProcess(MethodParameter parameter, RepositoryInvoker invoker,
|
||||
Class<?> domainType, Map<String, String[]> parameters) {
|
||||
protected RepositoryInvoker postProcess(MethodParameter parameter, RepositoryInvoker invoker, Class<?> domainType,
|
||||
Map<String, String[]> parameters) {
|
||||
|
||||
Object repository = repositories.getRepositoryFor(domainType);
|
||||
|
||||
if (!QueryDslPredicateExecutor.class.isInstance(repository)
|
||||
|| !parameter.hasParameterAnnotation(QuerydslPredicate.class)) {
|
||||
if (!parameter.hasParameterAnnotation(QuerydslPredicate.class)) {
|
||||
return invoker;
|
||||
}
|
||||
|
||||
ClassTypeInformation<?> type = ClassTypeInformation.from(domainType);
|
||||
return repositories.getRepositoryFor(domainType)//
|
||||
.filter(it -> QuerydslPredicateExecutor.class.isInstance(it))//
|
||||
.map(it -> {
|
||||
|
||||
QuerydslBindings bindings = factory.createBindingsFor(null, type);
|
||||
Predicate predicate = predicateBuilder.getPredicate(type, toMultiValueMap(parameters), bindings);
|
||||
ClassTypeInformation<?> type = ClassTypeInformation.from(domainType);
|
||||
|
||||
return new QuerydslRepositoryInvokerAdapter(invoker, (QueryDslPredicateExecutor<Object>) repository, predicate);
|
||||
QuerydslBindings bindings = factory.createBindingsFor(type);
|
||||
Predicate predicate = predicateBuilder.getPredicate(type, toMultiValueMap(parameters), bindings);
|
||||
|
||||
return (RepositoryInvoker) new QuerydslRepositoryInvokerAdapter(invoker,
|
||||
(QuerydslPredicateExecutor<Object>) it, predicate);
|
||||
|
||||
}).orElse(invoker);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -50,7 +50,7 @@ import org.springframework.data.geo.GeoModule;
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
import org.springframework.data.mapping.context.PersistentEntities;
|
||||
import org.springframework.data.projection.SpelAwareProxyProjectionFactory;
|
||||
import org.springframework.data.querydsl.QueryDslUtils;
|
||||
import org.springframework.data.querydsl.QuerydslUtils;
|
||||
import org.springframework.data.querydsl.binding.QuerydslBindingsFactory;
|
||||
import org.springframework.data.querydsl.binding.QuerydslPredicateBuilder;
|
||||
import org.springframework.data.repository.support.DefaultRepositoryInvokerFactory;
|
||||
@@ -72,6 +72,7 @@ import org.springframework.data.rest.core.support.EntityLookup;
|
||||
import org.springframework.data.rest.core.support.RepositoryRelProvider;
|
||||
import org.springframework.data.rest.core.support.SelfLinkProvider;
|
||||
import org.springframework.data.rest.core.support.UnwrappingRepositoryInvokerFactory;
|
||||
import org.springframework.data.rest.core.util.Java8PluginRegistry;
|
||||
import org.springframework.data.rest.webmvc.BasePathAwareController;
|
||||
import org.springframework.data.rest.webmvc.BasePathAwareHandlerMapping;
|
||||
import org.springframework.data.rest.webmvc.BaseUri;
|
||||
@@ -154,6 +155,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.Module;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
|
||||
|
||||
/**
|
||||
* Main application configuration for Spring Data REST. To customize how the exporter works, subclass this and override
|
||||
@@ -189,6 +191,11 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
|
||||
private RepositoryRestConfigurerDelegate configurerDelegate;
|
||||
|
||||
public RepositoryRestMvcConfiguration(ApplicationContext context,
|
||||
@Qualifier("mvcConversionService") ObjectFactory<ConversionService> conversionService) {
|
||||
super(context, conversionService);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
|
||||
@@ -335,7 +342,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
@Bean
|
||||
public RootResourceInformationHandlerMethodArgumentResolver repoRequestArgumentResolver() {
|
||||
|
||||
if (QueryDslUtils.QUERY_DSL_PRESENT) {
|
||||
if (QuerydslUtils.QUERY_DSL_PRESENT) {
|
||||
|
||||
QuerydslBindingsFactory factory = applicationContext.getBean(QuerydslBindingsFactory.class);
|
||||
QuerydslPredicateBuilder predicateBuilder = new QuerydslPredicateBuilder(defaultConversionService(),
|
||||
@@ -357,7 +364,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
|
||||
@Bean
|
||||
public BackendIdHandlerMethodArgumentResolver backendIdHandlerMethodArgumentResolver() {
|
||||
return new BackendIdHandlerMethodArgumentResolver(backendIdConverterRegistry(),
|
||||
return new BackendIdHandlerMethodArgumentResolver(Java8PluginRegistry.of(backendIdConverterRegistry()),
|
||||
resourceMetadataHandlerMethodArgumentResolver(), baseUri());
|
||||
}
|
||||
|
||||
@@ -380,7 +387,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
pageableResolver(), sortResolver());
|
||||
|
||||
return new RepositoryEntityLinks(repositories(), resourceMappings(), config(), templateVariables,
|
||||
backendIdConverterRegistry());
|
||||
Java8PluginRegistry.of(backendIdConverterRegistry()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -443,8 +450,12 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
@Bean
|
||||
public ObjectMapper objectMapper() {
|
||||
|
||||
Jdk8Module jdk8Module = new Jdk8Module();
|
||||
jdk8Module.configureAbsentsAsNulls(true);
|
||||
|
||||
ObjectMapper mapper = basicObjectMapper();
|
||||
mapper.registerModule(persistentEntityJackson2Module());
|
||||
mapper.registerModule(jdk8Module);
|
||||
|
||||
return mapper;
|
||||
}
|
||||
@@ -635,7 +646,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
EmbeddedResourcesAssembler assembler = new EmbeddedResourcesAssembler(entities, associationLinks(),
|
||||
excerptProjector());
|
||||
LookupObjectSerializer lookupObjectSerializer = new LookupObjectSerializer(
|
||||
OrderAwarePluginRegistry.create(getEntityLookups()));
|
||||
Java8PluginRegistry.of(getEntityLookups()));
|
||||
|
||||
return new PersistentEntityJackson2Module(associationLinks(), entities, uriToEntityConverter, linkCollector(),
|
||||
repositoryInvokerFactory, lookupObjectSerializer, resourceProcessorInvoker(), assembler);
|
||||
@@ -655,7 +666,6 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
|
||||
SpelAwareProxyProjectionFactory projectionFactory = new SpelAwareProxyProjectionFactory();
|
||||
projectionFactory.setBeanFactory(applicationContext);
|
||||
projectionFactory.setResourceLoader(applicationContext);
|
||||
|
||||
return new DefaultExcerptProjector(projectionFactory, resourceMappings());
|
||||
}
|
||||
@@ -732,7 +742,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
HateoasPageableHandlerMethodArgumentResolver resolver = super.pageableResolver();
|
||||
resolver.setPageParameterName(config().getPageParamName());
|
||||
resolver.setSizeParameterName(config().getLimitParamName());
|
||||
resolver.setFallbackPageable(new PageRequest(0, config().getDefaultPageSize()));
|
||||
resolver.setFallbackPageable(PageRequest.of(0, config().getDefaultPageSize()));
|
||||
resolver.setMaxPageSize(config().getMaxPageSize());
|
||||
|
||||
return resolver;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user