Skip to content

Commit

Permalink
Improve custom collection support.
Browse files Browse the repository at this point in the history
Custom collection support is now centralized in ….util.CustomCollections. It exposes API to detect whether a type is a map or collection, identifies the map base type etc.

Support for different collection implementations is externalized via the CustomCollectionRegistrar SPI that allows to define implementations via spring.factories. The current support for Vavr collections has been moved into an implementation of that, VavrCollections.

Unit tests for custom collection handling and conversion previously living in QueryExecutionConverterUnitTests have been moved into CustomCollectionsUnitTests.

Fixes #2619.
  • Loading branch information
odrotbohm committed May 3, 2022
1 parent 87c5e86 commit b3ec06f
Show file tree
Hide file tree
Showing 10 changed files with 838 additions and 430 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,14 @@
package org.springframework.data.convert;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.core.GenericTypeResolver;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.converter.Converter;
Expand All @@ -45,9 +35,9 @@
import org.springframework.data.convert.ConverterBuilder.ConverterAware;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.CustomCollections;
import org.springframework.data.util.Predicates;
import org.springframework.data.util.Streamable;
import org.springframework.data.util.VavrCollectionConverters;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -214,7 +204,7 @@ public void registerConvertersIn(@NonNull ConverterRegistry conversionService) {
Assert.notNull(conversionService, "ConversionService must not be null");

converters.forEach(it -> registerConverterIn(it, conversionService));
VavrCollectionConverters.getConvertersToRegister().forEach(it -> registerConverterIn(it, conversionService));
CustomCollections.registerConvertersIn(conversionService);
}

/**
Expand Down Expand Up @@ -876,7 +866,7 @@ Collection<?> getStoreConverters() {
}

@Override
public boolean equals(Object o) {
public boolean equals(@Nullable Object o) {

if (this == o) {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Stream;

import org.springframework.core.convert.ConversionService;
Expand All @@ -38,12 +39,13 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Slice;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.util.CustomCollections;
import org.springframework.data.util.NullableWrapper;
import org.springframework.data.util.NullableWrapperConverters;
import org.springframework.data.util.StreamUtils;
import org.springframework.data.util.Streamable;
import org.springframework.data.util.TypeInformation;
import org.springframework.data.util.VavrCollectionConverters;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -80,7 +82,7 @@ public abstract class QueryExecutionConverters {

private static final Set<WrapperType> WRAPPER_TYPES = new HashSet<>();
private static final Set<WrapperType> UNWRAPPER_TYPES = new HashSet<WrapperType>();
private static final Set<Converter<Object, Object>> UNWRAPPERS = new HashSet<>();
private static final Set<Function<Object, Object>> UNWRAPPERS = new HashSet<>();
private static final Set<Class<?>> ALLOWED_PAGEABLE_TYPES = new HashSet<>();
private static final Map<Class<?>, ExecutionAdapter> EXECUTION_ADAPTER = new HashMap<>();
private static final Map<Class<?>, Boolean> supportsCache = new ConcurrentReferenceHashMap<>();
Expand All @@ -98,16 +100,19 @@ public abstract class QueryExecutionConverters {

WRAPPER_TYPES.add(NullableWrapperToCompletableFutureConverter.getWrapperType());

if (VAVR_PRESENT) {
UNWRAPPERS.addAll(CustomCollections.getUnwrappers());

CustomCollections.getCustomTypes().stream()
.map(WrapperType::multiValue)
.forEach(WRAPPER_TYPES::add);

WRAPPER_TYPES.add(VavrTraversableUnwrapper.INSTANCE.getWrapperType());
UNWRAPPERS.add(VavrTraversableUnwrapper.INSTANCE);
CustomCollections.getPaginationReturnTypes().forEach(ALLOWED_PAGEABLE_TYPES::add);

if (VAVR_PRESENT) {

// Try support
WRAPPER_TYPES.add(WrapperType.singleValue(io.vavr.control.Try.class));
EXECUTION_ADAPTER.put(io.vavr.control.Try.class, it -> io.vavr.control.Try.of(it::get));

ALLOWED_PAGEABLE_TYPES.add(io.vavr.collection.Seq.class);
}
}

Expand Down Expand Up @@ -195,10 +200,7 @@ public static void registerConvertersIn(ConfigurableConversionService conversion
conversionService.removeConvertible(Collection.class, Object.class);

NullableWrapperConverters.registerConvertersIn(conversionService);

if (VAVR_PRESENT) {
conversionService.addConverter(VavrCollectionConverters.FromJavaConverter.INSTANCE);
}
CustomCollections.registerConvertersIn(conversionService);

conversionService.addConverter(new NullableWrapperToCompletableFutureConverter());
conversionService.addConverter(new NullableWrapperToFutureConverter());
Expand All @@ -220,9 +222,9 @@ public static Object unwrap(@Nullable Object source) {
return source;
}

for (Converter<Object, Object> converter : UNWRAPPERS) {
for (Function<Object, Object> converter : UNWRAPPERS) {

Object result = converter.convert(source);
Object result = converter.apply(source);

if (result != source) {
return result;
Expand Down Expand Up @@ -382,36 +384,6 @@ static WrapperType getWrapperType() {
}
}

/**
* Converter to unwrap Vavr {@link io.vavr.collection.Traversable} instances.
*
* @author Oliver Gierke
* @since 2.0
*/
private enum VavrTraversableUnwrapper implements Converter<Object, Object> {

INSTANCE;

private static final TypeDescriptor OBJECT_DESCRIPTOR = TypeDescriptor.valueOf(Object.class);

@Nullable
@Override
@SuppressWarnings("null")
public Object convert(Object source) {

if (source instanceof io.vavr.collection.Traversable) {
return VavrCollectionConverters.ToJavaConverter.INSTANCE //
.convert(source, TypeDescriptor.forObject(source), OBJECT_DESCRIPTOR);
}

return source;
}

public WrapperType getWrapperType() {
return WrapperType.multiValue(io.vavr.collection.Traversable.class);
}
}

