Skip to content

Commit 288f244

Browse files
christophstroblodrotbohm
authored andcommitted
DATAMONGO-1609 - Fix failing tests.
Fix issues pointed out by failing tests. Main focus was to restore functionality and not a Java 8 code cleanup. So, this one still needs some love and polishing.
1 parent 90bb626 commit 288f244

39 files changed

+120
-130
lines changed

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1172,7 +1172,7 @@ protected UpdateResult doUpdate(final String collectionName, final Query query,
11721172
public UpdateResult doInCollection(MongoCollection<Document> collection)
11731173
throws MongoException, DataAccessException {
11741174

1175-
Optional<? extends MongoPersistentEntity<?>> entity = entityClass == null ? null
1175+
Optional<? extends MongoPersistentEntity<?>> entity = entityClass == null ? Optional.empty()
11761176
: getPersistentEntity(entityClass);
11771177

11781178
increaseVersionForUpdateIfNecessary(entity, update);
@@ -2011,7 +2011,9 @@ protected void populateIdIfNecessary(Object savedObject, Object id) {
20112011
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject);
20122012

20132013
Optional<Object> value = accessor.getProperty(idProp);
2014-
value.ifPresent(it -> new ConvertingPropertyAccessor(accessor, conversionService).setProperty(idProp, value));
2014+
if(!value.isPresent()) {
2015+
new ConvertingPropertyAccessor(accessor, conversionService).setProperty(idProp, Optional.of(id));
2016+
}
20152017
});
20162018
}
20172019

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -755,7 +755,7 @@ public Mono<Long> count(final Query query, final Class<?> entityClass, String co
755755

756756
final Document Document = query == null ? null
757757
: queryMapper.getMappedObject(query.getQueryObject(),
758-
entityClass == null ? null : mappingContext.getPersistentEntity(entityClass));
758+
entityClass == null ? Optional.empty() : mappingContext.getPersistentEntity(entityClass));
759759

760760
return collection.count(Document);
761761
});
@@ -976,8 +976,8 @@ private <T> Mono<T> doSaveVersioned(T objectToSave, MongoPersistentEntity<?> ent
976976
ReactiveMongoTemplate.this.assertUpdateableIdIfNotSet(objectToSave);
977977

978978
// Create query for entity with the id and old version
979-
Object id = convertingAccessor.getProperty(idProperty);
980-
Query query = new Query(Criteria.where(idProperty.getName()).is(id).and(versionProperty.getName()).is(version));
979+
Optional<Object> id = convertingAccessor.getProperty(idProperty);
980+
Query query = new Query(Criteria.where(idProperty.getName()).is(id.get()).and(versionProperty.getName()).is(version.get()));
981981

982982
// Bump version number
983983
convertingAccessor.setProperty(versionProperty, Optional.of(versionNumber.orElse(0).longValue() + 1));
@@ -1308,8 +1308,8 @@ private Entry<String, Object> extractIdPropertyAndValue(Object object) {
13081308
throw new MappingException("No id property found for object of type " + objectType);
13091309
}
13101310

1311-
Object idValue = entity.get().getPropertyAccessor(object).getProperty(idProp);
1312-
return Collections.singletonMap(idProp.getFieldName(), idValue).entrySet().iterator().next();
1311+
Optional<Object> idValue = entity.get().getPropertyAccessor(object).getProperty(idProp);
1312+
return Collections.singletonMap(idProp.getFieldName(), idValue.get()).entrySet().iterator().next();
13131313
}
13141314

13151315
/**
@@ -1706,7 +1706,7 @@ private void populateIdIfNecessary(Object savedObject, Object id) {
17061706
MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(savedObject.getClass());
17071707
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject);
17081708

1709-
if (accessor.getProperty(idProp) != null) {
1709+
if (accessor.getProperty(idProp).isPresent()) {
17101710
return;
17111711
}
17121712

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolverCallback.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,6 @@ public DefaultDbRefResolverCallback(Bson surroundingObject, ObjectPath path, SpE
5757
*/
5858
@Override
5959
public Object resolve(MongoPersistentProperty property) {
60-
return resolver.getValueInternal(property, surroundingObject, evaluator, path);
60+
return resolver.getValueInternal(property, surroundingObject, evaluator, path).orElse(null);
6161
}
6262
}

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535

3636
import com.mongodb.BasicDBList;
3737
import com.mongodb.DBObject;
38+
import org.springframework.util.ObjectUtils;
3839

