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:
Oliver Drotbohm
2023-03-11 23:50:05 +01:00
parent 6d0034f15f
commit e4bca534bf
21 changed files with 1025 additions and 129 deletions

View File

@@ -0,0 +1,48 @@
/*
* 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.core;
import static org.assertj.core.api.Assertions.*;
import java.net.URI;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link ResolvingAggregateReference}.
*
* @author Oliver Drotbohm
*/
class ResolvingAggregateReferenceUnitTests {
@Test // GH-2239
void usesResolverForFinalInstanceLookup() {
var reference = new ResolvingAggregateReference<>(URI.create("/foo/42"), it -> "aggregate", it -> 42L);
assertThat(reference.resolveAggregate()).isEqualTo("aggregate");
assertThat(reference.resolveId()).isEqualTo(42);
}
@Test // GH-2239
void appliesCustomExtractor() {
var reference = new ResolvingAggregateReference<>(URI.create("/foo/42"), it -> "aggregate",
it -> Long.valueOf(it.toString())).withIdSource(it -> it.getPathSegments().get(1));
assertThat(reference.resolveId()).isEqualTo(42);
}
}

View File

@@ -18,29 +18,37 @@ package org.springframework.data.rest.core;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import lombok.Value;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import org.jmolecules.ddd.types.AggregateRoot;
import org.jmolecules.ddd.types.Association;
import org.jmolecules.ddd.types.Identifier;
import org.jmolecules.spring.PrimitivesToAssociationConverter;
import org.junit.jupiter.api.BeforeEach;
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.converter.GenericConverter.ConvertiblePair;
import org.springframework.data.annotation.Id;
import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.repository.core.RepositoryInformation;
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.rest.core.UriToEntityConverterUnitTests.JMoleculesAggregateRoot.JMoleculesIdentifier;
import org.springframework.data.util.Streamable;
import org.springframework.data.util.TypeInformation;
import org.springframework.format.support.DefaultFormattingConversionService;
/**
* Unit tests for {@link UriToEntityConverter}.
@@ -53,22 +61,28 @@ class UriToEntityConverterUnitTests {
static final TypeDescriptor URI_TYPE = TypeDescriptor.valueOf(URI.class);
static final TypeDescriptor STRING_TYPE = TypeDescriptor.valueOf(String.class);
static final TypeDescriptor ENTITY_TYPE = TypeDescriptor.valueOf(Entity.class);
static final TypeDescriptor UUID_ENTITY_TYPE = TypeDescriptor.valueOf(UuidEntity.class);
static final TypeDescriptor UUID_TYPE = TypeDescriptor.valueOf(UUID.class);
static final TypeDescriptor UNKNOWN_TYPE = TypeDescriptor.valueOf(Override.class);
@Mock Repositories repositories;
@Mock RepositoryInvokerFactory invokerFactory;
KeyValueMappingContext<?, ?> context;
UriToEntityConverter converter;
ConversionService conversionService;
@BeforeEach
void setUp() {
var conversionService = new DefaultFormattingConversionService();
conversionService.addConverter(new PrimitivesToAssociationConverter(() -> conversionService));
this.context = new KeyValueMappingContext<>();
this.context.setInitialEntitySet(new HashSet<Class<?>>(Arrays.asList(Entity.class, NonEntity.class)));
this.context.setInitialEntitySet(Set.of(Entity.class, NonEntity.class, UuidEntity.class));
this.context.afterPropertiesSet();
this.converter = new UriToEntityConverter(new PersistentEntities(Arrays.asList(this.context)), invokerFactory,
repositories);
this.converter = new UriToEntityConverter(new PersistentEntities(List.of(this.context)), invokerFactory,
() -> conversionService);
}
@Test // DATAREST-427
@@ -80,25 +94,6 @@ class UriToEntityConverterUnitTests {
assertThat(result).doesNotContain(new ConvertiblePair(URI.class, NonEntity.class));
}
@Test // DATAREST-427
void cannotConvertEntityWithIdPropertyIfStringConversionMissing() {
assertThat(converter.matches(URI_TYPE, ENTITY_TYPE)).isFalse();
}
@Test // DATAREST-427
void canConvertEntityWithIdPropertyAndFromStringConversionPossible() {
doReturn(Optional.of(mock(RepositoryInformation.class))).when(repositories)
.getRepositoryInformationFor(ENTITY_TYPE.getType());
assertThat(converter.matches(URI_TYPE, ENTITY_TYPE)).isTrue();
}
@Test // DATAREST-427
void cannotConvertEntityWithoutIdentifier() {
assertThat(converter.matches(URI_TYPE, TypeDescriptor.valueOf(NonEntity.class))).isFalse();
}
@Test // DATAREST-427
void invokesConverterWithLastUriPathSegment() {
@@ -115,7 +110,7 @@ class UriToEntityConverterUnitTests {
void rejectsUnknownType() {
assertThatExceptionOfType(ConversionFailedException.class) //
.isThrownBy(() -> converter.convert(URI.create("/foo/1"), URI_TYPE, STRING_TYPE));
.isThrownBy(() -> converter.convert(URI.create("/foo/1"), URI_TYPE, UNKNOWN_TYPE));
}
@Test // DATAREST-427
@@ -129,18 +124,19 @@ class UriToEntityConverterUnitTests {
void rejectsNullPersistentEntities() {
assertThatIllegalArgumentException() //
.isThrownBy(() -> new UriToEntityConverter(null, invokerFactory, repositories));
.isThrownBy(
() -> new UriToEntityConverter(null, invokerFactory, () -> conversionService));
}
@Test // DATAREST-741
void rejectsNullRepositoryInvokerFactory() {
assertThatIllegalArgumentException() //
.isThrownBy(() -> new UriToEntityConverter(mock(PersistentEntities.class), null, repositories));
.isThrownBy(() -> new UriToEntityConverter(mock(PersistentEntities.class), null, () -> conversionService));
}
@Test // DATAREST-741
void rejectsNullRepositories() {
void rejectsNullConversionService() {
assertThatIllegalArgumentException() //
.isThrownBy(() -> new UriToEntityConverter(mock(PersistentEntities.class), invokerFactory, null));
@@ -153,16 +149,59 @@ class UriToEntityConverterUnitTests {
void doesNotRegisterTypeWithUnmanagedRawType() {
PersistentEntities entities = mock(PersistentEntities.class);
doReturn(Streamable.of(ClassTypeInformation.OBJECT)).when(entities).getManagedTypes();
doReturn(Streamable.of(TypeInformation.OBJECT)).when(entities).getManagedTypes();
new UriToEntityConverter(entities, invokerFactory, repositories);
new UriToEntityConverter(entities, invokerFactory, () -> conversionService);
}
@Test
void resolvesIdentifierType() {
var uuid = UUID.randomUUID();
assertThat(converter.convert(URI.create("/foo/" + uuid), STRING_TYPE, UUID_TYPE)).isEqualTo(uuid);
}
@Test
void resolvesAssociations() {
var typeDescriptor = new TypeDescriptor(
ResolvableType.forClassWithGenerics(Association.class, JMoleculesAggregateRoot.class,
JMoleculesIdentifier.class),
null, null);
var uuid = UUID.randomUUID();
assertThat(converter.convert(URI.create("/foo/" + uuid), URI_TYPE, typeDescriptor))
.isInstanceOfSatisfying(Association.class, it -> {
assertThat(it.getId()).isEqualTo(JMoleculesIdentifier.of(uuid));
});
}
static class Entity {
@Id String id;
}
static class UuidEntity {
@Id UUID id;
}
static class NonEntity {
String value;
}
static class JMoleculesAggregateRoot implements AggregateRoot<JMoleculesAggregateRoot, JMoleculesIdentifier> {
@Override
public JMoleculesIdentifier getId() {
return JMoleculesIdentifier.of(UUID.randomUUID());
}
@Value(staticConstructor = "of")
static class JMoleculesIdentifier implements Identifier {
UUID id;
}
}
private static void someMethod(Association<JMoleculesAggregateRoot, JMoleculesIdentifier> association) {}
}