Skip to content

Introduce MongoConverterConfigurationAdapter#withPropertyValueConversions. #4556

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.2.0-SNAPSHOT</version>
<version>4.2.x-4555-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data MongoDB</name>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-benchmarks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.2.0-SNAPSHOT</version>
<version>4.2.x-4555-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.2.0-SNAPSHOT</version>
<version>4.2.x-4555-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.2.0-SNAPSHOT</version>
<version>4.2.x-4555-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,8 @@ protected Object decorate(Object target) {

private static boolean requiresSession(Method method) {

if (method.getParameterCount() == 0
|| !ClassUtils.isAssignable(ClientSession.class, method.getParameterTypes()[0])) {
return true;
}

return false;
return method.getParameterCount() == 0
|| !ClassUtils.isAssignable(ClientSession.class, method.getParameterTypes()[0]);
}

private static Object[] prependSessionToArguments(ClientSession session, MethodInvocation invocation) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ public enum SessionSynchronization {
*
* @since 3.2.5
*/
NEVER;
NEVER
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
public class MongoAotPredicates {

public static final Predicate<Class<?>> IS_SIMPLE_TYPE = (type) -> MongoSimpleTypes.HOLDER.isSimpleType(type) || TypeUtils.type(type).isPartOf("org.bson");
public static final Predicate<ReactiveLibrary> IS_REACTIVE_LIBARARY_AVAILABLE = (lib) -> ReactiveWrappers.isAvailable(lib);
public static final Predicate<ReactiveLibrary> IS_REACTIVE_LIBARARY_AVAILABLE = ReactiveWrappers::isAvailable;
public static final Predicate<ClassLoader> IS_SYNC_CLIENT_PRESENT = (classLoader) -> ClassUtils.isPresent("com.mongodb.client.MongoClient", classLoader);

public static boolean isReactorPresent() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
import static org.springframework.data.mongodb.config.BeanNames.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

Expand Down Expand Up @@ -63,7 +61,6 @@
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;

import org.w3c.dom.Element;

/**
Expand Down Expand Up @@ -97,7 +94,7 @@ public BeanDefinition parse(Element element, ParserContext parserContext) {
id = StringUtils.hasText(id) ? id : DEFAULT_CONVERTER_BEAN_NAME;

String autoIndexCreation = element.getAttribute("auto-index-creation");
boolean autoIndexCreationEnabled = StringUtils.hasText(autoIndexCreation) && Boolean.valueOf(autoIndexCreation);
boolean autoIndexCreationEnabled = StringUtils.hasText(autoIndexCreation) && Boolean.parseBoolean(autoIndexCreation);

parserContext.pushContainingComponent(new CompositeComponentDefinition("Mapping Mongo Converter", element));

Expand Down Expand Up @@ -371,7 +368,7 @@ public NegatingFilter(TypeFilter... filters) {

Assert.notNull(filters, "TypeFilters must not be null");

this.delegates = new HashSet<>(Arrays.asList(filters));
this.delegates = Set.of(filters);
}

public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
package org.springframework.data.mongodb.config;

import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Expand Down Expand Up @@ -228,10 +228,6 @@ private static void verifyUserNamePresent(String[] source) {
}

private static String decodeParameter(String it) {
try {
return URLDecoder.decode(it, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("o_O UTF-8 not supported", e);
}
return URLDecoder.decode(it, StandardCharsets.UTF_8);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
import static org.springframework.data.config.ParsingUtils.*;
import static org.springframework.data.mongodb.config.MongoParsingUtils.*;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.BeanDefinitionStoreException;
Expand Down Expand Up @@ -51,16 +49,7 @@
*/
public class MongoDbFactoryParser extends AbstractBeanDefinitionParser {

private static final Set<String> MONGO_URI_ALLOWED_ADDITIONAL_ATTRIBUTES;

static {

Set<String> mongoUriAllowedAdditionalAttributes = new HashSet<String>();
mongoUriAllowedAdditionalAttributes.add("id");
mongoUriAllowedAdditionalAttributes.add("write-concern");

MONGO_URI_ALLOWED_ADDITIONAL_ATTRIBUTES = Collections.unmodifiableSet(mongoUriAllowedAdditionalAttributes);
}
private static final Set<String> MONGO_URI_ALLOWED_ADDITIONAL_ATTRIBUTES = Set.of("id", "write-concern");

@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@
*/
class AggregationUtil {

QueryMapper queryMapper;
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
Lazy<AggregationOperationContext> untypedMappingContext;
final QueryMapper queryMapper;
final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
final Lazy<AggregationOperationContext> untypedMappingContext;

AggregationUtil(QueryMapper queryMapper,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ enum BulkMode {

/** Perform bulk operations in parallel. Processing will continue on errors. */
UNORDERED
};
}

/**
* Add a single insert to the bulk operation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public static ChangeStreamOptions empty() {

/**
* Obtain a shiny new {@link ChangeStreamOptionsBuilder} and start defining options in this fancy fluent way. Just
* don't forget to call {@link ChangeStreamOptionsBuilder#build() build()} when your're done.
* don't forget to call {@link ChangeStreamOptionsBuilder#build() build()} when done.
*
* @return new instance of {@link ChangeStreamOptionsBuilder}.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public interface CursorPreparer extends ReadPreferenceAware {
FindIterable<Document> prepare(FindIterable<Document> iterable);

/**
* Apply query specific settings to {@link MongoCollection} and initate a find operation returning a
* Apply query specific settings to {@link MongoCollection} and initiate a find operation returning a
* {@link FindIterable} via the given {@link Function find} function.
*
* @param collection must not be {@literal null}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

/**
* An interface used by {@link MongoTemplate} for processing documents returned from a MongoDB query on a per-document
* basis. Implementations of this interface perform the actual work of prcoessing each document but don't need to worry
* basis. Implementations of this interface perform the actual work of processing each document but don't need to worry
* about exception handling. {@link MongoException}s will be caught and translated by the calling MongoTemplate An
* DocumentCallbackHandler is typically stateful: It keeps the result state within the object, to be available later for
* later inspection.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ private Object resolveValue(String key, @Nullable MongoPersistentEntity<?> sourc
PropertyPath from = PropertyPath.from(key, sourceEntity.getTypeInformation());
PersistentPropertyPath<MongoPersistentProperty> persistentPropertyPath = entityOperations.context
.getPersistentPropertyPath(from);
return BsonUtils.resolveValue(map, persistentPropertyPath.toDotPath(p -> p.getFieldName()));
return BsonUtils.resolveValue(map, persistentPropertyPath.toDotPath(MongoPersistentProperty::getFieldName));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public interface FindPublisherPreparer extends ReadPreferenceAware {
FindPublisher<Document> prepare(FindPublisher<Document> findPublisher);

/**
* Apply query specific settings to {@link MongoCollection} and initate a find operation returning a
* Apply query specific settings to {@link MongoCollection} and initiate a find operation returning a
* {@link FindPublisher} via the given {@link Function find} function.
*
* @param collection must not be {@literal null}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public void updateId(Object value) {
* @author Christoph Strobl
* @since 2.2
*/
class MappedUpdate implements UpdateDefinition {
static class MappedUpdate implements UpdateDefinition {

private final Update delegate;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public PropertySpecifier property(String path) {
}

/**
* Specify additional types to be considered wehen rendering the schema for the given path.
* Specify additional types to be considered when rendering the schema for the given path.
*
* @param path path the path using {@literal dot '.'} notation.
* @param types must not be {@literal null}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@
*/
public enum MongoActionOperation {

REMOVE, UPDATE, INSERT, INSERT_LIST, SAVE, BULK, REPLACE;
REMOVE, UPDATE, INSERT, INSERT_LIST, SAVE, BULK, REPLACE
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public WriteConcernResult getWriteResult() {
}

/**
* Returns the {@link MongoActionOperation} in which the current exception occured.
* Returns the {@link MongoActionOperation} in which the current exception occurred.
*
* @return the actionOperation
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,9 @@
*/
package org.springframework.data.mongodb.core;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.bson.BsonInvalidOperationException;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
Expand Down Expand Up @@ -55,18 +51,17 @@
*/
public class MongoExceptionTranslator implements PersistenceExceptionTranslator {

private static final Set<String> DUPLICATE_KEY_EXCEPTIONS = new HashSet<>(
Arrays.asList("MongoException.DuplicateKey", "DuplicateKeyException"));
private static final Set<String> DUPLICATE_KEY_EXCEPTIONS = Set.of("MongoException.DuplicateKey",
"DuplicateKeyException");

private static final Set<String> RESOURCE_FAILURE_EXCEPTIONS = new HashSet<>(
Arrays.asList("MongoException.Network", "MongoSocketException", "MongoException.CursorNotFound",
"MongoCursorNotFoundException", "MongoServerSelectionException", "MongoTimeoutException"));
private static final Set<String> RESOURCE_FAILURE_EXCEPTIONS = Set.of("MongoException.Network",
"MongoSocketException", "MongoException.CursorNotFound", "MongoCursorNotFoundException",
"MongoServerSelectionException", "MongoTimeoutException");

private static final Set<String> RESOURCE_USAGE_EXCEPTIONS = new HashSet<>(
Collections.singletonList("MongoInternalException"));
private static final Set<String> RESOURCE_USAGE_EXCEPTIONS = Set.of("MongoInternalException");

private static final Set<String> DATA_INTEGRITY_EXCEPTIONS = new HashSet<>(
Arrays.asList("WriteConcernException", "MongoWriteException", "MongoBulkWriteException"));
private static final Set<String> DATA_INTEGRITY_EXCEPTIONS = Set.of("WriteConcernException", "MongoWriteException",
"MongoBulkWriteException");

private static final Set<String> SECURITY_EXCEPTIONS = Set.of("MongoCryptException");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1379,12 +1379,7 @@ protected <T> Collection<T> doInsertAll(Collection<? extends T> listToSave, Mong
}

String collection = getCollectionName(ClassUtils.getUserClass(element));
List<T> collectionElements = elementsByCollection.get(collection);

if (null == collectionElements) {
collectionElements = new ArrayList<>();
elementsByCollection.put(collection, collectionElements);
}
List<T> collectionElements = elementsByCollection.computeIfAbsent(collection, k -> new ArrayList<>());

collectionElements.add(element);
}
Expand Down Expand Up @@ -2315,11 +2310,9 @@ public <T> ExecutableInsert<T> insert(Class<T> domainType) {

protected String replaceWithResourceIfNecessary(String function) {

String func = function;

if (this.resourceLoader != null && ResourceUtils.isUrl(function)) {

Resource functionResource = resourceLoader.getResource(func);
Resource functionResource = resourceLoader.getResource(function);

if (!functionResource.exists()) {
throw new InvalidDataAccessApiUsageException(String.format("Resource %s not found", function));
Expand All @@ -2339,7 +2332,7 @@ protected String replaceWithResourceIfNecessary(String function) {
}
}

return func;
return function;
}

@Override
Expand Down Expand Up @@ -2698,8 +2691,6 @@ Document getMappedValidator(Validator validator, Class<?> domainType) {
protected <T> T doFindAndRemove(CollectionPreparer collectionPreparer, String collectionName, Document query,
Document fields, Document sort, @Nullable Collation collation, Class<T> entityClass) {

EntityReader<? super T, Bson> readerToUse = this.mongoConverter;

if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("findAndRemove using query: %s fields: %s sort: %s for class: %s in collection: %s",
serializeToJsonSafely(query), fields, sort, entityClass, collectionName));
Expand All @@ -2709,16 +2700,14 @@ protected <T> T doFindAndRemove(CollectionPreparer collectionPreparer, String co

return executeFindOneInternal(new FindAndRemoveCallback(collectionPreparer,
queryMapper.getMappedObject(query, entity), fields, sort, collation),
new ReadDocumentCallback<>(readerToUse, entityClass, collectionName), collectionName);
new ReadDocumentCallback<>(this.mongoConverter, entityClass, collectionName), collectionName);
}

@SuppressWarnings("ConstantConditions")
protected <T> T doFindAndModify(CollectionPreparer collectionPreparer, String collectionName, Document query,
Document fields, Document sort, Class<T> entityClass, UpdateDefinition update,
@Nullable FindAndModifyOptions options) {

EntityReader<? super T, Bson> readerToUse = this.mongoConverter;

if (options == null) {
options = new FindAndModifyOptions();
}
Expand All @@ -2742,7 +2731,7 @@ protected <T> T doFindAndModify(CollectionPreparer collectionPreparer, String co
return executeFindOneInternal(
new FindAndModifyCallback(collectionPreparer, mappedQuery, fields, sort, mappedUpdate,
update.getArrayFilters().stream().map(ArrayFilter::asDocument).collect(Collectors.toList()), options),
new ReadDocumentCallback<>(readerToUse, entityClass, collectionName), collectionName);
new ReadDocumentCallback<>(this.mongoConverter, entityClass, collectionName), collectionName);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ Document getMappedSort(@Nullable MongoPersistentEntity<?> entity) {
* @param consumer must not be {@literal null}.
*/
void applyCollation(@Nullable Class<?> domainType, Consumer<com.mongodb.client.model.Collation> consumer) {
getCollation(domainType).ifPresent(consumer::accept);
getCollation(domainType).ifPresent(consumer);
}

/**
Expand Down Expand Up @@ -526,7 +526,7 @@ <T> Class<T> getDriverCompatibleClass(Class<T> type) {
}

/**
* Get the most speficic read target type based on the user {@literal requestedTargetType} an the property type
* Get the most specific read target type based on the user {@literal requestedTargetType} an the property type
* based on meta information extracted from the {@literal domainType}.
*
* @param requestedTargetType must not be {@literal null}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1810,8 +1810,7 @@ protected Mono<UpdateResult> doUpdate(String collectionName, Query query, @Nulla

Document updateObj = updateContext.getMappedUpdate(entity);
if (containsVersionProperty(queryObj, entity))
throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: "
+ updateObj.toString() + " to collection " + collectionName);
throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity %s to collection %s".formatted(entity.getName(), collectionName));
}
}
});
Expand Down
Loading