Support to receive aggregate references as request parameters.
We now support using AggregateReference as type to bind request parameters taking URIs pointing to related aggregates. The default resolution will try to resolve the entire URI via UriToEntityConverter but one can also provide a function that can extract any part of the URI to be then resolved into either an identifier, aggregate instance or jMolecules Association against the ConversionService. Fixes #2239.
This commit is contained in:
@@ -20,7 +20,9 @@ import java.util.function.Supplier;
|
||||
|
||||
import org.jmolecules.ddd.types.Entity;
|
||||
import org.jmolecules.ddd.types.Identifier;
|
||||
import org.jmolecules.spring.AssociationToPrimitivesConverter;
|
||||
import org.jmolecules.spring.IdentifierToPrimitivesConverter;
|
||||
import org.jmolecules.spring.PrimitivesToAssociationConverter;
|
||||
import org.jmolecules.spring.PrimitivesToIdentifierConverter;
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
@@ -73,8 +75,13 @@ class JMoleculesConfigurer implements WebMvcConfigurer, RepositoryRestConfigurer
|
||||
|
||||
Supplier<ConversionService> supplier = () -> conversionService;
|
||||
|
||||
conversionService.addConverter(new PrimitivesToIdentifierConverter(supplier));
|
||||
conversionService.addConverter(new IdentifierToPrimitivesConverter(supplier));
|
||||
var primitivesToIdentifierConverter = new PrimitivesToIdentifierConverter(supplier);
|
||||
var identifierToPrimitivesConverter = new IdentifierToPrimitivesConverter(supplier);
|
||||
|
||||
conversionService.addConverter(primitivesToIdentifierConverter);
|
||||
conversionService.addConverter(identifierToPrimitivesConverter);
|
||||
conversionService.addConverter(new AssociationToPrimitivesConverter<>(identifierToPrimitivesConverter));
|
||||
conversionService.addConverter(new PrimitivesToAssociationConverter<>(primitivesToIdentifierConverter));
|
||||
}
|
||||
|
||||
@Lazy
|
||||
|
||||
@@ -23,6 +23,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.beans.factory.BeanClassLoaderAware;
|
||||
@@ -320,13 +321,15 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
@Bean
|
||||
@Qualifier
|
||||
public DefaultFormattingConversionService defaultConversionService(PersistentEntities persistentEntities,
|
||||
RepositoryInvokerFactory repositoryInvokerFactory, Repositories repositories) {
|
||||
RepositoryInvokerFactory repositoryInvokerFactory) {
|
||||
|
||||
DefaultFormattingConversionService conversionService = (DefaultFormattingConversionService) defaultConversionService;
|
||||
var conversionService = (DefaultFormattingConversionService) defaultConversionService;
|
||||
Supplier<ConversionService> supplier = () -> conversionService;
|
||||
|
||||
// Add Spring Data Commons formatters
|
||||
conversionService
|
||||
.addConverter(new UriToEntityConverter(persistentEntities, repositoryInvokerFactory, repositories));
|
||||
.addConverter(new UriToEntityConverter(persistentEntities, repositoryInvokerFactory, supplier));
|
||||
conversionService.addConverter(new StringToAggregateReferenceConverter(supplier));
|
||||
conversionService.addConverter(StringToLdapNameConverter.INSTANCE);
|
||||
addFormatters(conversionService);
|
||||
|
||||
@@ -638,8 +641,8 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
}
|
||||
|
||||
/**
|
||||
* Special {@link org.springframework.web.servlet.HandlerAdapter} that only recognizes handler methods defined in
|
||||
* the provided controller classes.
|
||||
* Special {@link org.springframework.web.servlet.HandlerAdapter} that only recognizes handler methods defined in the
|
||||
* provided controller classes.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@@ -734,7 +737,8 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
PluginRegistry.of(getEntityLookups()));
|
||||
|
||||
return new PersistentEntityJackson2Module(associationLinks.get(), persistentEntities.get(),
|
||||
new UriToEntityConverter(persistentEntities.get(), repositoryInvokerFactory.get(), repositories.get()),
|
||||
new UriToEntityConverter(persistentEntities.get(), repositoryInvokerFactory.get(),
|
||||
() -> defaultConversionService),
|
||||
linkCollector, repositoryInvokerFactory.get(), lookupObjectSerializer, invoker.getObject(), assembler);
|
||||
}
|
||||
|
||||
@@ -954,7 +958,8 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
|
||||
|
||||
objectMapper.registerModule(geoModule.getObject());
|
||||
objectMapper.registerModule(new AggregateReferenceResolvingModule(
|
||||
new UriToEntityConverter(persistentEntities.get(), repositoryInvokerFactory.get(), repositories.get()),
|
||||
new UriToEntityConverter(persistentEntities.get(), repositoryInvokerFactory.get(),
|
||||
() -> defaultConversionService),
|
||||
resourceMappings.get()));
|
||||
|
||||
if (repositoryRestConfiguration.get().isEnableEnumTranslation()) {
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* Copyright 2023 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
|
||||
*
|
||||
* https://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.webmvc.config;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.jmolecules.ddd.types.AggregateRoot;
|
||||
import org.jmolecules.ddd.types.Identifier;
|
||||
import org.springframework.core.convert.ConversionFailedException;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.converter.GenericConverter;
|
||||
import org.springframework.data.rest.core.AggregateReference;
|
||||
import org.springframework.data.rest.core.AssociationAggregateReference;
|
||||
import org.springframework.data.rest.core.ResolvingAggregateReference;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
|
||||
/**
|
||||
* A {@link GenericConverter} to convert {@link String}s into {@link AggregateReference} instance for the latter to be
|
||||
* injectable into Spring MVC controller methods.
|
||||
*
|
||||
* @author Oliver Drotbohm
|
||||
* @since 4.1
|
||||
*/
|
||||
class StringToAggregateReferenceConverter implements GenericConverter {
|
||||
|
||||
private static final boolean JMOLECULES_PRESENT = ClassUtils.isPresent(
|
||||
"org.jmolecules.spring.IdentifierToPrimitivesConverter",
|
||||
StringToAggregateReferenceConverter.class.getClassLoader());
|
||||
private static final Class<?> ASSOCIATION_AGGREGATE_REFERENCE_TYPE = tryToLoadAssociationReferenceClass();
|
||||
|
||||
private final Supplier<ConversionService> conversionService;
|
||||
|
||||
/**
|
||||
* Creates a new {@link StringToAggregateReferenceConverter} for the given {@link ConversionService}.
|
||||
*
|
||||
* @param conversionService must not be {@literal null}.
|
||||
*/
|
||||
StringToAggregateReferenceConverter(Supplier<ConversionService> conversionService) {
|
||||
|
||||
Assert.notNull(conversionService, "ConversionService must not be null!");
|
||||
|
||||
this.conversionService = conversionService;
|
||||
}
|
||||
|
||||
private static Class<?> tryToLoadAssociationReferenceClass() {
|
||||
|
||||
var classLoader = StringToAggregateReferenceConverter.class.getClassLoader();
|
||||
|
||||
if (!ClassUtils.isPresent("org.jmolecules.ddd.types.Association", classLoader)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return ClassUtils.forName("org.springframework.data.rest.core.AssociationAggregateReference", classLoader);
|
||||
} catch (ClassNotFoundException o_O) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Set<ConvertiblePair> getConvertibleTypes() {
|
||||
return Set.of(new ConvertiblePair(String.class, AggregateReference.class));
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public AggregateReference<?, ?> convert(@Nullable Object source, TypeDescriptor sourceType,
|
||||
TypeDescriptor targetType) {
|
||||
|
||||
if (source == null) {
|
||||
throw new ConversionFailedException(sourceType, targetType, source,
|
||||
new IllegalArgumentException("Source value must not be null"));
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
var uri = new URI(source.toString());
|
||||
var resolvableType = targetType.getResolvableType();
|
||||
|
||||
var aggregateDescriptor = new TypeDescriptor(resolvableType.getGeneric(0), null, targetType.getAnnotations());
|
||||
var identifierDescriptor = new TypeDescriptor(resolvableType.getGeneric(1), null, targetType.getAnnotations());
|
||||
|
||||
Function<Object, Object> aggregateResolver = it -> conversionService.get().convert(it, sourceType,
|
||||
aggregateDescriptor);
|
||||
Function<Object, Object> identifierResolver = it -> conversionService.get().convert(it, sourceType,
|
||||
identifierDescriptor);
|
||||
|
||||
var result = new ResolvingAggregateReference<>(uri, aggregateResolver, identifierResolver);
|
||||
|
||||
return JMOLECULES_PRESENT && resolvableType.toClass().equals(ASSOCIATION_AGGREGATE_REFERENCE_TYPE) //
|
||||
? withJMolecules(result) //
|
||||
: result;
|
||||
|
||||
} catch (URISyntaxException e) {
|
||||
throw new ConversionFailedException(sourceType, targetType, source, e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private static AggregateReference<?, ?> withJMolecules(AggregateReference<?, ?> source) {
|
||||
return new ResolvingAssociationAggregateReference(source);
|
||||
}
|
||||
|
||||
/**
|
||||
* An {@link AssociationAggregateReference} delegating to a simple {@link AggregateReference}.
|
||||
*
|
||||
* @author Oliver Drotbohm
|
||||
* @since 4.1
|
||||
*/
|
||||
private static class ResolvingAssociationAggregateReference<T extends AggregateRoot<T, ID>, ID extends Identifier>
|
||||
implements AssociationAggregateReference<T, ID> {
|
||||
|
||||
private AggregateReference<T, ID> delegate;
|
||||
|
||||
ResolvingAssociationAggregateReference(AggregateReference<T, ID> delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public URI getUri() {
|
||||
return delegate.getUri();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ID resolveId() {
|
||||
return delegate.resolveId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T resolveAggregate() {
|
||||
return delegate.resolveAggregate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssociationAggregateReference<T, ID> withIdSource(Function<UriComponents, Object> extractor) {
|
||||
return new ResolvingAssociationAggregateReference<T, ID>(delegate.withIdSource(extractor));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
* Copyright 2023 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
|
||||
*
|
||||
* https://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.webmvc.config;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.jmolecules.ddd.types.Association;
|
||||
import org.jmolecules.ddd.types.Identifier;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.convert.ConversionFailedException;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
import org.springframework.data.rest.core.AggregateReference;
|
||||
import org.springframework.data.rest.core.AssociationAggregateReference;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link StringToAggregateReferenceConverter}.
|
||||
*
|
||||
* @author Oliver Drotbohm
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class StringToAggregateReferenceConverterUnitTests {
|
||||
|
||||
@Mock ConversionService conversionService;
|
||||
|
||||
StringToAggregateReferenceConverter converter = new StringToAggregateReferenceConverter(() -> conversionService);
|
||||
|
||||
@Test // GH-2239
|
||||
void convertsUriIntoAggregateReference() {
|
||||
|
||||
var aggregate = new Object();
|
||||
|
||||
when(conversionService.convert(any(), any(), eq(toTypeDescriptor(Long.class)))).thenReturn(42L);
|
||||
when(conversionService.convert(any(), any(), eq(toTypeDescriptor(Object.class)))).thenReturn(aggregate);
|
||||
|
||||
var source = "/foo/42";
|
||||
|
||||
var result = converter.convert(source, TypeDescriptor.valueOf(String.class),
|
||||
toTypeDescriptor(AggregateReference.class, Object.class, Long.class));
|
||||
|
||||
assertThat(result.getUri()).isEqualTo(URI.create(source));
|
||||
assertThat(result.resolveId()).isEqualTo(42L);
|
||||
assertThat(result.resolveAggregate()).isEqualTo(aggregate);
|
||||
}
|
||||
|
||||
@Test // GH-2239
|
||||
void convertsUriIntoAggregateReferenceUsingCustomExtractor() {
|
||||
|
||||
var aggregate = new Object();
|
||||
|
||||
when(conversionService.convert(any(), any(), eq(toTypeDescriptor(Long.class)))).thenReturn(42L);
|
||||
when(conversionService.convert(any(), any(), eq(toTypeDescriptor(Object.class)))).thenReturn(aggregate);
|
||||
|
||||
var source = "/foo/42";
|
||||
|
||||
var result = converter.convert(source, TypeDescriptor.valueOf(String.class),
|
||||
toTypeDescriptor(AggregateReference.class, Object.class, Long.class));
|
||||
|
||||
result = result.withIdSource(it -> it.getPathSegments().get(1));
|
||||
|
||||
assertThat(result.getUri()).isEqualTo(URI.create(source));
|
||||
assertThat(result.resolveId()).isEqualTo(42L);
|
||||
assertThat(result.resolveAggregate()).isEqualTo(aggregate);
|
||||
}
|
||||
|
||||
@Test // GH-2239
|
||||
void createsAssociationAggregateReference() {
|
||||
|
||||
var identifier = new CustomIdentifier();
|
||||
|
||||
when(conversionService.convert(any(), any(), eq(toTypeDescriptor(CustomIdentifier.class)))).thenReturn(identifier);
|
||||
|
||||
var source = "/foo/42";
|
||||
|
||||
var result = converter.convert(source, TypeDescriptor.valueOf(String.class),
|
||||
toTypeDescriptor(AssociationAggregateReference.class, Object.class, CustomIdentifier.class));
|
||||
|
||||
assertThat(result).isInstanceOfSatisfying(AssociationAggregateReference.class, it -> {
|
||||
assertThat(it.resolveAssociation()).isNotNull()
|
||||
.extracting(Association::getId).isEqualTo(identifier);
|
||||
});
|
||||
}
|
||||
|
||||
@Test // GH-2239
|
||||
void rejectsNullSource() {
|
||||
|
||||
assertThatExceptionOfType(ConversionFailedException.class)
|
||||
.isThrownBy(() -> converter.convert(null, TypeDescriptor.valueOf(String.class),
|
||||
toTypeDescriptor(AggregateReference.class, Object.class, UUID.class)));
|
||||
}
|
||||
|
||||
@Test // GH-2239
|
||||
void rejectsInvalidURI() {
|
||||
|
||||
assertThatExceptionOfType(ConversionFailedException.class)
|
||||
.isThrownBy(() -> converter.convert("@\\", TypeDescriptor.valueOf(String.class),
|
||||
toTypeDescriptor(AggregateReference.class, Object.class, UUID.class)));
|
||||
}
|
||||
|
||||
@Test // GH-2239
|
||||
void registersConversions() {
|
||||
|
||||
var service = new DefaultConversionService();
|
||||
service.addConverter(converter);
|
||||
|
||||
assertThat(service.canConvert(String.class, AggregateReference.class)).isTrue();
|
||||
assertThat(service.canConvert(String.class, AssociationAggregateReference.class)).isTrue();
|
||||
}
|
||||
|
||||
private static TypeDescriptor toTypeDescriptor(Class<?> type, Class<?>... generics) {
|
||||
|
||||
var resolvableType = ResolvableType.forClassWithGenerics(type, generics);
|
||||
|
||||
return new TypeDescriptor(resolvableType, null, null);
|
||||
}
|
||||
|
||||
private static class CustomIdentifier implements Identifier {}
|
||||
}
|
||||
Reference in New Issue
Block a user