private static class IterableToStreamableConverter implements ConditionalGenericConverter {

private static final TypeDescriptor STREAMABLE = TypeDescriptor.valueOf(Streamable.class);
Expand Down Expand Up @@ -477,7 +449,7 @@ public Cardinality getCardinality() {
}

@Override
public boolean equals(Object o) {
public boolean equals(@Nullable Object o) {

if (this == o) {
return true;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright 2022 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.util;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

import org.springframework.core.convert.converter.ConverterRegistry;

/**
* An SPI to register custom collection types. Implementations need to be registered via
* {@code META-INF/spring.factories}.
*
* @author Oliver Drotbohm
* @since 2.7
*/
public interface CustomCollectionRegistrar {

/**
* Returns whether the registrar is available, meaning whether it can be used at runtime. Primary use is for
* implementations that need to perform a classpath check to prevent the actual methods loading classes that might not
* be available.
*
* @return whether the registrar is available
*/
default boolean isAvailable() {
return true;
}

/**
* Returns all types that are supposed to be considered maps. Primary requirement is key and value generics expressed
* in the first and second generics parameter of the type. Also, the types should be transformable into their
* Java-native equivalent using {@link #toJavaNativeCollection()}.
*
* @return will never be {@literal null}.
* @see #toJavaNativeCollection()
*/
Collection<Class<?>> getMapTypes();

/**
* Returns all types that are supposed to be considered collections. Primary requirement is that their component types
* are expressed as first generics parameter. Also, the types should be transformable into their Java-native
* equivalent using {@link #toJavaNativeCollection()}.
*
* @return will never be {@literal null}.
* @see #toJavaNativeCollection()
*/
Collection<Class<?>> getCollectionTypes();

/**
* Return all types that are considered valid return types for methods using pagination. These are usually collections
* with a stable order, like {@link List} but no {@link Set}s, as pagination usually involves sorting.
*
* @return will never be {@literal null}.
*/
default Collection<Class<?>> getAllowedPaginationReturnTypes() {
return Collections.emptyList();
}

/**
* Register all converters to convert instances of the types returned by {@link #getCollectionTypes()} and
* {@link #getMapTypes()} from an to their Java-native counterparts.
*
* @param registry will never be {@literal null}.
*/
void registerConvertersIn(ConverterRegistry registry);

/**
* Returns a {@link Function} to convert instances of their Java-native counterpart.
*
* @return must not be {@literal null}.
*/
Function<Object, Object> toJavaNativeCollection();
}
Loading

0 comments on commit b3ec06f

Please sign in to comment.