3940
/**
4041
* Default implementation of {@link MongoTypeMapper} allowing configuration of the key to lookup and store type
@@ -108,10 +109,10 @@ public void writeTypeRestrictions(Document result, Set<Class<?>> restrictedTypes
108109

109110
for (Class<?> restrictedType : restrictedTypes) {
110111

111-
Object typeAlias = getAliasFor(ClassTypeInformation.from(restrictedType));
112+
Alias typeAlias = getAliasFor(ClassTypeInformation.from(restrictedType));
112113

113-
if (typeAlias != null) {
114-
restrictedMappedTypes.add(typeAlias);
114+
if (typeAlias != null && !ObjectUtils.nullSafeEquals(Alias.NONE, typeAlias) && typeAlias.getValue().isPresent()) {
115+
restrictedMappedTypes.add(typeAlias.getValue().get());
115116
}
116117
}
117118

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
import org.springframework.data.mapping.model.SpELExpressionEvaluator;
5656
import org.springframework.data.mapping.model.SpELExpressionParameterValueProvider;
5757
import org.springframework.data.mongodb.MongoDbFactory;
58+
import org.springframework.data.mongodb.core.convert.MongoConverters.ObjectIdToBigIntegerConverter;
5859
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
5960
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
6061
import org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent;
@@ -240,7 +241,9 @@ private <S extends Object> S read(TypeInformation<S> type, Bson bson, ObjectPath
240241
}
241242
// Retrieve persistent entity info
242243

243-
return read((MongoPersistentEntity<S>) mappingContext.getRequiredPersistentEntity(typeToUse), (Document) bson,
244+
Document target = bson instanceof BasicDBObject ? new Document((BasicDBObject)bson) : (Document) bson;
245+
246+
return read((MongoPersistentEntity<S>) mappingContext.getRequiredPersistentEntity(typeToUse), target,
244247
path);
245248
}
246249

@@ -271,7 +274,7 @@ private <S extends Object> S read(final MongoPersistentEntity<S> entity, final D
271274
DocumentAccessor documentAccessor = new DocumentAccessor(bson);
272275

273276
// make sure id property is set before all other properties
274-
Object idValue = idProperty.filter(it -> documentAccessor.hasValue(it)).map(it -> {
277+
Optional<Object> idValue = idProperty.filter(it -> documentAccessor.hasValue(it)).map(it -> {
275278

276279
Optional<Object> value = getValueInternal(it, bson, evaluator, path);
277280
accessor.setProperty(it, value);
@@ -280,7 +283,7 @@ private <S extends Object> S read(final MongoPersistentEntity<S> entity, final D
280283
});
281284

282285
final ObjectPath currentPath = path.push(result, entity,
283-
idValue != null ? idProperty.map(it -> bson.get(it.getFieldName())).orElse(null) : null);
286+
idValue.isPresent() ? idProperty.map(it -> bson.get(it.getFieldName())).orElse(null) : null);
284287

285288
// Set properties not already set in the constructor
286289
entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
@@ -867,7 +870,7 @@ protected DBRef createDBRef(Object target, MongoPersistentProperty property) {
867870
}
868871

869872
return dbRefResolver.createDbRef(property == null ? null : property.getDBRef(), entity,
870-
idMapper.convertId(Optional.of(id)));
873+
idMapper.convertId(id instanceof Optional ? (Optional)id : Optional.ofNullable(id)).orElse(null));
871874

872875
}).orElseThrow(() -> new MappingException("No id property found on class " + entity.getType()));
873876
}

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoExampleMapper.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import java.util.List;
2424
import java.util.Map;
2525
import java.util.Map.Entry;
26+
import java.util.Optional;
2627
import java.util.Set;
2728
import java.util.Stack;
2829
import java.util.regex.Pattern;
@@ -98,9 +99,9 @@ public Document getMappedExample(Example<?> example, MongoPersistentEntity<?> en
9899

99100
Document reference = (Document) converter.convertToMongoType(example.getProbe());
100101

101-
Optionals.ifAllPresent(entity.getIdProperty(), //
102-
entity.getIdentifierAccessor(example.getProbe()).getIdentifier(), //
103-
(property, identifier) -> reference.remove(property.getFieldName()));
102+
if(entity.getIdProperty().isPresent() && !entity.getIdentifierAccessor(example.getProbe()).getIdentifier().isPresent()) {
103+
reference.remove(entity.getIdProperty().get().getFieldName());
104+
}
104105

105106
ExampleMatcherAccessor matcherAccessor = new ExampleMatcherAccessor(example.getMatcher());
106107

@@ -241,7 +242,7 @@ private void applyPropertySpecs(String path, Document source, Class<?> probeType
241242
}
242243

243244
private boolean isEmptyIdProperty(Entry<String, Object> entry) {
244-
return entry.getKey().equals("_id") && entry.getValue() == null;
245+
return entry.getKey().equals("_id") && entry.getValue() == null || entry.getValue().equals(Optional.empty());
245246
}
246247

247248
private void applyStringMatcher(Map.Entry<String, Object> entry, StringMatcher stringMatcher, boolean ignoreCase) {

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -318,11 +318,11 @@ protected Object getMappedValue(Field documentField, Object value) {
318318
String inKey = valueDbo.containsField("$in") ? "$in" : "$nin";
319319
List<Object> ids = new ArrayList<Object>();
320320
for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
321-
ids.add(convertId(id));
321+
ids.add(convertId(id).get());
322322
}
323323
resultDbo.put(inKey, ids);
324324
} else if (valueDbo.containsField("$ne")) {
325-
resultDbo.put("$ne", convertId(valueDbo.get("$ne")));
325+
resultDbo.put("$ne", convertId(valueDbo.get("$ne")).get());
326326
} else {
327327
return getMappedObject(resultDbo, Optional.empty());
328328
}
@@ -337,18 +337,18 @@ else if (isDocument(value)) {
337337
String inKey = valueDbo.containsKey("$in") ? "$in" : "$nin";
338338
List<Object> ids = new ArrayList<Object>();
339339
for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
340-
ids.add(convertId(id));
340+
ids.add(convertId(id).orElse(null));
341341
}
342342
resultDbo.put(inKey, ids);
343343
} else if (valueDbo.containsKey("$ne")) {
344-
resultDbo.put("$ne", convertId(valueDbo.get("$ne")));
344+
resultDbo.put("$ne", convertId(valueDbo.get("$ne")).orElse(null));
345345
} else {
346346
return getMappedObject(resultDbo, Optional.empty());
347347
}
348348
return resultDbo;
349349

350350
} else {
351-
return convertId(value);
351+
return convertId(value).orElse(null);
352352
}
353353
}
354354

@@ -461,7 +461,7 @@ protected Object convertAssociation(Object source, MongoPersistentProperty prope
461461
if (source instanceof DBRef) {
462462

463463
DBRef ref = (DBRef) source;
464-
return new DBRef(ref.getCollectionName(), convertId(ref.getId()));
464+
return new DBRef(ref.getCollectionName(), convertId(ref.getId()).get());
465465
}
466466

467467
if (source instanceof Iterable) {
@@ -538,7 +538,7 @@ private DBRef createDbRefFor(Object source, MongoPersistentProperty property) {
538538
}
539539

540540
private Optional<Object> convertId(Object id) {
541-
return convertId(Optional.of(id));
541+
return convertId(Optional.ofNullable(id));
542542
}
543543

544544
/**
@@ -857,7 +857,7 @@ public MongoPersistentProperty getProperty() {
857857
@Override
858858
public MongoPersistentEntity<?> getPropertyEntity() {
859859
MongoPersistentProperty property = getProperty();
860-
return property == null ? null : mappingContext.getRequiredPersistentEntity(property);
860+
return property == null ? null : mappingContext.getPersistentEntity(property).orElse(null);
861861
}
862862

863863
/*

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ private void checkForIndexes(final MongoPersistentEntity<?> entity) {
131131

132132
private void checkForAndCreateIndexes(MongoPersistentEntity<?> entity) {
133133

134-
if (entity.findAnnotation(Document.class) != null) {
134+
if (entity.findAnnotation(Document.class).isPresent()) {
135135
for (IndexDefinitionHolder indexToCreate : indexResolver.resolveIndexFor(entity.getTypeInformation())) {
136136
createIndex(indexToCreate);
137137
}

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexResolver.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,13 +261,13 @@ public void doWithPersistentProperty(MongoPersistentProperty persistentProperty)
261261
String propertyDotPath = (StringUtils.hasText(dotPath) ? dotPath + "." : "")
262262
+ persistentProperty.getFieldName();
263263

264-
Float weight = indexed != null ? indexed.get().weight()
264+
Float weight = indexed.isPresent() ? indexed.get().weight()
265265
: (includeOptions.getParentFieldSpec() != null ? includeOptions.getParentFieldSpec().getWeight() : 1.0F);
266266

267267
if (persistentProperty.isEntity()) {
268268

269269
TextIndexIncludeOptions optionsForNestedType = includeOptions;
270-
if (!IncludeStrategy.FORCE.equals(includeOptions.getStrategy()) && indexed != null) {
270+
if (!IncludeStrategy.FORCE.equals(includeOptions.getStrategy()) && indexed.isPresent()) {
271271
optionsForNestedType = new TextIndexIncludeOptions(IncludeStrategy.FORCE,
272272
new TextIndexedFieldSpec(propertyDotPath, weight));
273273
}
@@ -281,7 +281,7 @@ public void doWithPersistentProperty(MongoPersistentProperty persistentProperty)
281281
LOGGER.info(String.format("Potentially invalid index structure discovered. Breaking operation for %s.",
282282
entity.getName()), e);
283283
}
284-
} else if (includeOptions.isForce() || indexed != null) {
284+
} else if (includeOptions.isForce() || indexed.isPresent()) {
285285
indexDefinitionBuilder.onField(propertyDotPath, weight);
286286
}
287287
}

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.springframework.data.geo.Metrics;
2626
import org.springframework.data.geo.Point;
2727
import org.springframework.util.Assert;
28+
import org.springframework.util.ObjectUtils;
2829

2930
/**
3031
* Builder class to build near-queries.
@@ -150,8 +151,10 @@ public NearQuery skip(long skip) {
150151
public NearQuery with(Pageable pageable) {
151152

152153
Assert.notNull(pageable, "Pageable must not be 'null'.");
153-
this.num = pageable.getOffset() + pageable.getPageSize();
154-
this.skip = pageable.getOffset();
154+
if(!ObjectUtils.nullSafeEquals(Pageable.NONE, pageable)) {
155+
this.num = pageable.getOffset() + pageable.getPageSize();
156+
this.skip = pageable.getOffset();
157+
}
155158
return this;
156159
}
157160

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import org.springframework.data.domain.Sort.Order;
3434
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
3535
import org.springframework.util.Assert;
36+
import org.springframework.util.ObjectUtils;
3637

3738
/**
3839
* @author Thomas Risberg
@@ -151,7 +152,7 @@ public Query withHint(String name) {
151152
*/
152153
public Query with(Pageable pageable) {
153154

154-
if (pageable == null) {
155+
if (pageable == null || ObjectUtils.nullSafeEquals(Pageable.NONE, pageable)) {
155156
return this;
156157
}
157158

@@ -169,7 +170,7 @@ public Query with(Pageable pageable) {
169170
*/
170171
public Query with(Sort sort) {
171172

172-
if (sort == null) {
173+
if (sort == null || ObjectUtils.nullSafeEquals(Sort.unsorted(), sort)) {
173174
return this;
174175
}
175176

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryBean.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,6 @@ protected T create(CreationalContext<T> creationalContext, Class<T> repositoryTy
6868
MongoOperations mongoOperations = getDependencyInstance(operations, MongoOperations.class);
6969
MongoRepositoryFactory factory = new MongoRepositoryFactory(mongoOperations);
7070

71-
return factory.getRepository(repositoryType, customImplementation);
71+
return customImplementation.isPresent() ? factory.getRepository(repositoryType, customImplementation.get()) : factory.getRepository(repositoryType);
7272
}
7373
}

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbQuery.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package org.springframework.data.mongodb.repository.support;
1717

18+
import org.bson.Document;
1819
import org.springframework.data.mongodb.core.MongoOperations;
1920
import org.springframework.data.mongodb.core.MongoTemplate;
2021

@@ -58,7 +59,9 @@ public SpringDataMongodbQuery(final MongoOperations operations, final Class<? ex
5859

5960
@Override
6061
public T apply(DBObject input) {
61-
return operations.getConverter().read(type, (BasicDBObject) input);
62+
63+
;
64+
return operations.getConverter().read(type, new Document((BasicDBObject) input));
6265
}
6366
}, new SpringDataMongodbSerializer(operations.getConverter()));
6467

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbSerializer.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,8 @@ protected String getKeyForPath(Path<?> expr, PathMetadata metadata) {
120120
@Override
121121
protected DBObject asDBObject(String key, Object value) {
122122

123+
value = value instanceof Optional ? ((Optional)value).orElse(null) : value;
124+
123125
if (ID_KEY.equals(key)) {
124126
DBObject superIdValue = super.asDBObject(key, value);
125127
Document mappedIdValue = mapper.getMappedObject((BasicDBObject) superIdValue, Optional.empty());

spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AuditingViaJavaConfigRepositoriesTests.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
import static org.junit.Assert.*;
2020
import static org.mockito.Mockito.*;
2121

22+
import java.util.Optional;
23+
2224
import org.junit.Before;
2325
import org.junit.Test;
2426
import org.junit.runner.RunWith;
@@ -82,7 +84,7 @@ public void setup() {
8284
@Test // DATAMONGO-792, DATAMONGO-883
8385
public void basicAuditing() {
8486

85-
doReturn(this.auditor).when(this.auditorAware).getCurrentAuditor();
87+
doReturn(Optional.of(this.auditor)).when(this.auditorAware).getCurrentAuditor();
8688

8789
AuditablePerson savedUser = auditablePersonRepository.save(new AuditablePerson("user"));
8890

0 commit comments

Comments
 (0)